CORS and CSRF solve different problems. CORS controls whether browser JavaScript is allowed to read cross-origin responses. CSRF protects cookie-authenticated applications from unwanted state-changing requests initiated by an attacker-controlled site.
What CORS means
Browsers enforce the same-origin policy. CORS allows a server to explicitly tell the browser which other origins may access its responses.
Access-Control-Allow-Origin: https://app.example.com
Preflight request
Some cross-origin requests trigger an OPTIONS preflight. The browser asks the server whether the intended method and headers are allowed before sending the actual request.
sequenceDiagram
participant Browser
participant API
Browser->>API: OPTIONS preflight
API-->>Browser: CORS policy
Browser->>API: Actual request
API-->>Browser: Response
Credentials
Cookie-based cross-origin requests require careful credential and origin configuration. A wildcard origin is not a valid replacement for an explicit trusted origin when credentials are involved.
What CSRF is
CSRF occurs when a victim's browser automatically sends authentication credentials such as cookies to a target site while the victim is tricked into initiating a state-changing request.
flowchart TD
A[Victim logged in] --> B[Malicious site]
B --> C[Browser sends request]
C --> D[Target API]
D --> E[State changes if unprotected]
CSRF defenses
Common defenses include SameSite cookie settings, anti-CSRF tokens, origin or referer validation where appropriate, and careful API design. The correct combination depends on the authentication architecture.
JWT and CSRF
If a bearer token is explicitly placed in an Authorization header by JavaScript, the browser does not automatically attach that header to an unrelated malicious site's request in the same way it automatically sends cookies. However, this does not make token-based systems immune to XSS or other attacks.
CORS is not authentication
CORS does not decide whether a user is authorized. A backend still needs authentication and authorization. CORS is a browser access-control mechanism.
Output examples
Allowed origin:
https://app.example.com -> API response readable
Unknown origin:
https://attacker.example -> browser blocks response
CSRF protected request:
Missing CSRF proof -> request rejected
Common mistakes
- Using CORS as if it were authentication.
- Allowing every origin in a credentialed production API.
- Forgetting preflight requirements.
- Assuming Authorization headers solve every browser security issue.
- Ignoring SameSite and CSRF design when using cookies.
Interview questions
- What is CORS?
- What is a preflight request?
- What is CSRF?
- CORS vs CSRF?
- Does JWT automatically prevent CSRF?
- Why can CORS not replace backend authorization?