Spring Security - How to Enable and Disable CSRF
Last Updated :
11 Sep, 2025
Spring Security provides mechanisms to protect applications from common security threats. One of the most important protections is Cross-Site Request Forgery (CSRF) defense. By default, Spring Security enables CSRF protection, but developers often disable it for APIs without understanding when it’s safe.
What is CSRF
Cross-Site Request Forgery (CSRF) is an attack that tricks an authenticated user into unknowingly sending a malicious request to a web application.
Example:
- If you are logged into your banking application, a malicious site could trick your browser into making a POST request to transfer money without your consent.
- CSRF protection prevents this by ensuring that every state-changing request (POST, PUT, DELETE, PATCH) contains a valid CSRF token issued by the server.
Step-by-Step Implementation
Folder Structure:
Before moving to the project, let’s have a look at the complete project structure for our Spring MVC application.
Folder StructureStep 2: Add Dependencies to pom.xml File
Add the following dependencies to your pom.xml file
- Spring Web MVC
- Java Servlet API
- Spring Security Config
- Spring Security Web
Below is the complete pom.xml file. Please cross-verify if you have missed some dependencies.
pom.xml:
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gfg.springsecurity</groupId>
<artifactId>springsecurity</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>springsecurity Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.gfg.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.24</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.7.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-web -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.7.3</version>
</dependency>
</dependencies>
<build>
<finalName>springsecurity</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see https://maven.apache.org/ref/3.9.11/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Step 3: Configure DispatcherServlet
The DispatcherServlet handles all incoming requests in Spring MVC.
Go to the src > main > java and create a class WebAppInitilizer. Below is the code for the WebAppInitilizer.java file.
File: WebAppInitilizer.java
Java
package com.gfg.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebAppInitilizer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
Class[] configFiles = {MyAppConfig.class};
return configFiles;
}
@Override
protected String[] getServletMappings() {
String[] mappings = {"/"};
return mappings;
}
}
Create another class in the same location (src > main > java) and name it MyAppConfig. Below is the code for the MyAppConfig.java file.
MyAppConfig.java
Java
package com.gfg.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebMvc
@ComponentScan("com")
public class MyAppConfig {
// Configure view resolver
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
// Password encoder bean for Spring Security
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Step 5: Create a Spring MVC Controller
Go to the src > main > java and create a class GfgController. Below is the code for the GfgController.java file.
File: GfgController.java
Java
package com.gfg.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class GfgController {
@GetMapping("/gfg")
public String helloGfg() {
return "hello-gfg"; // Maps to hello-gfg.jsp
}
}
Step 6: Create Your JSP View
Go to the src > main > webapp > WEB-INF > right-click > New > Folder and name the folder as views. Then views > right-click > New > JSP File and name your first view. Here we have named it as hello-gfg.jsp file. Below is the code for the hello-gfg.jsp file. We have created a simple web page inside that file.
hello-gfg.jsp
HTML
<!DOCTYPE html>
<html>
<body bgcolor="green">
<h1>Hello GeeksforGeeks!</h1>
</body>
</html>
Step 7: Configure Spring Security Filter Chain
Go to the src > main > java and create a class MySecurityAppConfig and annotate the class with @EnableWebSecurity annotation. This class will help to create the spring security filter chain. Below is the code for the MySecurityAppConfig.java file.
MySecurityAppConfig.java
Java
package com.gfg.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
@SuppressWarnings("deprecation")
@EnableWebSecurity
public class MySecurityAppConfig extends WebSecurityConfigurerAdapter {
@Autowired
private PasswordEncoder passwordEncoder;
// Configure in-memory user authentication
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("gfg")
.password(passwordEncoder.encode("gfg123"))
.roles("ADMIN");
}
// Configure HTTP security (basic authentication + form login)
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
}
SecurityInitializer.java
Go to the src > main > java and create a class SecurityInitializer. This class will help to register the spring security filter chain with our application. Below is the code for the SecurityInitializer.java file.
Java
package com.gfg.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
// Registers the Spring Security filter chain
}
Step 8: Enable and Disable CSRF Protection
Default Behavior: CSRF is enabled by default in Spring Security.
Disabling CSRF (for APIs or stateless apps):
Java
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic()
.and()
.csrf().disable(); // Disable CSRF
}
Step 9: Run and Test the Application
- Right-click the project -> Run As -> Run on Server.
- Access your controller:
http://localhost:8080/springsecurity/gfg
You will see an authentication popup. Inspect the page source:
- With CSRF enabled: <input type="hidden" name="_csrf" value="..."> appears in forms.
- With CSRF disabled: No CSRF token appears.

Now right-click and go to the View page source.


Explore
Java Enterprise Edition
Multithreading
Concurrency
JDBC (Java Database Connectivity)
Java Frameworks
JUnit