【问题标题】:Spring security configuration: enable/disable authenticationSpring 安全配置:启用/禁用身份验证
【发布时间】: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


【解决方案1】:

您可以创建两个安全配置

@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

【讨论】:

  • 此外,由于 OP 要求根据其应用程序属性中设置的属性切换安全机制。您可以结合此答案并将@Profile 替换为@ConditionalOnProperty 注释。要了解@ConditionalOnProperty 并了解它在做什么,请在此处查看此答案:What is purpose of @ConditionalOnProperty。还要始终检查@Profiles/ConditionalOnProperty 的条件是否互斥或已设置订单!
  • 感谢这个建议,它对我的​​研究很有帮助。
猜你喜欢
  • 2011-05-04
  • 2023-04-05
  • 2015-08-08
  • 2019-01-27
  • 1970-01-01
  • 2014-10-27
  • 1970-01-01
  • 2015-01-23
  • 2019-02-21
相关资源
最近更新 更多