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:

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

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

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

Frontend receives:

Frontend then adds it to request headers:

πŸ”’ 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

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