Do You Need CSRF Tokens With JWT or REST APIs?
It depends on where the token lives: if the browser sends your credential automatically (a cookie), you need CSRF protection, and if your own JavaScript adds it by hand in an Authorization header, you usually don't.
This post is for developers and site owners who build or inherit a REST API, a single-page app, or a JWT login and keep hearing conflicting advice. You'll get a decision table, a checklist for the cases that do need protection, and a quick test you can run yourself.
What CSRF actually is (and why storage matters)
CSRF stands for cross-site request forgery. An attacker's web page tricks a logged-in user's browser into sending a request to your site, such as "change email" or "transfer funds".
The trick only works because browsers attach cookies to requests automatically, even when the request starts on another site. The attacker never sees the cookie. They just make the browser use it. OWASP explains the mechanism in its CSRF Prevention Cheat Sheet.
So the real question is not "REST or not" or "JWT or not". It is: does the browser attach the credential on its own?
Is CSRF possible with JWT?
Yes, if the JWT travels in a cookie. A JWT (JSON Web Token) is just a signed string that proves who you are. The format does not matter to CSRF. The delivery method does.
- JWT in a cookie: the browser sends it automatically. CSRF is possible.
- JWT in an
Authorization: Bearer ...header: your code has to add it to each request. A malicious page on another site cannot read it or add it. Classic CSRF does not work.
There is a technical reason the header case is safe. A cross-site request with a custom Authorization header triggers a CORS preflight (a permission check the browser makes first). Your server has to approve the attacker's origin for it to go through. See MDN's CORS guide for how that works.
Decision table: where is the credential stored?
| How the user proves who they are | Browser sends it automatically? | CSRF risk? | What to do |
|---|---|---|---|
Bearer JWT in Authorization header, kept in JS memory or localStorage | No | No classic CSRF | No CSRF token needed. Focus on XSS defense |
JWT in a cookie (even HttpOnly) | Yes | Yes | SameSite cookie plus a CSRF token or Origin check |
| Classic server session ID cookie | Yes | Yes | Use your framework's built-in CSRF protection |
| HTTP Basic auth or client certificates | Yes | Yes | Treat like cookies. Add CSRF protection |
| API accepts both a cookie and a header | Yes, on the cookie path | Yes | Protect the cookie path, or accept only one method |
| Server-to-server API key in a header | No browser involved | No | No CSRF token needed |
Notice that HttpOnly does not help here. HttpOnly stops JavaScript from reading the cookie (an XSS defense). It does nothing to stop the browser from sending it.
Decision table: by how people use your app
| Setup | CSRF token needed? | Why |
|---|---|---|
| Browser app, login stored in a cookie | Yes (or equivalent defenses) | Browser attaches the cookie |
| Browser SPA, Bearer token set by your JS | No | Nothing is sent automatically |
| Mobile app calling your API with a Bearer token | No | No browser cookie jar is involved, as long as the app sends a Bearer header and not session cookies |
| Public API with no login | No | There is no user session to hijack |
| Partner or machine API using API keys | No | Keys are set by the calling server |
Is a CSRF token necessary for a REST API?
Not by itself. "REST" describes API style, and it says nothing about authentication. A REST API that uses cookie sessions needs CSRF protection. A REST API that uses only Bearer tokens in headers usually doesn't.
Framework docs say the same thing. Spring Security, for example, documents when it's reasonable to disable CSRF for requests that browsers won't make with automatic credentials. Django REST Framework only enforces CSRF when you use SessionAuthentication. Token and JWT authentication classes skip it.
When tokens are required, and when they aren't
You need CSRF protection when:
- A cookie (session ID or JWT) authenticates state-changing requests (POST, PUT, PATCH, DELETE).
- You use Basic auth or client certificates in browsers.
- Your API accepts a cookie as one of several login options.
- You have a cookie-based login on one subdomain and other, less trusted subdomains on the same domain.
You usually don't need a CSRF token when:
- Every request carries a Bearer token that your JavaScript adds explicitly.
- The client is a mobile app or a server, not a browser.
- The endpoint is public and does nothing that depends on who is logged in.
If you skip CSRF tokens because of the header approach, make sure no cookie can also log the user in. One leftover cookie fallback brings the risk right back.
Checklist: protecting a cookie-based JWT or session
Layer these. No single one is perfect.
- Set strict cookie flags. For example:
Set-Cookie: session=<jwt>; Path=/; Secure; HttpOnly; SameSite=Lax
SameSite=Lax stops browsers sending the cookie on cross-site POST requests. Strict is tighter but can break links from email. Keep in mind "same site" includes your subdomains, so a vulnerable sibling subdomain can still attack you. MDN covers the details in its cookies guide.
- Add a CSRF token to state-changing requests. The server hands the page a random token. The page sends it back in a header such as
X-CSRF-Token. The server rejects the request if it is missing or wrong. OWASP recommends either a synchronizer token or a signed double-submit cookie.
- Check the
Originheader. On POST, PUT, PATCH and DELETE, reject requests whereOriginis present and not your own site. Modern browsers also sendSec-Fetch-Site, which you can check as an extra layer.
- Never change data on GET. Lax cookies are still sent on top-level GET navigations. A "delete account" link that works with GET is a CSRF hole.
- Lock down CORS. Never reflect any
Originback inAccess-Control-Allow-Originwhile also sendingAccess-Control-Allow-Credentials: true. List the exact origins you trust.
- Don't trust the JSON content type as a defense. Some servers parse a body as JSON even when it arrives as
text/plain, which a cross-site form can send without a preflight. RequireContent-Type: application/jsonand reject the rest.
Use your framework's built-in tool where one exists: Django's CsrfViewMiddleware, Spring Security's CSRF filter, Laravel's ValidateCsrfToken (formerly VerifyCsrfToken) middleware. In Express, the older csurf package is deprecated. Maintained alternatives such as csrf-csrf exist, so check the current state of any package you pick.
Quick self-test: does your server enforce it?
Use a test account on a site you own. First, send a state-changing request with the cookie but without the CSRF token:
curl -i -X POST https://your-site.example/api/profile \
-H "Cookie: session=YOUR_TEST_COOKIE" \
-H "Content-Type: application/json" \
-d '{"name":"csrf-test"}'
A protected endpoint returns a 403 (or similar 4xx) and does not change the data. Next, repeat the request with a foreign origin. For the Origin test, first fetch a valid CSRF token with your test account and include it, as in the X-CSRF-Token header below. Skip that header if your app does not use CSRF tokens.
curl -i -X POST https://your-site.example/api/profile \
-H "Cookie: session=YOUR_TEST_COOKIE" \
-H "X-CSRF-Token: YOUR_TEST_TOKEN" \
-H "Origin: https://evil.example" \
-H "Content-Type: application/json" \
-d '{"name":"csrf-test"}'
Here is how to read the results. If you rely on CSRF tokens, the first request should be rejected. If the first request (no token) returns 200 and the name changes, you have a gap only if your app relies on CSRF tokens. An app that relies on SameSite cookies plus an Origin check can legitimately accept it, because curl ignores SameSite and sends no Origin header. If a request without the token returns 200 and the name changes, the server is not checking tokens on that route.
If you rely on an Origin check, send the second request with a valid CSRF token (if you use one) so the Origin check is tested on its own. Without a valid token, a 403 could come from the token check and hide a missing Origin check. If the second request returns 200 and the name changes, the server is not enforcing the Origin check.
This only proves what the server checks. It does not replicate a real browser attack, so treat it as a smoke test, not a clean bill of health.
The trade-off nobody mentions: XSS
Moving the JWT to a header and localStorage removes CSRF, but it creates a different risk. Any cross-site scripting (XSS) bug, where an attacker runs JavaScript on your page, can read localStorage and steal the token. A HttpOnly cookie can't be read by scripts, but it needs the CSRF defenses above.
Neither choice is free. Pick one on purpose, then defend against its weak spot. The OWASP JWT guidance discusses token storage trade-offs in more depth.
Where CSRF fits in your wider security picture
CSRF is one of several issues that show up when an API is built quickly: weak CORS, missing cookie flags, broken access checks. Our free website security check is a passive outside look at subdomains, technology, DNS and email security. It does not test CORS, cookie flags or CSRF. Our security headers tool shows which headers you send. For a plain-English view of what attackers look at first, read is my website hackable.
Logic problems like "does this endpoint check the CSRF token on every route?" are hard for scanners to judge. That is where manual testing beats automated scans.
Key takeaways
- CSRF depends on automatic credentials, not on REST or JWT. Cookies are sent automatically, so they need protection.
- A Bearer token that your JavaScript adds to the
Authorizationheader normally does not need a CSRF token. - A JWT in a cookie behaves like any session cookie. Use
SameSite, a CSRF token, and Origin checks together. - Don't accept both a cookie and a header on the same endpoints unless you protect the cookie path.
- Test with
curl: if you rely on CSRF tokens, a state-changing request without the token should fail.
Want a human to check your API's login flow?
If you're unsure whether your cookies, CORS and CSRF checks hold up, a real person can test them by hand. A Bug Circuit audit is a manual security test of one website, including the API that site itself calls. A separate API used by other systems, such as a mobile app backend, is a standalone API assessment with its own fixed quote. It ends in a written report with each issue, its severity, evidence and fix steps. Essential is $49 one-time, and you can see the details on the pricing page. It's a focused small-site audit, not a compliance certificate or a multi-week enterprise pentest. We report the problems and explain the fix. Fixing is a separate service, quoted per issue, and only if you want it.
A real human security engineer audits your whole site by hand and sends a full report: every issue, its severity, and the exact fix. From $49, with a 14-day money-back guarantee.
See pricing