REST API Security — CORS, CSRF, and JWT
Fast recall
Quick revision
Core answer
Understanding of why CSRF doesn't apply to JWT APIs, and correct CORS configuration
Enabling CSRF protection on a stateless JWT API — adds overhead without security benefit
Explain the SameSite cookie attribute as a modern alternative to CSRF tokens, and explain preflight OPTIONS requests
Interview-ready guide
Interview answer
CORS and CSRF are two separate security concerns that are commonly confused because both involve cross-origin requests. They protect against different attacks and are configured independently.
CORS — protecting the browser from reading unauthorized responses
- The browser checks
Access-Control-Allow-Originto decide if JavaScript can read the response - CORS does not prevent the request from reaching the server — it prevents the response from being readable by the origin JavaScript
- Backend-to-backend calls ignore CORS entirely — only browser-originated JavaScript is affected
CSRF — protecting session-cookie apps from forged requests
- The attack: malicious site tricks the user's browser into sending a request to your API; browser automatically includes the session cookie
- The fix: require a secret token that the malicious site cannot access (Synchronizer Token Pattern)
- For SPAs:
CookieCsrfTokenRepositorywrites the CSRF token to a JavaScript-readable cookie; the SPA reads it and sends it asX-XSRF-TOKENheader
When to disable CSRF
- Stateless JWT APIs: the
Authorization: Bearerheader is not sent automatically by browsers; the cross-site forgery attack vector does not apply http.csrf(csrf -> csrf.disable())in your Spring Security configuration
Modern apps using SameSite=Strict cookies get CSRF protection for free from the browser — the cookie is never sent on cross-origin requests.
REST API Security — CORS, CSRF, and JWT
Direct Answer
CORS restricts which origins can call your API from browsers — configure it with @CrossOrigin or Spring Security's CORS config. CSRF is not needed for stateless JWT APIs. Authentication uses JWT Bearer tokens in the Authorization header.
Common Mistakes & Pitfalls
Enabling CSRF protection on a stateless JWT API — adds overhead without security benefit
Check your understanding
Answer these without looking back at the article.
- When would CSRF protection be necessary for a REST API?
- What is the difference between AllowedOrigins and AllowedOriginPatterns?
- Why is 'Access-Control-Allow-Origin: *' dangerous in production?
Related interview prep categories
1Want a guided curriculum order?
These modules are also sequenced in our flagship backend interview track — open it when you prefer an ordered path instead of browsing by topic.