【发布时间】:2019-07-25 18:16:20
【问题描述】:
我的问题是这样的:
我想通过扩展 WebSecurityConfigurerAdapter 的类中的配置来禁用和启用身份验证。我有一个测试,如果没有提供登录信息,它预计状态是未经授权的。这是配置类:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
public static final String USER = "workshop-user";
public static final String ADMIN = "workshop-admin";
@Value("${WORKSHOP_USER_PASSWORD:user}")
private String userPassword;
@Value("${WORKSHOP_ADMIN_PASSWORD:admin}")
private String administratorPassword;
@Value("${features.security.disable}")
private boolean securityDisable;
@Bean
public BCryptPasswordEncoder encoder() {
return new BCryptPasswordEncoder(9);
}
@Override
@Bean
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser(USER)
.password(encoder().encode(userPassword))
.roles("CLIENT_APP")
.and()
.withUser(ADMIN)
.password(encoder().encode(administratorPassword))
.roles("CLIENT_APP", "ADMINISTRATOR");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
if(!securityDisable) {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/**/import").hasRole("ADMINISTRATOR")
.antMatchers("/api-docs/**", "/swagger-resources/**", "/v2/api-docs", "/**/favicon.ico", "/webjars/**", "/api/admin/health").permitAll()
.anyRequest().permitAll()
//replace .permitAll() with .authenticated() for authentiaction
//replace .authenticated() with .permitAll() for disabling security
.and()
.csrf().disable()
.headers().disable()
.httpBasic();
}
else{
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/**/import").hasRole("ADMINISTRATOR")
.antMatchers("/api-docs/**", "/swagger-resources/**", "/v2/api-docs", "/**/favicon.ico", "/webjars/**", "/api/admin/health").permitAll()
.anyRequest().authenticated()
//replace .permitAll() with .authenticated() for authentiaction
//replace .authenticated() with .permitAll() for disabling security
.and()
.csrf().disable()
.headers().disable()
.httpBasic();
}
}
这是我在 application.properties 中的标志
features.security.disable = true
我试图通过配置找到另一种方法,但无法找到另一个答案。问题是我知道这很简单,因为 if/else 语句。一个是经过身份验证的,另一个是 permitAll 条目。你知道有没有一种使用“更好的方法”的方法,它不会像这样重复污染代码?我试图查看文档和其他帖子,但找不到任何相关信息。
【问题讨论】:
-
我认为出于测试目的,不包括 SecurityAutoConfiguration 比你的方法更好,@SpringBootApplication(exclude = {SecurityAutoConfiguration.class} ) public class SpringBootTest{}
-
另一种方法是使用单独的配置文件
-
那么创建另一个配置方法并使用我创建的这个标志在他们两个上使用配置文件?因为我希望可以选择使用属性中的标志在禁用和启用安全性之间进行选择,这就是我不想使用排除选项的原因。
-
请检查我的答案
标签: java spring spring-boot spring-security