How to disable csrf in Spring using application.properties?

60,832

Solution 1

As the WebSecurityConfigurerAdapter uses an imperative approach you can inject the value of the security.enable-csrf variable and disable CSRF when it be false. You are right, I think this should work out of the box.

@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();
       }
    }
}

What I did was to set that variable to false in my application.yml for when I had a dev spring profile active, although you could create a profile called nosecurity for such purposes too. It eases this process a lot:

--- application.yml ---

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

security.enable-csrf: false

#other Development configurations

I hope it suits your needs

Update on Dec 17th of 2017

Based on a comment of a Spring Boot member this issue is fixed on new versions of Spring: I had it on version 1.5.2.RELEASE but it seems that in version 1.5.9.RELEASE (the latest stable one to the date before version 2) its already fixed and by default csrf is disabled and it can be enabled with security.enable_csrf: true. Therefore a possible solution could be just upgrading to version 1.5.9.RELEASE, before making a major one to version 2 where the architecture might be quite more different.

Solution 2

An update:

Looks like there is an issue with disabling CSRF using application.properties on spring-boot 1.x (and thanks to Eliux for openning this case).

So my solution for spring-boot 1.5.7 with an embedded tomcat is disabling CSRF via SecurityConfig class (note that this way I keep the tomcat ootb basic authentication):

@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");
    }
} 
Share:
60,832

Related videos on Youtube

membersound
Author by

membersound

JEE + Frameworks like Spring, Hibernate, JSF, GWT, Vaadin, SOAP, REST.

Updated on May 08, 2022

Comments

  • membersound
    membersound almost 2 years

    The following property exists:

    security.enable-csrf=false

    BUT csrf protection is still on if I add the property to application.properties.

    What works is to disable it programatically.

    But I'd prefer properties configuration. Why could it not be working?

    @Configuration
    public class AuthConfig extends WebSecurityConfigurerAdapter {
        @Autowired
        private UserDetailsService userDetailsService;
    
        @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);
            http.csrf().disable();
    
        }
    }
    
    • M. Deinum
      M. Deinum almost 7 years
      That will only work if Spring Boot is allowed to configure security, if you are messing around with Security yourself, that property won't do anything. Also make sure you are on a version of Spring Boot that supports that property.
    • membersound
      membersound almost 7 years
      I'm on newest -1.5.4 and I only added the configure() method to disable the csrf. If I remove that method completely, the property is still not taken into account. The only custom security config is with configure(AuthenticationManagerBuilder auth) that I use to set BCryptPasswordEncoder. But that should not impact the csrf.
    • M. Deinum
      M. Deinum almost 7 years
      That depends, if you have @EnableWebMvc on it that will disable auto configuration.
    • membersound
      membersound almost 7 years
      @SpringBootApplication is my only annotation. And I'm extending WebSecurityConfigurerAdapter. Maybe that's the cause?
    • M. Deinum
      M. Deinum almost 7 years
      Are you using Spring Boot? As that isn't really clear from your question...
    • membersound
      membersound almost 7 years
      Yes, added spring-boot to tags.
    • M. Deinum
      M. Deinum almost 7 years
      Did you enable basic authentication (which is the default) or did you disable that... Also the default is to disable csrf protection so you must have some additional security configuration (properties or classes) that disables the default setup.
    • membersound
      membersound almost 7 years
      I have security.basic.enabled=true and using maven spring-boot-starter-security.
    • M. Deinum
      M. Deinum almost 7 years
      Then I'm out of ideas. There is too little information too help you. imho you have something in the code that disables the default configuration (could be something you have or additional dependencies) however with the little information in the question that is hard to tell.
  • membersound
    membersound almost 7 years
    Thanks, that's a great idea. Though it still not explains why the crsf configuration is not entirely disabled by just setting the configuration property.
  • EliuX
    EliuX almost 7 years
    An issue should be raised in their Spring github and/or jira
  • EliuX
    EliuX over 6 years
    In the Spring Security documenation for CSRF it says that by default its on and to disable it you must do it by Java or xml code. The .properties attribute is something that should be implemented by Spring Boot: An issue opened in Spring Boot
  • EliuX
    EliuX over 6 years
    It seems that for versions like 1.5.9 or superior this is fixed.
  • 01000001
    01000001 over 4 years
    CSRF is enabled by default as of Spring Security 4.0. docs.spring.io/spring-security/site/docs/4.2.1.RELEASE/…
  • Hiren
    Hiren about 4 years
    Suppose I kept it "disable" via external configuration & I am running my app. Now at some point of time I want to "enable" CSRF so I changed property to TRUE and hit the /refresh end point, but does that mean that Spring container will again call "configure" method of "AuthConfig" ? If not then I need to either re-stage my app or restart my app so new configuration is loaded by spring container.