Skip to content

Cross-site request forgery (CSRF)

When is it relevant

A new or changed state-changing entry point (POST, PUT, PATCH, DELETE, or a GET that changes state) that authenticates with credentials the browser sends automatically: cookies, HTTP basic auth or client certificates. It doesn't apply when the only credential is a header the page has to set itself, such as Authorization: Bearer.

Attack

A page on another site makes the victim's browser send the request, and the browser attaches their cookies. This works through an auto-submitting form, an image tag for GET, or fetch with mode: 'no-cors'. JSON endpoints are exposed too if they also accept form or text/plain bodies, or if CORS allows credentials from any origin.

Mitigation

  • Set session cookies with SameSite=Lax or Strict, plus Secure and HttpOnly.
  • On unsafe methods, reject cross-site requests. Use a CSRF token, or check Sec-Fetch-Site or Origin against your own origin.
  • Never change state on GET. Accept only application/json bodies where possible.
  • Don't reflect arbitrary origins in Access-Control-Allow-Origin together with credentials.

Test

  • Point-in-time: send each state-changing request with the session cookie but without the CSRF token, with a foreign Origin or Sec-Fetch-Site: cross-site, and as a form or text/plain body. Each must be rejected. Check the cookie flags.
  • Continuous: an integration test that a cross-site state-changing request is rejected, and a config check on cookie flags and the CORS allowlist.

Examples

Mitigation options

Option When it fits Docs
SameSite on the session cookie Always; the cheapest baseline express-session
Double-submit token middleware (csrf-csrf) Form apps, and anywhere you need SameSite=None csrf-csrf
Synchronizer token in the session You already have a server-side session and want no extra dependency express-session
Custom header + strict CORS JSON APIs called by your own front end OWASP CSRF

csurf was the usual answer for years. It is deprecated and archived — do not add it to new code, and flag it in review (expressjs/csurf).

Vulnerable — cookie session, no SameSite, state-changing POST

app.use(session({ secret: process.env.SESSION_SECRET, cookie: { httpOnly: true } }))
// cookie.sameSite is undefined -> the browser default varies by browser and version

app.post('/account/email', requireAuth, async (req, res) => {
  await User.updateOne({ _id: req.user.id }, { email: req.body.email })
  res.redirect('/account')
})

Any site can auto-submit a form to this endpoint and the browser attaches the session cookie.

Vulnerable — state change on GET

app.get('/account/delete', requireAuth, deleteAccount)   // an <img> tag triggers it

Vulnerable — token issued but never bound or compared

app.use((req, res, next) => {
  res.locals.csrfToken = req.session.csrfToken ??= crypto.randomUUID()
  next()
})

app.post('/account/email', requireAuth, async (req, res) => {
  // the form renders the token, but nothing checks it on the way back in
  await User.updateOne({ _id: req.user.id }, { email: req.body.email })
  res.redirect('/account')
})

Mitigated — SameSite

app.use(session({
  secret: process.env.SESSION_SECRET,
  cookie: { httpOnly: true, secure: true, sameSite: 'lax' },
}))

lax still sends the cookie on top-level GET navigations, so it only protects you if no GET route changes state. Use strict when you don't need inbound links to arrive authenticated.

Mitigated — double-submit token middleware (csrf-csrf v4)

import { doubleCsrf } from 'csrf-csrf'

const { doubleCsrfProtection, generateCsrfToken, invalidCsrfTokenError } = doubleCsrf({
  getSecret: () => process.env.CSRF_SECRET,          // required
  getSessionIdentifier: (req) => req.session.id,     // required: binds token to session
  cookieOptions: { sameSite: 'lax', secure: true, path: '/' },
  // forms post the token in a field; the default reads the x-csrf-token header
  getCsrfTokenFromRequest: (req) => req.body?._csrf ?? req.get('x-csrf-token'),
})

// order matters: session and cookies must be parsed before the CSRF middleware
app.use(session({ /* ... */ }))
app.use(cookieParser())
app.use(express.urlencoded({ extended: false }))

// protect every state-changing request app-wide (GET/HEAD/OPTIONS are skipped)
app.use(doubleCsrfProtection)

app.get('/account', requireAuth, (req, res) => {
  res.render('account', { csrfToken: generateCsrfToken(req, res) })
})

app.post('/account/email', requireAuth, async (req, res) => {
  await User.updateOne({ _id: req.user.id }, { email: req.body.email })
  res.redirect('/account')
})

app.use((err, req, res, next) => {
  if (err === invalidCsrfTokenError) return res.status(403).render('error', { message: 'Invalid CSRF token' })
  next(err)
})
<form method="post" action="/account/email">
  <input type="hidden" name="_csrf" value="<%= csrfToken %>">
  <input type="email" name="email" required>
  <button type="submit">Save</button>
</form>

getSessionIdentifier is what makes this a real defence: the token is an HMAC over the session ID, so a token minted for the attacker's own session is rejected when replayed against the victim's.

Docs: csrf-csrf · cookie-parser · express-session

Mitigated — synchronizer token middleware of your own

import crypto from 'node:crypto'

const IGNORED = new Set(['GET', 'HEAD', 'OPTIONS'])

export function csrfTokens(req, res, next) {
  if (!req.session) return next(new Error('csrfTokens requires a session'))
  req.session.csrfSecret ??= crypto.randomBytes(32).toString('base64url')
  res.locals.csrfToken = req.session.csrfSecret        // available to every view
  next()
}

export function requireCsrfToken(req, res, next) {
  if (IGNORED.has(req.method)) return next()

  const expected = Buffer.from(req.session?.csrfSecret ?? '', 'utf8')
  const supplied = Buffer.from(req.body?._csrf ?? req.get('x-csrf-token') ?? '', 'utf8')

  if (expected.length === 0 || expected.length !== supplied.length ||
      !crypto.timingSafeEqual(expected, supplied)) {
    return res.status(403).render('error', { message: 'Invalid CSRF token' })
  }
  next()
}

app.use(csrfTokens)
app.use(requireCsrfToken)

The secret lives in the session, so it is per-user and dies with the session. timingSafeEqual needs equal-length buffers, which is why the length is checked first rather than inside the comparison.

Docs: crypto.timingSafeEqual · express-session

Mitigated — custom header for a JSON API

app.use(cors({ origin: 'https://app.example.com', credentials: true }))

app.use((req, res, next) => {
  if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next()
  if (req.get('X-Requested-With') !== 'XMLHttpRequest') return res.sendStatus(403)
  next()
})

This works because a cross-origin request carrying a custom header needs a preflight, which your CORS policy refuses. It fails if the endpoint also accepts simple content types.

Docs: cors

Bypasses to check

  • Token generated and rendered but never validated, validated only on some routes, or compared with == instead of a constant-time comparison.
  • Token not bound to the session: a global or per-process value, or getSessionIdentifier returning a constant, lets an attacker use a token minted from their own session.
  • The protection middleware mounted after the routes it should cover, or before cookieParser/express.urlencoded, so the token is never parsed.
  • ignoredMethods widened, or a state-changing GET — both leave a write path with no token.
  • Body parsed as application/json in the middleware but the route also accepts text/plain or application/x-www-form-urlencoded, which need no preflight.
  • Method override: ?_method=POST or X-HTTP-Method-Override turning a GET into a write.
  • sameSite: 'none' without a token; or the __Host- cookie prefix used with a domain set or path other than /, so the cookie is silently rejected and the check falls back to something weaker.
  • CORS that reflects Origin with credentials: true, or an allowlist matched with startsWith/includes so https://app.example.com.evil.com passes.
  • Login CSRF: the login route itself has no token, letting an attacker log a victim into the attacker's account.
  • Token rotated on every render but the old one still accepted indefinitely, or not rotated on privilege change (login, re-authentication).

What to grep for

  • sameSite, credentials: true, cors(, origin:
  • csurf, doubleCsrf, doubleCsrfProtection, generateCsrfToken, getSessionIdentifier, _csrf, X-Requested-With
  • timingSafeEqual, === next to a token comparison
  • app.get( on paths containing delete, remove, update, approve

Mitigation options

Option When it fits Docs
Spring Security CSRF protection (on by default) Any app that authenticates with a cookie Spring Security CSRF
CookieCsrfTokenRepository No server session (JWT in a cookie), or a JavaScript front end that reads the token Persisting the token
SameSite on the auth cookie Always; a baseline, not a replacement for tokens ResponseCookie
No cookie auth on the API (bearer tokens only) JSON APIs called with an Authorization header JWT resource server

Spring Security checks a CSRF token on every POST, PUT, PATCH and DELETE unless someone turns it off. So the review question is where it was turned off or narrowed (csrf.disable(), ignoringRequestMatchers), and whether those paths really can't be reached with a cookie. CSRF only matters where the browser sends credentials on its own: cookies (session or JWT) and HTTP Basic, not an Authorization: Bearer header the page sets itself.

Vulnerable — CSRF disabled while auth is a cookie

http
    .csrf(AbstractHttpConfigurer::disable)            // "it's a stateless JWT app"
    .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
    .addFilterBefore(new JwtCookieFilter(jwt), UsernamePasswordAuthenticationFilter.class);

Stateless isn't the same as CSRF-proof. If the JWT is in a cookie, the browser attaches it to a cross-site form post exactly like a session cookie.

Vulnerable — API exempted, but the API also accepts the cookie

http.csrf(csrf -> csrf.ignoringRequestMatchers("/api/**"));
String token = bearer(request);
if (token == null) token = cookie(request, "token");   // fallback makes /api cookie-authenticated

The exemption is safe only if /api/** authenticates exclusively from the Authorization header.

Vulnerable — state change on GET, or a mapping with no method

@GetMapping("/projects/{id}/delete")                      // an <img> tag triggers it
public String delete(@PathVariable String id) { … }

@RequestMapping("/account/email")                         // GET, POST, … all accepted
public String changeEmail(@RequestParam String email) { … }

CSRF protection skips GET, so either form is a write with no token.

Mitigated — keep the default, render the token

http.csrf(Customizer.withDefaults());                    // or leave csrf() out entirely
<#-- FreeMarker (.ftlh) -->
<form method="post" action="/account/email">
  <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}">
  <input type="email" name="email" required>
  <button type="submit">Save</button>
</form>

Thymeleaf with th:action and Spring's <form:form> tag add the hidden field automatically. FreeMarker and plain HTML need it written in, or exposed to the model with a @ModelAttribute("csrf") CsrfToken.

Docs: CSRF in forms

Mitigated — no server session: cookie token repository

http.csrf(csrf -> csrf
        .csrfTokenRepository(new CookieCsrfTokenRepository())          // HttpOnly by default
        .ignoringRequestMatchers(request -> request.getRequestURI().startsWith("/api/")));
// /api/** reads the bearer header only; pages read the cookie only
String token = request.getRequestURI().startsWith("/api/") ? bearer(request) : cookieToken(request);

The default repository keeps the token in the HttpSession, which a stateless app doesn't want, so the token goes in a cookie and the form echoes it back. Use CookieCsrfTokenRepository.withHttpOnlyFalse() only when JavaScript must read it, and send it back in the X-XSRF-TOKEN header. The /api exemption holds here because the API never looks at the cookie.

Docs: CookieCsrfTokenRepository · Single-page applications

Mitigated — SameSite on the auth cookie

ResponseCookie cookie = ResponseCookie.from("token", jwt)
        .httpOnly(true).secure(true).sameSite("Lax").path("/").build();
response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
server.servlet.session.cookie.same-site=lax

Lax still sends the cookie on top-level GET navigations, so it only helps if no GET route changes state. Keep the token check as well: SameSite doesn't stop requests from sibling subdomains, which count as same-site.

Docs: Session cookie properties

Bypasses to check

  • csrf.disable() or csrf(AbstractHttpConfigurer::disable) anywhere, and what authenticates those requests: a session cookie, a JWT cookie, HTTP Basic, or "remember me".
  • ignoringRequestMatchers(...) covering paths that also accept a cookie, or a matcher written with startsWith / contains that covers more than meant.
  • Several SecurityFilterChain beans: the chain for /api/** disables CSRF, and a later change moves a cookie-authenticated route under it.
  • @RequestMapping without method, @GetMapping on a write, or HiddenHttpMethodFilter (_method=DELETE) turning a POST into another verb. Spring Boot leaves it off unless spring.mvc.hiddenmethod.filter.enabled=true.
  • The token rendered in forms but a custom CsrfTokenRequestHandler or requireCsrfProtectionMatcher that never matches.
  • sameSite("None") without a token, or no SameSite at all on a hand-built Set-Cookie.
  • CORS that allows credentials from a reflected or loosely matched origin (allowedOriginPatterns("*") with allowCredentials(true)).
  • Login CSRF: /login excluded from CSRF so an attacker can log a victim into the attacker's account.

What to grep for

  • csrf(, disable(), ignoringRequestMatchers, requireCsrfProtectionMatcher, CsrfTokenRepository, withHttpOnlyFalse
  • _csrf, CsrfToken, X-XSRF-TOKEN
  • @RequestMapping( without method, @GetMapping on paths with delete, remove, update, approve
  • sameSite, same-site, ResponseCookie, allowCredentials, hiddenmethod

Mitigation options

Option When it fits Docs
Flask-WTF CSRFProtect Any form app with cookie sessions; protects every POST, PUT, PATCH and DELETE Flask-WTF CSRF
SESSION_COOKIE_SAMESITE='Lax' Always; the cheap baseline Flask config
Bearer tokens only, for the API JSON APIs that never read the session cookie OWASP CSRF

What CSRFProtect does on a request. It generates a random token, keeps it in the signed session, and renders a signed copy into each form through {{ csrf_token() }}. On every unsafe method, a before_request hook reads csrf_token from the form (or the X-CSRFToken header). It checks the signature and expiry, and checks that the token matches the one in the caller's session. If it doesn't, the request gets a 400. A page on another site can make the browser send the cookie, but it can't read the token, so its forged POST fails.

Vulnerable — no CSRF protection, state change on POST

@app.post('/settings/email')
@login_required
def change_email():
    users.update_email(g.user['id'], request.form['email'])
    return redirect('/settings')

Vulnerable — the API is exempt but also reads the cookie

csrf.exempt(api_bp)

@api_bp.post('/transfer')
def transfer():
    user = users.find_by_id(session['user_id'])      # cookie auth on an exempt blueprint

Vulnerable — state change on GET

@app.get('/repos/<rid>/delete')     # an <img src> on any site deletes it

Mitigated — global CSRFProtect, token in every form

csrf = CSRFProtect()
csrf.init_app(app)
app.config.update(SESSION_COOKIE_SAMESITE='Lax', SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SECURE=True)
<form method="post" action="{{ url_for('settings.change_email') }}">
  <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
  ...
</form>

Docs: Flask-WTF CSRF

Mitigated — an exempt API that only accepts bearer tokens

csrf.exempt(api_bp)

@api_bp.before_request
def _no_cookies():
    g.user = None                 # never call load_session_user() for /api; require_token sets g.user

Bypasses to check

  • @csrf.exempt on single views, and on blueprints that also read session.
  • WTF_CSRF_CHECK_DEFAULT = False with only some views calling csrf.protect().
  • WTF_CSRF_METHODS narrowed so that PUT or DELETE aren't checked.
  • CORS (Flask-CORS) with supports_credentials=True and a wildcard or reflected origin.
  • SESSION_COOKIE_SAMESITE=None without a token.

What to grep for

  • CSRFProtect, csrf.exempt, WTF_CSRF_, csrf_token(), X-CSRFToken
  • SESSION_COOKIE_SAMESITE, CORS(, supports_credentials
  • methods=['GET', @app.get( on routes that write

Resources