CSRF Protection in REST APIs with Spring Boot

In the world of modern web development, security is a foundational pillar. One such security threat that developers must defend against is CSRF (Cross-Site Request Forgery). In this post, we’ll walk through how to effectively implement CSRF Protection in REST APIs using Spring Boot and Spring Security.

We’ll cover:

  • What CSRF is
  • When and why it matters for APIs
  • How to configure Spring Security for CSRF-safe endpoints
CSRF Protection in REST APIs with Spring Boot

πŸ“Œ What is CSRF?

CSRF (Cross-Site Request Forgery) is an attack where a malicious website tricks a logged-in user into performing unintended actions on another website where they are authenticated.

Example attack scenario:

  • User logs in to yourapp.com.
  • Without logging out, the user visits malicious.com.
  • A script on malicious.com sends a POST request to yourapp.com/api/transfer on behalf of the user.

If CSRF protection isn’t enabled, that malicious request could go through.

⚠️ Does CSRF Affect REST APIs?

Not always β€” but sometimes.

  • If your REST APIs are stateless and use tokens (like JWT) in headers: CSRF is less of a concern.
  • If your APIs use cookies for authentication, especially in Single Page Applications (SPAs): CSRF must be addressed.

So, if your frontend stores session cookies or uses form-based login, you need CSRF Protection in REST APIs.

🧱 Spring Boot Setup

Dependencies (pom.xml)

Make sure the following dependencies are in your pom.xml:



    org.springframework.boot
    spring-boot-starter-security


    org.springframework.boot
    spring-boot-starter-web



πŸ› οΈ Implementing CSRF Protection in REST APIs

πŸ“ com.kscodes.springboot.security.config.SecurityConfig.java


package com.kscodes.springboot.security.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.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf
                .ignoringRequestMatchers("/api/public/**") // disable CSRF for public endpoints
            )
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/public/**").permitAll()
                .anyRequest().authenticated()
            );

        return http.build();
    }
}

Explanation:

  • CSRF is enabled by default in Spring Security.
  • We’re disabling CSRF only for specific public endpoints.
  • For protected endpoints, CSRF tokens are still required.

πŸ”‘ How CSRF Token Works in REST APIs

If you use cookies for authentication, the CSRF token must be:

  • Sent from backend as part of a response (e.g., in a header or meta tag).
  • Read by the frontend and included in every state-changing request (POST, PUT, DELETE).

Example: Sending CSRF Token to Frontend


@GetMapping("/csrf-token")
public CsrfToken csrfToken(CsrfToken token) {
    return token;
}

Frontend receives:


{
  "headerName": "X-CSRF-TOKEN",
  "parameterName": "_csrf",
  "token": "random-csrf-value"
}

Frontend then adds it to request headers:


fetch("/api/secure/data", {
  method: "POST",
  headers: {
    "X-CSRF-TOKEN": "random-csrf-value"
  },
  body: JSON.stringify({ ... })
});

πŸ”’ Real-World Strategy for CSRF Protection in REST APIs

If using:Then:
Cookie-based loginEnable CSRF protection and send token
Stateless APIs with JWTYou can disable CSRF
Third-party clients (mobile)Disable CSRF (if not using session/cookie)

βœ… Example Controller

πŸ“ com.kscodes.springboot.security.controller.UserController.java


package com.kscodes.springboot.security.controller;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/secure")
public class UserController {

    @PostMapping("/update-profile")
    public String updateProfile(@RequestBody String profileData) {
        return "Profile updated securely.";
    }
}

You must send a CSRF token with this POST request.

πŸ“Œ Key Takeaways

  • CSRF Protection in REST APIs is crucial if you rely on cookies.
  • Spring Boot provides out-of-the-box CSRF token generation and validation.
  • Use csrfToken() endpoint to expose token to frontend.
  • Stateless APIs using JWT or OAuth2 typically don’t need CSRF.

πŸ”— References