【发布时间】:2018-06-26 00:37:47
【问题描述】:
编辑:
我进一步深入研究了问题,结果发现即使使用单一配置,问题仍然存在。如果我使用单一配置并保持
http.antMatcher("/api/test/**")
网址没有得到保护。 删除 antMatcher 和 antMatchers 会立即保护 url。 即如果我使用:
http.httpBasic()
.and()
.authorizeRequests()
.anyRequest()
.authenticated();
那么只有 spring security 会保护 url。为什么 antMatcher 不起作用?
(更新了标题以包含实际问题。)
原帖:
我提到了以下 stackoverflow 问题:
和 spring 安全文档:
https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#multiple-httpsecurity
但我无法配置多个 http 安全元素。 当我遵循官方 spring 文档时,它在我的情况下有效,只是因为第二个 http 安全元素是一个包罗万象的事实,但是一旦我添加了一个特定的 url,所有的 url 都可以在没有任何身份验证的情况下访问。
这是我的代码:
@EnableWebSecurity
@Configuration
public class SecurityConfig {
@Bean
public UserDetailsService userDetailsService() throws Exception {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withUsername("user").password("userPass").roles("USER").build());
manager.createUser(User.withUsername("admin").password("adminPass").roles("ADMIN").build());
return manager;
}
@Configuration
@Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
@Override
public void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("user").password("user").roles("USER");
auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
}
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/v1/**")
.authorizeRequests()
.antMatchers("/api/v1/**").authenticated()
.and()
.httpBasic();
}
}
@Configuration
@Order(2)
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Override
public void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("user1").password("user").roles("USER");
auth.inMemoryAuthentication().withUser("admin1").password("admin").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/test/**")
.authorizeRequests()
.antMatchers("/api/test/**").authenticated()
.and()
.formLogin();
}
}
}
现在可以访问任何网址。如果我从第二个配置中删除 antMatcher,所有 url 都会变得安全。
【问题讨论】:
-
只要移除/添加 antMatcher,相同的 url 就会变得安全和不安全。例如如果我访问 localhost:8100/api/test/hello,只有在没有 antMatcher 行时才会提示我输入用户名密码。
-
api 是我的上下文根。我试过starstartest/starstar,但它也不起作用(使用wildchar * word star。Stackoverflow Android应用正在将wildchar转换为粗体格式。在测试之前和之后使用双星/)
标签: java spring spring-security