#
Disable the CSRF
This tutorial explains how we can disable the CSRF when using Spring Security.
This example start from My first Spring Boot Service using Spring Security You need to pass through this article before.
Info
YWRtaW46YQ==
is the "username:password" encoded using Base64.- By default, only the GET methods is working well. If you receive a "403 Forbidden when performing" using a POST, PUT, DELETE method it is most likely related to CSRF. Either provide the CSRF Token or disable CSRF protection (not recommended).
Info
My example is using Spring Security 6.1.1. This can be seen in the External Libraries of the project.
For disabling the CSRF we need to change the default implementation of SecurityFilterChain
configuration class.
For this, I added the "ProjectSpringSecurityConfig" class which modify the SecurityFilterChain Bean.
package com.demo.springsecurity.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class ProjectSpringSecurityConfig {
@Bean
public SecurityFilterChain myFilterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable());
return http.build();
}
}
Now we can run POST, PUT, DELETE, PATCH requests without taking care of the CSRF. Even if this is not a good approach for PROD, it is a good approach for testing and understanding Spring Security.
Info
We can have multiple SecurityFilterChain Beans, but in this case we need to use @Order annotation.