Spring安全性配置:启用/禁用身份验证

时间:2019-03-04 12:21:07

标签: java spring spring-boot spring-security

我的问题是这样的:

我想通过扩展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语句。一个被认证,另一个被许可。您是否知道有一种方法可以使用“更好的方式”来避免重复代码污染代码?我试图查看文档和其他帖子,但找不到与我有关的任何信息。

1 个答案:

答案 0 :(得分:0)

您可以创建两个安全配置

@Configuration
@Profile("prod")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        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();
    }
}


@Configuration
@Profile("test")
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        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();
    }
}

根据您的要求运行

-Dspring.profiles.active=prod
-Dspring.profiles.active=test