如何使用application.properties在Spring中禁用csrf?

时间:2017-06-29 11:51:39

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

存在以下属性:

$3

但如果我将属性添加到security.enable-csrf=false,则csrf保护仍然存在。

以编程方式禁用它是有效的。

但我更喜欢属性配置。为什么它不起作用?

application.properties

2 个答案:

答案 0 :(得分:7)

由于WebSecurityConfigurerAdapter使用命令式方法,您可以注入security.enable-csrf变量的值,并在其为false时禁用CSRF。你是对的,我认为这应该是开箱即用的。

@Configuration
public class AuthConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Value("${security.enable-csrf}")
    private boolean csrfEnabled;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
       super.configure(http);

       if(!csrfEnabled)
       {
         http.csrf().disable();
       }
    }
}

我所做的是在我的application.yml中将该变量设置为false,以便我有一个 dev 弹簧配置文件处于活动状态,尽管您可以创建一个名为 nosecurity 的配置文件出于这样的目的。它简化了这个过程:

--- application.yml ---

# Production configuration
server:
  port: ${server.web.port}
admin.email: ${admin.email}
#etc
---
spring:
  profiles: dev

security.enable-csrf: false

#other Development configurations

我希望它符合您的需求

2017年12月17日更新

基于comment of a Spring Boot member这个问题在新版本的Spring上得到修复:我在版本1.5.2.RELEASE上使用了它,但似乎在版本1.5.9.RELEASE中(迄今为止最新的稳定版本)在版本2之前)它已经固定,默认情况下 csrf 被禁用,可以使用security.enable_csrf: true启用它。因此,可能的解决方案可能只是升级到版本1.5.9.RELEASE,然后再制作版本2的主要版本,其中架构可能会更加不同。

答案 1 :(得分:3)

更新:

看起来在spring-boot 1.x上使用application.properties禁用CSRF存在问题(感谢Eliux打开此case)。

所以我的 spring-boot 1.5.7 解决方案是使用嵌入式tomcat通过 SecurityConfig 类禁用CSRF(注意这样我保留了tomcat ootb基本身份验证) :

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Note: 
        // Use this to enable the tomcat basic authentication (tomcat popup rather than spring login page)
        // Note that the CSRf token is disabled for all requests (change it as you wish...)
        http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // Add here any custom code you need in order to get the credentials from the user...  
        auth.inMemoryAuthentication()
            .withUser("myUserName")
            .password("myPassword")
            .roles("USER");
    }
} 
相关问题