Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 743
Himalay Majumdar Avatar asked Oct 03 '14 13:10

Himalay Majumdar


People also ask

How do I disable CSRF Spring Security?

Disable using security configuration code The spring boot security application allows to configure the security details in a customized class that extends WebSecurityConfigurerAdapter class. The CSRF feature can be disabled using the code “ http. csrf(). disable ()”.

How do I enable CSRF token in Spring Security?

3.1 Enabling CSRF Token in Spring Security disable() in your Spring security config class. With default setup, if you look at the source code of the page, you will see the _csrf parameter being added automatically to the form by Spring security.

Is CSRF enabled by default in Spring Security?

As of Spring Security 4.0, CSRF protection is enabled by default with XML configuration.

Should I disable CSRF Spring?

What is the real-life reason to disable it? The Spring documentation suggests: 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.


1 Answers

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()          }      } } 
like image 94
Himalay Majumdar Avatar answered Oct 15 '22 20:10

Himalay Majumdar