00:00

CORS vs CSRF: What Is the Difference?

Last updated:

CORS and CSRF both deal with requests that cross from one website to another, and their names look alike, so they are often confused. They protect against different things and work in opposite directions. CORS decides whether a script on another origin may read your responses. CSRF protection decides whether a state-changing request really came from your pages.

The most dangerous misunderstanding is that a strict CORS policy prevents CSRF. It does not. This page compares the two side by side, shows which one applies in common architectures, and demonstrates with a real request why CSRF protection is still required when CORS is configured.

1. What Are CORS and CSRF?

CORS (Cross-Origin Resource Sharing) is a browser mechanism, controlled by response headers such as Access-Control-Allow-Origin, that relaxes the same-origin policy for trusted origins. It is about reading: without CORS permission, a script on another origin may still trigger some requests, but cannot read the responses. See CORS in Spring Security.

CSRF (Cross-Site Request Forgery) is an attack: another site makes the victim's browser send a request that carries the victim's cookies. CSRF protection is the defence, a secret token that only your pages can include. See CSRF protection.

2. CORS vs CSRF: Key Differences

AspectCORSCSRF protection
What it isA browser permission mechanismA defence against an attack
Protects againstOther origins reading your responses with JavaScriptOther sites making the browser send forged, credentialed requests
Who enforces itThe browser, based on your response headersYour server, by checking a token
DirectionOpens access for trusted originsCloses a hole that cookies create
Applies toScript-initiated cross-origin requests (fetch, XHR)Unsafe methods (POST, PUT, PATCH, DELETE) authenticated by cookies or other automatic credentials
Stops plain HTML form posts?No: forms are sent without asking CORSYes: the form cannot contain the secret token
Affects non-browser clients?NoOnly if they authenticate with cookies
Spring Security settinghttp.cors(...) with a CorsConfigurationSourcehttp.csrf(...), enabled by default

3. Why CORS Does Not Stop CSRF

A forged form post is sent regardless of CORSAn attacker page submits a hidden form to the API. The browser sends it with the victim session cookie without a CORS preflight, because simple form posts are exempt. CORS only affects whether the attacker can read the response. CsrfFilter rejects the request because the token is missing. evil.example page hidden auto-submit form Browser sends POST with the victim's session cookie No preflight simple requests skip CORS checks CsrfFilter no token: 403 CORS headers only control reading
Figure 1: CORS decides who may read the answer; only the CSRF token stops the request itself.

Browsers distinguish "simple" requests, such as a GET or a form POST with a form or plain-text content type, from requests that need a preflight. Simple requests are sent immediately, with cookies, whatever CORS headers the server would return. CORS only decides afterwards whether the script may see the response. For a CSRF attack, seeing the response is unnecessary: the harm is done by the request.

Spring's CorsFilter adds a second effect: for paths that have a CORS configuration, it rejects requests whose Origin header is not allowed. That is helpful, but it is not a CSRF defence to rely on, because it only covers configured paths, and not every forged request carries an Origin header that the server can check.

4. Example: A Forged Request Against a Cookie-Based App

This uses the donation application from the CSRF protection tutorial, built with Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2. It has no CORS configuration at all, exactly like many server-rendered sites. Neha logs in; then a request is sent the way her browser would send a hidden form from https://evil.example: with her cookie, a foreign Origin, a simple text/plain body and no CSRF token.

Terminal
$ LOGIN_CSRF=$(curl -s -c cookies.txt localhost:8080/login | grep -o 'name="_csrf" type="hidden" value="[^"]*"' | cut -d'"' -f6)

$ curl -b cookies.txt -c cookies.txt -X POST localhost:8080/login -d username=neha -d password=neha-pass -d _csrf=$LOGIN_CSRF
HTTP/1.1 302
Location: http://localhost:8080/

$ curl -b cookies.txt -X POST localhost:8080/api/donations/monthly -H 'Origin: https://evil.example' -H 'Content-Type: text/plain' -d '{"amount":50000}'
HTTP/1.1 403
{"timestamp":"2026-11-18T12:13:36.726Z","status":403,"error":"Forbidden","path":"/api/donations/monthly"}

With DEBUG logging for org.springframework.security.web.csrf, the server log names the reason:

Terminal
CsrfFilter: Invalid CSRF token found for http://localhost:8080/api/donations/monthly

No CORS rule stood in the way, because there is none and because the request was simple. The request reached the application with a valid session, and only CsrfFilter refused it with 403. Without CSRF protection, the forged donation would have been accepted.

5. Which Protection Do You Need?

ArchitectureCORSCSRF protection
Server-rendered app (Thymeleaf), same origin, session cookieNot neededRequired (default form token)
SPA on the same origin as the API, session cookieNot neededRequired (csrf.spa())
SPA on another origin, session cookie with allowCredentialsRequired, exact originsRequired
SPA on another origin, bearer token in a headerRequiredNot needed for header-only tokens
Mobile app or service calling an API with bearer tokensNot needed (no browser)Not needed
Webhook from a partner, signed requestNot neededExclude the path; verify the signature

6. Configuring Both in Spring Security

When a browser front end on another origin uses a session cookie, both are needed in the same chain:

Both protections together (excerpt)
http
    .cors(Customizer.withDefaults())      // CorsConfigurationSource bean with exact origins and allowCredentials(true)
    .csrf(csrf -> csrf.spa())             // token in the XSRF-TOKEN cookie, sent back as X-XSRF-TOKEN
    .authorizeHttpRequests(auth -> auth.anyRequest().authenticated())
    .formLogin(Customizer.withDefaults());

Note that with a front end on a different origin, the JavaScript cannot read a cookie set for the API's domain, so the token must be delivered another way, for example from a GET /csrf endpoint that returns it in the body, or by serving the front end and the API under one site through a reverse proxy.

7. Common Mistakes and Best Practices

  • "We configured CORS, so CSRF can be disabled." Form posts and other simple requests are never stopped by CORS.
  • Disabling CSRF because a SPA "uses an API". If the API authenticates with a cookie, it needs CSRF protection.
  • Allowing any origin with credentials. allowedOriginPatterns("*") plus allowCredentials(true) lets any site make credentialed calls and read the answers.
  • Treating either one as authorization. Neither checks who the user is or what they may do; that remains the job of authentication and authorization rules.
  • Use SameSite cookies as an extra layer, not as a replacement for tokens.

8. Summary

  • CORS is a browser mechanism that lets trusted origins read your responses; it is not a defence against forged requests.
  • CSRF protection is a server-side token check that stops forged requests made with automatic credentials.
  • Simple requests such as form posts are sent without any CORS check, so CORS cannot prevent CSRF.
  • Cookie-based browser apps need CSRF protection; header-only bearer token APIs do not.
  • Cross-origin SPAs with cookies need both: exact-origin CORS with credentials and CSRF tokens.

9. References