在预生产环境中禁用WebSecurity Spring Boot

时间:2020-09-04 09:25:11

标签: java spring spring-boot rest spring-security

我正在尝试将身份验证用于生产环境。太棒了,当我尝试访问时,需要输入密码和用户名。我只想将此功能用于生产环境。不知道如何针对不同的配置文件/环境禁用它。我尝试使用基于.yml属性的if-else,但这引起了其他问题。 POST和UPDATE方法开始返回403 Forbidden。这是示例代码:

   @Configuration
@EnableWebSecurity
@Profile("!test")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSecurityConfig.class);

    @Value("${server.environment}")
    private String environment;

    @Value("${swagger.user}")
    private String swaggerUser;

    @Value("${swagger.password}")
    private String swaggerPass;




    @Override
    protected void configure(HttpSecurity http) throws Exception {
        if("stage".equals(environment) || "prod".equals(environment)){
            LOGGER.info("Environment: " + environment + " swagger authentication is on");
            http.csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/v2/api-docs").authenticated()
                    .and()
                    .httpBasic();
        } else {
            http.csrf().disable();
            LOGGER.info("Environment: " + environment + " swagger authentication is off");
        }

    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser(swaggerUser).password("{noop}" + swaggerPass).roles("USER");
    }

我曾尝试禁用整个WebSecurityConfig bean,但这没有用,因为存在依赖关系,现在每次要求登录时都如此。

试过这个,没用:

@Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/**").permitAll();
        }

4 个答案:

答案 0 :(得分:6)

推荐的方法是为生产和预发布环境创建另一个类,而不是使用if-else。您可能需要允许使用permitAll()的其他端点,或者需要添加基于权限的方法,例如hasRole()。另外,请确保您在控制器上没有任何安全注释,例如@PreAuthorized, @Secured等。

推荐方法:

产品或暂存环境的安全配置

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

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSecurityProductionConfig.class);

    @Value("${server.environment}")
    private String environment;

    @Value("${swagger.user}")
    private String swaggerUser;

    @Value("${swagger.password}")
    private String swaggerPass;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        LOGGER.info("Environment: " + environment + " swagger authentication is on");

        http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/v2/api-docs").authenticated()
            .antMatchers("**/**").permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
            .withUser(swaggerUser).password("{noop}" + swaggerPass).roles("USER");
    }
}

开发人员和其他环境的安全配置

@Configuration
@EnableWebSecurity
@Profile("!prod")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSecurityConfig.class);

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    LOGGER.info("Security configuration for the non prod env is loaded");
        http
            .csrf().disable()
            .authorizeRequests().antMatchers("**/**").permitAll();
    }

}

If-Else方法

@Configuration
@EnableWebSecurity
@Profile("!test")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSecurityConfig.class);

    @Value("${server.environment}")
    private String environment;

    @Value("${swagger.user}")
    private String swaggerUser;

    @Value("${swagger.password}")
    private String swaggerPass;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        
        if ("stage".equals(environment) || "prod".equals(environment)) {
            LOGGER.info("Environment: " + environment + " swagger authentication is on");
            http
                .authorizeRequests()
                .antMatchers("/v2/api-docs").authenticated();
        } else {
            http.authorizeRequests().antMatchers("**/**").permitAll();
            LOGGER.info("Environment: " + environment + " swagger authentication is off");
        }
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
            .withUser(swaggerUser).password("{noop}" + swaggerPass).roles("USER");
    }
}

答案 1 :(得分:0)

您可以尝试添加WebSecurityConfig的另一个实现,该实现将允许自由访问您的招摇,并根据您的application.yml中的属性使用@ConditionalOnProperty来确定应使用哪个实现。 / p>

答案 2 :(得分:0)

从一开始您的方法就很好,

  1. 您使用以下配置创建一个名为“ test”的配置文件: application-test.properties spring.autoconfigure.exclude = org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
  2. 然后通过添加与我看到的操作相同的@Profile(“!test”)在WebSecurityConfigurerAdapter上添加测试配置文件
  3. 在没有安全配置的情况下通过活动测试配置文件加入测试配置文件

java --spring.profiles.active=test -jar yourapp.jar

mvn spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=test

答案 3 :(得分:0)

如果仅想为产品环境配置安全性,则只需为产品环境实现WebSecurityConfigurerAdapter。



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

        @Override
        protected void configure(HttpSecurity http) throws Exception {
                http.csrf().disable()
                        .authorizeRequests()
                        .antMatchers("/v2/api-docs").authenticated()
                        .and()
                        .httpBasic();
        }
    }

有关更多信息,请访问此博客:https://www.baeldung.com/spring-security-disable-profile