Spring Security and CSRF
Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious website tricks a user into performing actions on another website where they are authenticated. This guide covers key concepts and steps for protecting your Spring Boot application against CSRF attacks, including adding dependencies, enabling CSRF protection, and configuring security settings.
Key Concepts of CSRF
- CSRF (Cross-Site Request Forgery): An attack that tricks the user into executing unwanted actions on a web application in which they are authenticated.
- CSRF Token: A unique, secret, unpredictable value that is generated by the server and transmitted to the client to prevent CSRF attacks.
- Security Configuration: Configuring Spring Security to enable CSRF protection.
Adding Dependencies
Include the Spring Security dependency in your pom.xml
file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Enabling CSRF Protection
CSRF protection is enabled by default in Spring Security. Ensure it is configured in your security settings:
Example: SecurityConfiguration.java
// SecurityConfiguration.java
package com.example.myapp.config;
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.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home", true)
.failureUrl("/login?error=true")
.and()
.logout()
.logoutSuccessUrl("/login?logout=true")
.permitAll();
}
}
Handling CSRF Tokens in Forms
Include the CSRF token in your forms to ensure they are protected:
Example: login.html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="/css/styles.css" />
</head>
<body>
<div class="swf-lsn-container">
<h2>Login</h2>
<form method="post" action="/login">
<input type="hidden" name="_csrf" value="${_csrf.token}" />
<div>
<label>Username:</label>
<input type="text" name="username" />
</div>
<div>
<label>Password:</label>
<input type="password" name="password" />
</div>
<div>
<input type="submit" value="Login" />
</div>
</form>
<div class="swf-lsn-error-message">
<#if error?string?trim != "">
Invalid username or password.
</#if>
<#if logout?string?trim != "">
You have been logged out.
</#if>
</div>
</div>
</body>
</html>
Configuring CSRF Protection for APIs
For APIs, you might need to disable CSRF protection and use other methods like JWT:
Example: SecurityConfiguration.java (API)
// SecurityConfiguration.java (API)
package com.example.myapp.config;
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.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/public/**", "/api/authenticate").permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
}
Key Points
- CSRF (Cross-Site Request Forgery): An attack that tricks the user into executing unwanted actions on a web application in which they are authenticated.
- CSRF Token: A unique, secret, unpredictable value that is generated by the server and transmitted to the client to prevent CSRF attacks.
- Security Configuration: Configuring Spring Security to enable CSRF protection.
- Include the Spring Security dependency in your
pom.xml
file. - Ensure CSRF protection is configured in your security settings.
- Include the CSRF token in your forms to ensure they are protected.
- For APIs, consider disabling CSRF protection and using other methods like JWT.
Conclusion
Protecting your Spring Boot application against CSRF attacks is essential for ensuring its security. By understanding and implementing CSRF protection, including CSRF tokens in forms, and configuring security settings appropriately, you can safeguard your application from CSRF vulnerabilities. Happy coding!