Search code examples
javaspringspring-mvcspring-securitycsrf

Spring Security: enable / disable CSRF by client type (browser / non-browser )


Spring Security documentation says:

"When you use CSRF protection? Our recommendation is to use CSRF protection for any request that could be processed by a browser by normal users. If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection."


What if my service is going to be used by both "browser" and "non-browser" clients such as third party external services, does Spring Security provide a way to disable CSRF exclusively for certain type of clients?


Solution

  • I am sure there is a way to do this in Spring Security XML, but since I am using Java Config, here is my solution.

     @Configuration
     @EnableWebSecurity
     public class SecurityConfig {
    
        @Configuration
        @Order(1)
        public static class SoapApiConfigurationAdapter extends WebSecurityConfigurerAdapter {
            protected void configure(HttpSecurity http) throws Exception {
                http
                    .antMatcher("/soap/**")
                    .csrf().disable()
                    .httpBasic();
            }
        }
    
    
        @Configuration
        public static class WebApiConfigurationAdapter extends WebSecurityConfigurerAdapter {
    
            protected void configure(HttpSecurity http) throws Exception {
                http        
                    .formLogin()
                        .loginProcessingUrl("/authentication")
                        .usernameParameter("j_username")
                        .passwordParameter("j_password").permitAll()
                        .and()
                    .csrf().disable()
    
            }
         }
    }