Sample code for spring security CSRF protection

  • 2021-07-01 07:35:16
  • OfStack

CSRF refers to cross-site request forgery (Cross-site request forgery), which is one of the common attacks of web.

Starting with Spring Security 4.0, CSRF protection is enabled by default to prevent CSRF from attacking applications, and Spring Security CSRF is protected against PATCH, POST, PUT, and DELETE methods.

This is the spring boot project. With @ EnableWebSecurity annotation enabled, csrf protection takes effect automatically.

Therefore, under the default configuration, even if you have logged in, the requests for PATCH, POST, PUT and DELETE initiated in the page will still be rejected, and 403 will be returned, and csrfToken needs to be added when requesting the interface.

If you use a template engine such as freemarker or jsp, you can add the following hidden fields to the form for form submission:


<input type =  " hidden "  name =  " ${_csrf.parameterName} "  value =  " ${_csrf.token} "  /> 

If you are using JSON, you cannot submit the CSRF token in the HTTP parameter. Instead, you can submit the token in the HTTP header. A typical pattern is to include CSRF tokens in meta-tags. An example of JSP is shown below:


<html> 
<head> 
  <meta name =  " _csrf "  content =  " ${_csrf.token} "  /> 
  <!--  The default title name is X-CSRF-TOKEN --> 
  <meta name =  " _csrf_header "  content =  " ${_csrf.headerName} "  /> 
</ head> 

You can then include the token in all Ajax requests. If you use jQuery, you can do this using the following methods:


var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$.ajax({
  url:url,
  type:'POST',
  async:false,
  dataType:'json',  // Data format returned: json/xml/html/script/jsonp/text
  beforeSend: function(xhr) {
    xhr.setRequestHeader(header, token); // Before sending the request, set the csrfToken Set to the request header 
  },
  success:function(data,textStatus,jqXHR){
  }
});

If you do not want to enable CSRF protection, you can cancel csrf in the spring security configuration, as follows:


@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/login").permitAll()
        .anyRequest().authenticated()
        .and()
        ...
    http.csrf().disable(); // Cancel csrf Protection 
  }
}

Related articles: