CSRF: how cross-site request forgery works, and the three checks that refuse it
Cross-site request forgery gets a signed-in visitor's browser to send a request they never meant to send.
This guide explains in plain English why browsers make that possible, what CSRF tokens, Origin and Sec-Fetch-Site checks and SameSite cookies each do, and where each one stops. It comes with a request matrix and a lab you can run on your own machine with Node.js alone.
In this guide
State-changing request matrix and CSRF lab
An illustration on invented hosts and a made-up account. Part 1 is a matrix of eight ways a request can reach a state-changing endpoint, with what a browser sends in each, sourced row by row, and what an anti-forgery token, an Origin or Sec-Fetch-Site check and SameSite each do, for cookie and bearer authentication.
How to use itHide the instructions
Parts 2 to 6 are a Node.js lab with no installs: a server with switchable checks, a scripted client that stands in for the browser, a regression test that fails when a check is switched off, and steps to see what your own browser sends. Run it on your own machine, for learning and for testing code you own.
csrf.txt
Introduction5 lines
Part 1: The state-changing request matrix145 lines
Part 2: The lab files498 lines
Part 3: Send every matrix row under seven server settings141 lines
Part 4: The regression test154 lines
Part 5: See what your own browser sends16 lines
Part 6: Point the test at your own code5 lines
Whole template999 lines
ILLUSTRATION ONLY. The account, its display name, the hosts app.example.com, blog.example.com and other.example.net, and every request below are invented for this page. The lab runs on your own machine, binds to 127.0.0.1, keeps everything in memory and can change nothing but a made-up display name. Use it for learning and for testing code you own.
What this asset is, and what it is not. Part 1 is a matrix of what a browser sends in eight situations, taken from the documents named in each row, and what each check does with it. Parts 2 to 4 are a lab whose scripted client stands in for the browser and sends the cookie and headers Part 1 lists. The lab proves what a server does with each set of headers. It does not prove what any browser sends: the sources do that, and Part 5 shows you how to watch your own browser.
Written and run on: Node.js 26.0.0, the only version it was run on. It uses node:http, node:crypto, node:test and node:assert, which ship with Node.js, so there is nothing to install. Every output below comes from that run; timings and ports will differ on your machine.
================================================================
PART 1: THE STATE-CHANGING REQUEST MATRIX
The endpoint in every row is POST /account/display-name on https://app.example.com, which renames the signed-in account. Each row is one way a request can reach it. For each row the matrix gives what a browser sends, with the document that says so in parentheses, then what each of the three checks does, what bearer authentication changes, the lab's result, and what is left if that check is the only one in place.
Source names used in the rows:
OWASP cheat sheet OWASP Cross-Site Request Forgery Prevention Cheat Sheet
WSTG-SESS-05 OWASP Web Security Testing Guide v4.2, Testing for Cross Site Request Forgery
CWE-352 MITRE CWE-352, Cross-Site Request Forgery
ASVS 5.0 V3 OWASP ASVS 5.0.0, V3 Web Frontend Security
MDN Set-Cookie MDN Web Docs, Set-Cookie header (SameSite attribute)
MDN Site glossary MDN Web Docs glossary, Site
MDN Origin glossary MDN Web Docs glossary, Origin
MDN Origin header MDN Web Docs, Origin header
MDN Sec-Fetch-Site MDN Web Docs, Sec-Fetch-Site header
MDN RequestInit MDN Web Docs, RequestInit (the credentials option)
MDN CORS guide MDN Web Docs, Cross-Origin Resource Sharing (CORS)
MDN CSRF guide MDN Web Docs, Cross-site request forgery (CSRF)
MDN same-origin policy MDN Web Docs, Same-origin policy
Fetch Standard WHATWG Fetch Standard, "append a request Origin header" (Living Standard)
Fetch Metadata draft W3C Fetch Metadata Request Headers, Working Draft of 21 September 2026 (a work in progress)
HTML Standard WHATWG HTML Standard, 7.1.1.1 Sites (Living Standard)
URL Standard WHATWG URL Standard, registrable domain (Living Standard)
cookie draft IETF draft-ietf-httpbis-rfc6265bis-22, an Internet-Draft that would replace RFC 6265
RFC 6750 RFC 6750, OAuth 2.0 Bearer Token Usage
How the three checks are set up here and in the lab:
Anti-forgery token: a random token stored in the server session, sent back in a hidden form field or an X-CSRF-Token header, and compared in constant time (OWASP cheat sheet).
Origin or Sec-Fetch-Site check: Sec-Fetch-Site must be same-origin. When the header is absent, Origin must equal https://app.example.com exactly, and a missing or null Origin is refused. This is a strict form of the OWASP cheat sheet's policy, which also allows same-site for teams that trust every sibling host.
SameSite: the attribute on the session cookie. The browser enforces it; the server only sets it.
Bearer authentication, in every row: your own script adds the token in an Authorization header (RFC 6750). It is neither a cookie nor HTTP authentication the browser stores, which is what WSTG-SESS-05 says CSRF relies on, and a page on another origin cannot read your origin's storage to find it (MDN same-origin policy). So in rows S2 to S8 the request arrives without it.
A cookie with no SameSite attribute: not covered row by row, because browsers differ. MDN Set-Cookie says some browsers use Lax as the default and points to its compatibility data, and that when Lax is applied as a default, cookies are also sent on POST requests if they were set no more than two minutes earlier. The OWASP cheat sheet says Chromium-based browsers treat such a cookie as Lax and Firefox and Safari do not. The cookie draft gives it a Default flag that its rules treat like Lax, and lets a browser send recently created cookies of that kind on cross-site top-level requests of any method, naming two minutes or less as a reasonable limit. Set the attribute yourself, and use Part 5 to see what your own browser does.
S1 SAME-ORIGIN FORM POST
Situation: a form on https://app.example.com posts to https://app.example.com/account/display-name.
What the browser sends:
Session cookie: sent under Strict, Lax and None, because this is a same-site request (MDN Set-Cookie).
Origin: https://app.example.com, or null if the page's Referrer-Policy is no-referrer. MDN says that, broadly speaking, browsers add Origin to same-origin requests other than GET and HEAD (MDN Origin header; Fetch Standard).
Sec-Fetch-Site: same-origin (Fetch Metadata draft; MDN Sec-Fetch-Site).
Token check: passes, because your own page supplied the token.
Origin or Sec-Fetch-Site check: passes.
SameSite: no effect.
Bearer authentication: your script adds the header and the request is accepted.
Lab result: 200 changed under all seven settings.
Left if only one check is present: this is the legitimate request. Every check has to let it through, and every lab setting does.
S2 CROSS-SITE FORM POST (A TOP-LEVEL NAVIGATION WITH POST)
Situation: a form on https://other.example.net posts to the endpoint.
What the browser sends:
Session cookie: Strict, not sent. Lax, not sent: Lax allows a cross-site top-level navigation only with a safe method, which excludes POST. None, sent (MDN Set-Cookie).
Origin: https://other.example.net, or null under some Referrer-Policy values (Fetch Standard; MDN Origin header).
Sec-Fetch-Site: cross-site (Fetch Metadata draft; MDN Sec-Fetch-Site).
Token check: refuses. Cross-origin reads are blocked by default, so as long as your page does not open them up, the other site has no token to send (MDN same-origin policy; MDN CORS guide).
Origin or Sec-Fetch-Site check: refuses on cross-site, or on an Origin that is null or does not match.
SameSite: Strict and Lax keep the cookie off, so the request carries no session. None does nothing.
Bearer authentication: no Authorization header, so no caller.
Lab result: A 200 changed. B, C, F and G 401 no-session. D 403 site. E 403 token.
Left if only one check is present:
Token only: covered, as long as the token stays out of URLs and logs (OWASP cheat sheet).
Origin or Sec-Fetch-Site only: covered while the browser sends one of the two headers. The check has to refuse a request that carries neither (OWASP cheat sheet).
SameSite only: a cookie set with None, clients that ignore the attribute, and cookies set without it in browsers that do not default to Lax (OWASP cheat sheet).
S3 CROSS-SITE LINK (A TOP-LEVEL NAVIGATION WITH GET)
Situation: a link on https://other.example.net points at /account/display-name?display_name=..., and the visitor clicks it. This row only matters if a GET request changes state. The lab keeps such a handler switched on to show what happens.
What the browser sends:
Session cookie: Strict, not sent. Lax, sent: a top-level navigation with a safe method, such as following a link. None, sent (MDN Set-Cookie).
Origin: not sent. The Fetch Standard adds Origin to a cross-origin request made in CORS mode (response tainting cors), or to one whose method is neither GET nor HEAD, and a followed link is neither (Fetch Standard).
Sec-Fetch-Site: cross-site (Fetch Metadata draft).
Token check: refuses if the GET handler checks a token, but a token in a URL can leak through browser history, log files and Referer headers (OWASP cheat sheet).
Origin or Sec-Fetch-Site check: refuses on cross-site. Without Sec-Fetch-Site there is no Origin to compare, so a check that lets a missing Origin through lets this request through.
SameSite: Lax does nothing here. Strict keeps the cookie off.
Bearer authentication: no Authorization header, so no caller.
Lab result: A and B 200 changed. C and G 401 no-session. D and F 403 site. E 403 token.
Left if only one check is present: SameSite=Lax alone leaves this row open. The fix is the method: a GET that changes nothing gives this row nothing to forge (OWASP cheat sheet; CWE-352; ASVS 5.0 V3, requirement 3.5.3). The regression test in Part 4 checks for it.
S4 CROSS-ORIGIN fetch() WITHOUT CREDENTIALS
Situation: a script on https://other.example.net calls fetch() to post to the endpoint and leaves the credentials option at its default.
What the browser sends:
Session cookie: not sent under any SameSite value. The credentials option defaults to same-origin, which sends credentials, cookies included, only to the same origin (MDN RequestInit).
Origin: https://other.example.net (Fetch Standard).
Sec-Fetch-Site: cross-site (Fetch Metadata draft).
Each check: the request carries no session, so it fails sign-in before any CSRF check applies.
Bearer authentication: no Authorization header, so no caller.
Lab result: 401 no-session under all seven settings.
Left if only one check is present: nothing in this row depends on a CSRF check.
S5 CROSS-ORIGIN fetch() WITH credentials: 'include', SENT AS A SIMPLE REQUEST
Situation: the same call with credentials set to include, a form-encoded body and no custom headers.
What the browser sends:
Session cookie: Strict and Lax, not sent, because Lax excludes requests made with fetch(). None, sent, unless the browser blocks or partitions third-party cookies; the cookie draft says most user agents limit them, in a variety of ways (MDN Set-Cookie; MDN CORS guide; cookie draft, section 7.1).
No preflight: a request that looks like a form submission needs no permission from your server before it is sent. The other page cannot read the response unless your CORS headers allow it, but the request has reached your server (MDN CORS guide).
Origin: https://other.example.net (Fetch Standard).
Sec-Fetch-Site: cross-site (Fetch Metadata draft).
With a JSON content type or a custom header instead, the browser sends an OPTIONS preflight first, and the actual request follows only if your response approves it, with credentials only if it also allows credentials (MDN CSRF guide; MDN CORS guide).
Token check: refuses. Origin or Sec-Fetch-Site check: refuses. SameSite: Strict and Lax keep the cookie off.
Bearer authentication: no Authorization header, so no caller.
Lab result: A 200 changed. B, C, F and G 401 no-session. D 403 site. E 403 token.
Left if only one check is present: as in S2. A CORS policy that names another origin and allows credentials opens non-simple requests from that origin too (MDN CSRF guide), which is the CORS misconfiguration guide's subject.
S6 IMAGE TAG ON ANOTHER SITE (A SUBRESOURCE GET)
Situation: a page on https://other.example.net includes an img element whose src is /account/display-name?display_name=...
What the browser sends:
Session cookie: Strict and Lax, not sent, because Lax excludes subresource requests such as images. None, sent, unless the browser blocks or partitions third-party cookies; the cookie draft says most user agents limit them, in a variety of ways (MDN Set-Cookie; MDN CORS guide; cookie draft, section 7.1).
Origin: not sent. A cross-origin GET in no-cors mode gets no Origin header (MDN Origin header; Fetch Standard).
Sec-Fetch-Site: cross-site (Fetch Metadata draft).
Token check: refuses if the handler checks one. Origin or Sec-Fetch-Site check: refuses on cross-site; without Sec-Fetch-Site there is no Origin either. SameSite: Strict and Lax keep the cookie off.
Bearer authentication: no Authorization header, so no caller.
Lab result: A 200 changed. B, C, F and G 401 no-session. D 403 site. E 403 token.
Left if only one check is present: an image can only send GET, so a GET that changes nothing leaves nothing here. This is the example WSTG-SESS-05 and the MDN CSRF guide both use.
S7 SIBLING SUBDOMAIN FORM POST (SAME SITE, DIFFERENT ORIGIN)
Situation: a form on https://blog.example.com posts to https://app.example.com.
What the browser sends:
Session cookie: sent under Strict, Lax and None. Both hosts share the registrable domain example.com, so this is a same-site request (MDN Site glossary; HTML Standard; OWASP cheat sheet).
Origin: https://blog.example.com, or null under some Referrer-Policy values (Fetch Standard; MDN Origin header).
Sec-Fetch-Site: same-site (Fetch Metadata draft; MDN Sec-Fetch-Site).
Token check: refuses. blog.example.com is a different origin and, unless your CORS policy lets it read your pages, cannot read the token (MDN Origin glossary; MDN same-origin policy; MDN CORS guide).
Origin or Sec-Fetch-Site check: refuses when only same-origin passes, as in the lab. A check that accepts same-site lets it through (OWASP cheat sheet).
SameSite: no effect under any value.
Bearer authentication: no Authorization header, so no caller.
Lab result: A, B and C 200 changed. D and F 403 site. E 403 token. G 401 no-session.
Left if only one check is present:
SameSite only: open to every host under example.com, including a subdomain someone else has taken over (OWASP cheat sheet).
Token only: covered by a token held in the session or a signed double-submit token bound to it. A naive double-submit cookie can be planted from a sibling subdomain (OWASP cheat sheet).
Origin or Sec-Fetch-Site only: covered if same-site is refused.
S8 SAME HOST, ANOTHER PORT (SAME SITE, DIFFERENT ORIGIN)
Situation: a form on https://app.example.com:8443, such as an admin tool or a development server, posts to https://app.example.com.
What the browser sends:
Session cookie: sent under Strict, Lax and None. The port is ignored when deciding the site, so this is a same-site request even though the two are different origins (MDN Site glossary; MDN Origin glossary; HTML Standard).
Origin: https://app.example.com:8443, or null under some Referrer-Policy values (Fetch Standard; MDN Origin header).
Sec-Fetch-Site: same-site, because same-origin needs the same scheme, host and port (MDN Sec-Fetch-Site; Fetch Metadata draft).
Token check: refuses. Another port is another origin and, unless your CORS policy lets it read your pages, cannot read the token (MDN Origin glossary; MDN same-origin policy; MDN CORS guide).
Origin or Sec-Fetch-Site check: refuses. The Origin carries the port, so it does not match exactly.
SameSite: no effect under any value.
Bearer authentication: no Authorization header, so no caller.
Lab result: A, B and C 200 changed. D and F 403 site. E 403 token. G 401 no-session.
Left if only one check is present: SameSite only leaves it open to anything served on another port of the same host.
================================================================
PART 2: THE LAB FILES
================================================================
Make an empty folder, save the four files below into it with the names shown, and open a terminal in that folder.
================================================================
FILE 1 OF 4: csrf-lab-server.mjs
================================================================
// csrf-lab-server.mjs: one invented account and one state-changing endpoint.
// Illustration only. It listens on 127.0.0.1, keeps everything in memory and
// changes nothing but the display name of a made-up account.
import { createServer } from 'node:http'
import { randomBytes, timingSafeEqual } from 'node:crypto'
// The origin this illustration pretends to be served from. The Origin check
// compares against this configured value, never against the Host header.
export const APP_ORIGIN = 'https://app.example.com'
// settings: auth ('cookie' or 'bearer'), tokenCheck and originCheck (true or
// false), sameSite ('Strict', 'Lax', 'None' or '' for no attribute),
// getChangesName (true is the mistake: a GET request that changes state)
// and logRequests (print each decision).
export function startLabServer(settings, port) {
const state = { displayName: 'Sam Example', sessions: new Map(), bearerTokens: new Set() }
const server = createServer(function (request, response) {
routeRequest(settings, state, request, response)
})
return new Promise(function (resolve) {
server.listen(port || 0, '127.0.0.1', function () {
resolve({ server: server, state: state, port: server.address().port })
})
})
}
function routeRequest(settings, state, request, response) {
const url = new URL(request.url, 'http://127.0.0.1')
if (request.method === 'POST' && url.pathname === '/lab/sign-in') return signIn(settings, state, response)
if (url.pathname === '/account/display-name') return handleDisplayName(settings, state, request, response, url)
if (request.method === 'GET' && url.pathname === '/') return sendAccountPage(settings, state, request, response)
sendText(response, 404, 'not-found')
}
// Signing in stands in for loading the account page: a cookie session gets
// a session cookie plus the anti-forgery token the page would embed, and
// bearer mode gets a token that the app's own script would keep.
function signIn(settings, state, response) {
if (settings.auth === 'bearer') {
const bearerToken = randomBytes(24).toString('base64url')
state.bearerTokens.add(bearerToken)
return sendJson(response, 200, { bearerToken: bearerToken })
}
const session = createSession(state)
response.setHeader('Set-Cookie', buildSessionCookie(session.id, settings.sameSite))
sendJson(response, 200, { csrfToken: session.csrfToken })
}
function createSession(state) {
const session = { id: randomBytes(24).toString('base64url'), csrfToken: randomBytes(24).toString('base64url') }
state.sessions.set(session.id, session)
return session
}
// Real deployments add Secure to every cookie. Here it is added only where
// SameSite=None requires it, so the browser steps work over plain http.
function buildSessionCookie(sessionId, sameSite) {
const parts = ['session=' + sessionId, 'Path=/', 'HttpOnly']
if (sameSite) parts.push('SameSite=' + sameSite)
if (sameSite === 'None') parts.push('Secure')
return parts.join('; ')
}
async function handleDisplayName(settings, state, request, response, url) {
const result = await decideDisplayNameChange(settings, state, request, url)
if (settings.logRequests) logDecision(request, result)
sendText(response, result.status, result.code)
}
// The checks run in this order: who is calling, where the request came
// from, then the anti-forgery token. Each one can be switched off.
async function decideDisplayNameChange(settings, state, request, url) {
const isGet = request.method === 'GET'
if (!isGet && request.method !== 'POST') return { status: 405, code: 'method' }
if (isGet && !settings.getChangesName) return { status: 405, code: 'method' }
const fields = isGet ? url.searchParams : new URLSearchParams(await readBody(request))
const caller = findCaller(settings, state, request)
if (!caller) return { status: 401, code: 'no-session' }
if (settings.originCheck) {
const sourceProblem = findSourceProblem(request)
if (sourceProblem) return { status: 403, code: sourceProblem }
}
if (settings.tokenCheck && settings.auth === 'cookie') {
const sentToken = fields.get('csrf_token') || readHeader(request, 'X-CSRF-Token')
if (!tokensMatch(caller.csrfToken, sentToken)) return { status: 403, code: 'token' }
}
state.displayName = fields.get('display_name') || ''
return { status: 200, code: 'changed' }
}
// Cookie mode reads the session cookie. Bearer mode ignores cookies and
// reads only the Authorization header.
function findCaller(settings, state, request) {
if (settings.auth === 'bearer') {
const header = readHeader(request, 'Authorization') || ''
const token = header.startsWith('Bearer ') ? header.slice(7) : ''
return state.bearerTokens.has(token) ? { csrfToken: '' } : null
}
return state.sessions.get(readCookie(request, 'session')) || null
}
// Sec-Fetch-Site first. Only same-origin passes, so same-site requests from
// a sibling subdomain or another port are refused. A browser that sends no
// Sec-Fetch-Site falls back to an exact Origin match, and a missing or null
// Origin is refused rather than trusted.
function findSourceProblem(request) {
const site = readHeader(request, 'Sec-Fetch-Site')
if (site) return site === 'same-origin' ? '' : 'site'
const origin = readHeader(request, 'Origin')
return origin === APP_ORIGIN ? '' : 'origin'
}
function tokensMatch(expected, received) {
if (!expected || !received) return false
const expectedBytes = Buffer.from(expected)
const receivedBytes = Buffer.from(received)
if (expectedBytes.length !== receivedBytes.length) return false
return timingSafeEqual(expectedBytes, receivedBytes)
}
// Node.js stores incoming header names in lower case.
function readHeader(request, name) {
return request.headers[name.toLowerCase()]
}
function readCookie(request, name) {
const pairs = (readHeader(request, 'Cookie') || '').split('; ')
for (const pair of pairs) {
if (pair.startsWith(name + '=')) return pair.slice(name.length + 1)
}
return ''
}
function readBody(request) {
return new Promise(function (resolve) {
const chunks = []
request.on('data', function (chunk) { chunks.push(chunk) })
request.on('end', function () { resolve(Buffer.concat(chunks).toString('utf8')) })
})
}
// Used by browser-check.mjs: the account page a signed-in user would see,
// with a form that carries this session's token.
function sendAccountPage(settings, state, request, response) {
let session = state.sessions.get(readCookie(request, 'session'))
if (!session) {
session = createSession(state)
response.setHeader('Set-Cookie', buildSessionCookie(session.id, settings.sameSite))
}
const html = [
'<!doctype html><meta charset="utf-8"><title>CSRF lab account</title>',
'<p>Display name: <strong>' + escapeHtml(state.displayName) + '</strong></p>',
'<form method="post" action="/account/display-name">',
'<input name="display_name" value="Changed from the account page">',
'<input type="hidden" name="csrf_token" value="' + escapeHtml(session.csrfToken) + '">',
'<button>Save display name</button></form>',
].join('')
response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
response.end(html)
}
function escapeHtml(text) {
return String(text)
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
.replaceAll("'", ''')
}
function logDecision(request, result) {
const cookieState = readCookie(request, 'session') ? 'present' : 'absent'
console.log(
request.method + ' /account/display-name' +
' | Origin: ' + (readHeader(request, 'Origin') || '(none)') +
' | Sec-Fetch-Site: ' + (readHeader(request, 'Sec-Fetch-Site') || '(none)') +
' | session cookie: ' + cookieState +
' | result: ' + result.status + ' ' + result.code
)
}
function sendText(response, status, text) {
response.writeHead(status, { 'content-type': 'text/plain; charset=utf-8' })
response.end(text)
}
function sendJson(response, status, body) {
response.writeHead(status, { 'content-type': 'application/json' })
response.end(JSON.stringify(body))
}
================================================================
FILE 2 OF 4: run-matrix.mjs
================================================================
// run-matrix.mjs: sends one request per matrix row to the lab server under
// seven settings and prints what the server did with each.
// This client stands in for the browser. Which cookie and headers it sends
// in each row is copied from the sources named in the matrix, so the output
// shows what the server does with those headers. It does not show what any
// browser does; the browser steps in the lab are how you check that.
import { request as httpRequest } from 'node:http'
import { APP_ORIGIN, startLabServer } from './csrf-lab-server.mjs'
const OTHER_SITE = 'https://other.example.net'
const ALL_VALUES = ['Strict', 'Lax', 'None']
const FORM_TYPE = 'application/x-www-form-urlencoded'
// cookieUnder lists the SameSite values under which a browser attaches the
// session cookie in that situation. carriesToken is true only where the
// request comes from your own page, which is the only page holding the token.
const situations = [
{ id: 'S1', label: 'same-origin form post', method: 'POST',
headers: { Origin: APP_ORIGIN, 'Sec-Fetch-Site': 'same-origin' }, cookieUnder: ALL_VALUES, carriesToken: true },
{ id: 'S2', label: 'cross-site form post', method: 'POST',
headers: { Origin: OTHER_SITE, 'Sec-Fetch-Site': 'cross-site' }, cookieUnder: ['None'], carriesToken: false },
{ id: 'S3', label: 'cross-site link (top-level GET)', method: 'GET',
headers: { 'Sec-Fetch-Site': 'cross-site' }, cookieUnder: ['Lax', 'None'], carriesToken: false },
{ id: 'S4', label: 'cross-origin fetch, no credentials', method: 'POST',
headers: { Origin: OTHER_SITE, 'Sec-Fetch-Site': 'cross-site' }, cookieUnder: [], carriesToken: false },
{ id: 'S5', label: 'cross-origin fetch, credentials include', method: 'POST',
headers: { Origin: OTHER_SITE, 'Sec-Fetch-Site': 'cross-site' }, cookieUnder: ['None'], carriesToken: false },
{ id: 'S6', label: 'image tag on another site', method: 'GET',
headers: { 'Sec-Fetch-Site': 'cross-site' }, cookieUnder: ['None'], carriesToken: false },
{ id: 'S7', label: 'sibling subdomain form post', method: 'POST',
headers: { Origin: 'https://blog.example.com', 'Sec-Fetch-Site': 'same-site' }, cookieUnder: ALL_VALUES, carriesToken: false },
{ id: 'S8', label: 'same host, another port, form post', method: 'POST',
headers: { Origin: 'https://app.example.com:8443', 'Sec-Fetch-Site': 'same-site' }, cookieUnder: ALL_VALUES, carriesToken: false },
]
// Every setting keeps the mistaken GET handler on, so the GET rows show
// what each check does when a GET request changes state.
const settingsList = [
{ id: 'A', label: 'no checks, SameSite=None', auth: 'cookie', tokenCheck: false, originCheck: false, sameSite: 'None' },
{ id: 'B', label: 'SameSite=Lax only', auth: 'cookie', tokenCheck: false, originCheck: false, sameSite: 'Lax' },
{ id: 'C', label: 'SameSite=Strict only', auth: 'cookie', tokenCheck: false, originCheck: false, sameSite: 'Strict' },
{ id: 'D', label: 'Origin and Sec-Fetch-Site check only', auth: 'cookie', tokenCheck: false, originCheck: true, sameSite: 'None' },
{ id: 'E', label: 'token check only', auth: 'cookie', tokenCheck: true, originCheck: false, sameSite: 'None' },
{ id: 'F', label: 'all three: token, origin, Lax', auth: 'cookie', tokenCheck: true, originCheck: true, sameSite: 'Lax' },
{ id: 'G', label: 'bearer token, no other check', auth: 'bearer', tokenCheck: false, originCheck: false, sameSite: '' },
]
function sendRequest(port, method, path, headers, body) {
return new Promise(function (resolve, reject) {
const outgoing = httpRequest({ host: '127.0.0.1', port: port, method: method, path: path, headers: headers }, function (response) {
const chunks = []
response.on('data', function (chunk) { chunks.push(chunk) })
response.on('end', function () {
resolve({ status: response.statusCode, headers: response.headers, body: Buffer.concat(chunks).toString('utf8') })
})
})
outgoing.on('error', reject)
outgoing.end(body)
})
}
async function signIn(port) {
const response = await sendRequest(port, 'POST', '/lab/sign-in', {}, '')
const setCookie = response.headers['set-cookie'] || []
return { cookie: setCookie.length ? setCookie[0].split(';')[0] : '', tokens: JSON.parse(response.body) }
}
// Builds the request a browser would send in this situation under these settings.
function buildRequest(situation, settings, signedIn) {
const fields = new URLSearchParams({ display_name: 'Forged by ' + situation.id })
if (situation.carriesToken && settings.auth === 'cookie') fields.set('csrf_token', signedIn.tokens.csrfToken)
const headers = Object.assign({}, situation.headers)
const cookieSent = settings.auth === 'cookie' && situation.cookieUnder.includes(settings.sameSite)
if (cookieSent) headers.Cookie = signedIn.cookie
if (settings.auth === 'bearer' && situation.carriesToken) headers.Authorization = 'Bearer ' + signedIn.tokens.bearerToken
if (situation.method === 'GET') {
return { path: '/account/display-name?' + fields.toString(), headers: headers, body: '' }
}
headers['Content-Type'] = FORM_TYPE
return { path: '/account/display-name', headers: headers, body: fields.toString() }
}
async function runSettings(settings) {
const lab = await startLabServer(Object.assign({ getChangesName: true }, settings))
const signedIn = await signIn(lab.port)
const results = {}
for (const situation of situations) {
const built = buildRequest(situation, settings, signedIn)
const response = await sendRequest(lab.port, situation.method, built.path, built.headers, built.body)
results[situation.id] = response.status + ' ' + response.body
}
lab.server.close()
return results
}
function describeRequest(situation) {
const query = situation.method === 'GET' ? '?display_name=Forged+by+' + situation.id : ''
const lines = [' ' + situation.method + ' /account/display-name' + query]
for (const name of Object.keys(situation.headers)) lines.push(' ' + name + ': ' + situation.headers[name])
if (situation.method === 'POST') lines.push(' Content-Type: ' + FORM_TYPE)
const cookieNote = situation.cookieUnder.length ? 'sent under SameSite=' + situation.cookieUnder.join(', ') : 'not sent under any SameSite value'
lines.push(' Session cookie: ' + cookieNote)
lines.push(' Anti-forgery token: ' + (situation.carriesToken ? 'sent (your own page)' : 'not sent'))
lines.push(' Bearer token header: ' + (situation.carriesToken ? 'sent (your own script)' : 'not sent'))
return lines
}
async function main() {
const resultsBySettings = {}
for (const settings of settingsList) resultsBySettings[settings.id] = await runSettings(settings)
for (const situation of situations) {
console.log(situation.id + ' ' + situation.label)
for (const line of describeRequest(situation)) console.log(line)
console.log(' Server response under each setting:')
for (const settings of settingsList) {
const name = (settings.id + ' ' + settings.label + ' ').padEnd(42, '.')
console.log(' ' + name + ' ' + resultsBySettings[settings.id][situation.id])
}
console.log('')
}
}
main()
================================================================
FILE 3 OF 4: csrf-checks.test.mjs
================================================================
// csrf-checks.test.mjs: each test isolates one check, holding the other
// check's input valid, so switching a check off fails that check's tests.
// Run: node csrf-checks.test.mjs (every check on: all tests pass)
// node csrf-checks.test.mjs token-off (the two token tests fail)
// node csrf-checks.test.mjs origin-off (the four origin tests fail)
// node csrf-checks.test.mjs samesite-off (the cookie attribute test fails)
// node csrf-checks.test.mjs get-on (the GET test fails)
import assert from 'node:assert/strict'
import { request as httpRequest } from 'node:http'
import { after, before, test } from 'node:test'
import { APP_ORIGIN, startLabServer } from './csrf-lab-server.mjs'
const switchedOff = process.argv[2] || 'none'
const knownSwitches = ['none', 'token-off', 'origin-off', 'samesite-off', 'get-on']
if (!knownSwitches.includes(switchedOff)) throw new Error('Unknown switch: ' + switchedOff)
const settings = {
auth: 'cookie',
tokenCheck: switchedOff !== 'token-off',
originCheck: switchedOff !== 'origin-off',
sameSite: switchedOff === 'samesite-off' ? '' : 'Lax',
getChangesName: switchedOff === 'get-on',
}
let lab
let signedIn
function sendRequest(method, path, headers, body) {
return new Promise(function (resolve, reject) {
const options = { host: '127.0.0.1', port: lab.port, method: method, path: path, headers: headers }
const outgoing = httpRequest(options, function (response) {
const chunks = []
response.on('data', function (chunk) { chunks.push(chunk) })
response.on('end', function () {
resolve({ status: response.statusCode, headers: response.headers, body: Buffer.concat(chunks).toString('utf8') })
})
})
outgoing.on('error', reject)
outgoing.end(body)
})
}
// Posts a display name with the signed-in session cookie and the given
// headers. token is the anti-forgery token to send, or '' for none.
function postName(name, headers, token) {
const fields = new URLSearchParams({ display_name: name })
if (token) fields.set('csrf_token', token)
const allHeaders = Object.assign({ Cookie: signedIn.cookie, 'Content-Type': 'application/x-www-form-urlencoded' }, headers)
return sendRequest('POST', '/account/display-name', allHeaders, fields.toString())
}
before(async function () {
lab = await startLabServer(settings)
const response = await sendRequest('POST', '/lab/sign-in', {}, '')
const setCookie = response.headers['set-cookie'][0]
signedIn = { setCookie: setCookie, cookie: setCookie.split(';')[0], csrfToken: JSON.parse(response.body).csrfToken }
})
after(function () {
lab.server.close()
})
const SAME_ORIGIN = { Origin: APP_ORIGIN, 'Sec-Fetch-Site': 'same-origin' }
test('baseline: your own page, with its token, changes the name', async function () {
const result = await postName('Baseline', SAME_ORIGIN, signedIn.csrfToken)
assert.equal(result.status, 200)
assert.equal(lab.state.displayName, 'Baseline')
})
test('token: a same-origin post with no token is refused', async function () {
const result = await postName('No token', SAME_ORIGIN, '')
assert.equal(result.status, 403)
assert.notEqual(lab.state.displayName, 'No token')
})
test('token: a same-origin post with a wrong token is refused', async function () {
const result = await postName('Wrong token', SAME_ORIGIN, 'not-the-session-token')
assert.equal(result.status, 403)
assert.notEqual(lab.state.displayName, 'Wrong token')
})
test('origin: Sec-Fetch-Site cross-site is refused even with a valid token', async function () {
const result = await postName('Cross-site', { Origin: 'https://other.example.net', 'Sec-Fetch-Site': 'cross-site' }, signedIn.csrfToken)
assert.equal(result.status, 403)
assert.notEqual(lab.state.displayName, 'Cross-site')
})
test('origin: Sec-Fetch-Site same-site from another port is refused', async function () {
const result = await postName('Other port', { Origin: 'https://app.example.com:8443', 'Sec-Fetch-Site': 'same-site' }, signedIn.csrfToken)
assert.equal(result.status, 403)
assert.notEqual(lab.state.displayName, 'Other port')
})
test('origin: with no Sec-Fetch-Site, a foreign Origin is refused', async function () {
const result = await postName('Foreign origin', { Origin: 'https://app.example.com.other.example.net' }, signedIn.csrfToken)
assert.equal(result.status, 403)
assert.notEqual(lab.state.displayName, 'Foreign origin')
})
test('origin: with no Sec-Fetch-Site, Origin null is refused', async function () {
const result = await postName('Null origin', { Origin: 'null' }, signedIn.csrfToken)
assert.equal(result.status, 403)
assert.notEqual(lab.state.displayName, 'Null origin')
})
test('cookie: the session cookie is issued with SameSite=Lax', function () {
assert.match(signedIn.setCookie, /; SameSite=Lax/)
})
test('GET: a cross-site link to the endpoint changes nothing', async function () {
const headers = { Cookie: signedIn.cookie, 'Sec-Fetch-Site': 'cross-site' }
const result = await sendRequest('GET', '/account/display-name?display_name=Linked', headers, '')
assert.equal(result.status, 405)
assert.notEqual(lab.state.displayName, 'Linked')
})
================================================================
FILE 4 OF 4: browser-check.mjs
================================================================
// browser-check.mjs: lets your own browser show which cookie and headers it
// sends. The token and origin checks are off, so the result depends only on
// what your browser sent, and the terminal prints what arrived.
// Run: node browser-check.mjs (session cookie with SameSite=Lax)
// node browser-check.mjs Strict (session cookie with SameSite=Strict)
// node browser-check.mjs unset (no SameSite attribute: your browser's default)
// Stop it with Ctrl+C.
import { createServer } from 'node:http'
import { startLabServer } from './csrf-lab-server.mjs'
const choice = process.argv[2] || 'Lax'
if (!['Lax', 'Strict', 'unset'].includes(choice)) throw new Error('Use Lax, Strict or unset')
const lab = await startLabServer({
auth: 'cookie',
tokenCheck: false,
originCheck: false,
sameSite: choice === 'unset' ? '' : choice,
getChangesName: false,
logRequests: true,
})
// A second address that is not the account page. Its form posts to the lab
// without a token, the way a page you do not control could.
const formTarget = 'http://127.0.0.1:' + lab.port + '/account/display-name'
const otherPage = [
'<!doctype html><meta charset="utf-8"><title>Another address</title>',
'<p>This page is not the account page. The button posts to ' + formTarget + '.</p>',
'<form method="post" action="' + formTarget + '">',
'<input name="display_name" value="Changed from another address">',
'<button>Post to the account</button></form>',
].join('')
const other = createServer(function (request, response) {
response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
response.end(otherPage)
})
other.listen(0, '127.0.0.1', function () {
const otherPort = other.address().port
console.log('SameSite setting on the session cookie: ' + choice)
console.log('1. Sign in (same origin): http://127.0.0.1:' + lab.port + '/')
console.log('2. Same site, another port: http://127.0.0.1:' + otherPort + '/')
console.log('3. Another site (localhost): http://localhost:' + otherPort + '/')
console.log('Each post to the account prints one line below.')
})
================================================================
PART 3: SEND EVERY MATRIX ROW UNDER SEVEN SERVER SETTINGS
================================================================
Command: node run-matrix.mjs
S1 same-origin form post
POST /account/display-name
Origin: https://app.example.com
Sec-Fetch-Site: same-origin
Content-Type: application/x-www-form-urlencoded
Session cookie: sent under SameSite=Strict, Lax, None
Anti-forgery token: sent (your own page)
Bearer token header: sent (your own script)
Server response under each setting:
A no checks, SameSite=None ............... 200 changed
B SameSite=Lax only ...................... 200 changed
C SameSite=Strict only ................... 200 changed
D Origin and Sec-Fetch-Site check only ... 200 changed
E token check only ....................... 200 changed
F all three: token, origin, Lax .......... 200 changed
G bearer token, no other check ........... 200 changed
S2 cross-site form post
POST /account/display-name
Origin: https://other.example.net
Sec-Fetch-Site: cross-site
Content-Type: application/x-www-form-urlencoded
Session cookie: sent under SameSite=None
Anti-forgery token: not sent
Bearer token header: not sent
Server response under each setting:
A no checks, SameSite=None ............... 200 changed
B SameSite=Lax only ...................... 401 no-session
C SameSite=Strict only ................... 401 no-session
D Origin and Sec-Fetch-Site check only ... 403 site
E token check only ....................... 403 token
F all three: token, origin, Lax .......... 401 no-session
G bearer token, no other check ........... 401 no-session
S3 cross-site link (top-level GET)
GET /account/display-name?display_name=Forged+by+S3
Sec-Fetch-Site: cross-site
Session cookie: sent under SameSite=Lax, None
Anti-forgery token: not sent
Bearer token header: not sent
Server response under each setting:
A no checks, SameSite=None ............... 200 changed
B SameSite=Lax only ...................... 200 changed
C SameSite=Strict only ................... 401 no-session
D Origin and Sec-Fetch-Site check only ... 403 site
E token check only ....................... 403 token
F all three: token, origin, Lax .......... 403 site
G bearer token, no other check ........... 401 no-session
S4 cross-origin fetch, no credentials
POST /account/display-name
Origin: https://other.example.net
Sec-Fetch-Site: cross-site
Content-Type: application/x-www-form-urlencoded
Session cookie: not sent under any SameSite value
Anti-forgery token: not sent
Bearer token header: not sent
Server response under each setting:
A no checks, SameSite=None ............... 401 no-session
B SameSite=Lax only ...................... 401 no-session
C SameSite=Strict only ................... 401 no-session
D Origin and Sec-Fetch-Site check only ... 401 no-session
E token check only ....................... 401 no-session
F all three: token, origin, Lax .......... 401 no-session
G bearer token, no other check ........... 401 no-session
S5 cross-origin fetch, credentials include
POST /account/display-name
Origin: https://other.example.net
Sec-Fetch-Site: cross-site
Content-Type: application/x-www-form-urlencoded
Session cookie: sent under SameSite=None
Anti-forgery token: not sent
Bearer token header: not sent
Server response under each setting:
A no checks, SameSite=None ............... 200 changed
B SameSite=Lax only ...................... 401 no-session
C SameSite=Strict only ................... 401 no-session
D Origin and Sec-Fetch-Site check only ... 403 site
E token check only ....................... 403 token
F all three: token, origin, Lax .......... 401 no-session
G bearer token, no other check ........... 401 no-session
S6 image tag on another site
GET /account/display-name?display_name=Forged+by+S6
Sec-Fetch-Site: cross-site
Session cookie: sent under SameSite=None
Anti-forgery token: not sent
Bearer token header: not sent
Server response under each setting:
A no checks, SameSite=None ............... 200 changed
B SameSite=Lax only ...................... 401 no-session
C SameSite=Strict only ................... 401 no-session
D Origin and Sec-Fetch-Site check only ... 403 site
E token check only ....................... 403 token
F all three: token, origin, Lax .......... 401 no-session
G bearer token, no other check ........... 401 no-session
S7 sibling subdomain form post
POST /account/display-name
Origin: https://blog.example.com
Sec-Fetch-Site: same-site
Content-Type: application/x-www-form-urlencoded
Session cookie: sent under SameSite=Strict, Lax, None
Anti-forgery token: not sent
Bearer token header: not sent
Server response under each setting:
A no checks, SameSite=None ............... 200 changed
B SameSite=Lax only ...................... 200 changed
C SameSite=Strict only ................... 200 changed
D Origin and Sec-Fetch-Site check only ... 403 site
E token check only ....................... 403 token
F all three: token, origin, Lax .......... 403 site
G bearer token, no other check ........... 401 no-session
S8 same host, another port, form post
POST /account/display-name
Origin: https://app.example.com:8443
Sec-Fetch-Site: same-site
Content-Type: application/x-www-form-urlencoded
Session cookie: sent under SameSite=Strict, Lax, None
Anti-forgery token: not sent
Bearer token header: not sent
Server response under each setting:
A no checks, SameSite=None ............... 200 changed
B SameSite=Lax only ...................... 200 changed
C SameSite=Strict only ................... 200 changed
D Origin and Sec-Fetch-Site check only ... 403 site
E token check only ....................... 403 token
F all three: token, origin, Lax .......... 403 site
G bearer token, no other check ........... 401 no-session
Reading the evidence:
S1 Your own page's request is accepted under every setting, which is the first thing any CSRF check has to get right.
S2, S5, S6 Each check on its own refuses the forged request. Only setting A, with no checks and SameSite=None, changes the name.
S3 SameSite=Lax alone (B) lets the forged GET change the name, because Lax sends the cookie on a top-level navigation with a safe method. The token and origin checks refuse it, and with no GET handler that changes state there is nothing to refuse.
S4 With credentials left at the fetch() default, no cookie travels, so every setting answers 401.
S7, S8 All three SameSite settings (A, B and C) let the change through, because a sibling subdomain and another port are the same site. Of the cookie settings, only the token check (E) and the same-origin-only origin check (D and F) refuse them.
G With a bearer token instead of a cookie, every forged row arrives without the Authorization header and is refused.
================================================================
PART 4: THE REGRESSION TEST
================================================================
Each test isolates one check and holds the other check's input valid, so switching one check off fails that check's tests and no others. Run it in the pipeline that deploys your app.
Command: node csrf-checks.test.mjs
✔ baseline: your own page, with its token, changes the name (9.944125ms)
✔ token: a same-origin post with no token is refused (0.560458ms)
✔ token: a same-origin post with a wrong token is refused (0.400916ms)
✔ origin: Sec-Fetch-Site cross-site is refused even with a valid token (0.434917ms)
✔ origin: Sec-Fetch-Site same-site from another port is refused (0.398666ms)
✔ origin: with no Sec-Fetch-Site, a foreign Origin is refused (0.313541ms)
✔ origin: with no Sec-Fetch-Site, Origin null is refused (0.299667ms)
✔ cookie: the session cookie is issued with SameSite=Lax (0.095666ms)
✔ GET: a cross-site link to the endpoint changes nothing (0.368583ms)
ℹ tests 9
ℹ suites 0
ℹ pass 9
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 18.157542
The process exits with code 0.
Command: node csrf-checks.test.mjs token-off
✔ baseline: your own page, with its token, changes the name (9.96725ms)
✖ token: a same-origin post with no token is refused (1.237125ms)
✖ token: a same-origin post with a wrong token is refused (0.503625ms)
✔ origin: Sec-Fetch-Site cross-site is refused even with a valid token (0.442375ms)
✔ origin: Sec-Fetch-Site same-site from another port is refused (0.358ms)
✔ origin: with no Sec-Fetch-Site, a foreign Origin is refused (0.290542ms)
✔ origin: with no Sec-Fetch-Site, Origin null is refused (0.267375ms)
✔ cookie: the session cookie is issued with SameSite=Lax (0.095375ms)
✔ GET: a cross-site link to the endpoint changes nothing (0.333667ms)
ℹ tests 9
ℹ suites 0
ℹ pass 7
ℹ fail 2
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 18.230417
✖ failing tests:
test at csrf-checks.test.mjs:71:1
✖ token: a same-origin post with no token is refused (1.237125ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
200 !== 403
(stack trace lines removed here)
test at csrf-checks.test.mjs:77:1
✖ token: a same-origin post with a wrong token is refused (0.503625ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
200 !== 403
(stack trace lines removed here)
Command: node csrf-checks.test.mjs origin-off
✔ baseline: your own page, with its token, changes the name (10.372417ms)
✔ token: a same-origin post with no token is refused (0.598917ms)
✔ token: a same-origin post with a wrong token is refused (0.385167ms)
✖ origin: Sec-Fetch-Site cross-site is refused even with a valid token (1.058625ms)
✖ origin: Sec-Fetch-Site same-site from another port is refused (0.448792ms)
✖ origin: with no Sec-Fetch-Site, a foreign Origin is refused (0.370792ms)
✖ origin: with no Sec-Fetch-Site, Origin null is refused (0.349417ms)
✔ cookie: the session cookie is issued with SameSite=Lax (0.108209ms)
✔ GET: a cross-site link to the endpoint changes nothing (0.37525ms)
ℹ tests 9
ℹ suites 0
ℹ pass 5
ℹ fail 4
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 19.26775
✖ failing tests:
test at csrf-checks.test.mjs:83:1
✖ origin: Sec-Fetch-Site cross-site is refused even with a valid token (1.058625ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
200 !== 403
(stack trace lines removed here)
(The other three origin tests fail the same way, each with 200 !== 403.)
Command: node csrf-checks.test.mjs samesite-off
✔ baseline: your own page, with its token, changes the name (9.659125ms)
✔ token: a same-origin post with no token is refused (0.650708ms)
✔ token: a same-origin post with a wrong token is refused (0.426125ms)
✔ origin: Sec-Fetch-Site cross-site is refused even with a valid token (0.405833ms)
✔ origin: Sec-Fetch-Site same-site from another port is refused (0.526166ms)
✔ origin: with no Sec-Fetch-Site, a foreign Origin is refused (0.387958ms)
✔ origin: with no Sec-Fetch-Site, Origin null is refused (0.32125ms)
✖ cookie: the session cookie is issued with SameSite=Lax (0.876ms)
✔ GET: a cross-site link to the endpoint changes nothing (0.403083ms)
ℹ tests 9
ℹ suites 0
ℹ pass 8
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 18.37475
✖ failing tests:
test at csrf-checks.test.mjs:107:1
✖ cookie: the session cookie is issued with SameSite=Lax (0.876ms)
AssertionError [ERR_ASSERTION]: The input did not match the regular expression /; SameSite=Lax/. Input:
'session=hGczGcg1bESQmT1eXSFe6p9qOjBMd5mc; Path=/; HttpOnly'
(stack trace lines removed here)
Command: node csrf-checks.test.mjs get-on
✔ baseline: your own page, with its token, changes the name (10.022333ms)
✔ token: a same-origin post with no token is refused (0.663542ms)
✔ token: a same-origin post with a wrong token is refused (0.395ms)
✔ origin: Sec-Fetch-Site cross-site is refused even with a valid token (0.444916ms)
✔ origin: Sec-Fetch-Site same-site from another port is refused (0.4495ms)
✔ origin: with no Sec-Fetch-Site, a foreign Origin is refused (0.326208ms)
✔ origin: with no Sec-Fetch-Site, Origin null is refused (0.343917ms)
✔ cookie: the session cookie is issued with SameSite=Lax (0.103791ms)
✖ GET: a cross-site link to the endpoint changes nothing (1.027875ms)
ℹ tests 9
ℹ suites 0
ℹ pass 8
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 18.692083
✖ failing tests:
test at csrf-checks.test.mjs:111:1
✖ GET: a cross-site link to the endpoint changes nothing (1.027875ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
403 !== 405
(stack trace lines removed here)
Each of the four runs with a check switched off exits with code 1, so a pipeline step running the test fails.
================================================================
PART 5: SEE WHAT YOUR OWN BROWSER SENDS
================================================================
Command: node browser-check.mjs
SameSite setting on the session cookie: Lax
1. Sign in (same origin): http://127.0.0.1:54946/
2. Same site, another port: http://127.0.0.1:54947/
3. Another site (localhost): http://localhost:54947/
Each post to the account prints one line below.
The token and origin checks are off in this mode, so whether the name changes depends only on whether your browser sent the session cookie.
1. Open the first address. It is the account page, and it sets the session cookie. Open your browser's developer tools, choose the Network panel and press Save display name. Click the request to /account/display-name and read its request headers: Origin, Sec-Fetch-Site and Cookie. Compare them with row S1.
2. Open the second address and press the button. It is the same host on another port: a different origin but the same site, because the site ignores the port (HTML Standard; MDN Site glossary). Compare the headers with row S8. The sources say the session cookie is sent under Lax and Strict alike and Sec-Fetch-Site reads same-site.
3. Open the third address and press the button. It is the second page again, reached as localhost instead of 127.0.0.1. That is a different site: the HTML Standard builds a site from the whole host when the host has no registrable domain, and under the URL Standard an IP address has none, so the hosts 127.0.0.1 and localhost cannot match. Compare with row S2. The sources say that under Lax and Strict the cookie is not sent and Sec-Fetch-Site reads cross-site.
4. After each post, the terminal prints one line with the Origin, Sec-Fetch-Site and session cookie the server received, and its result. Stop the server with Ctrl+C and repeat with node browser-check.mjs Strict, then node browser-check.mjs unset. With unset your browser applies its own default, and MDN Set-Cookie says a browser that applies Lax as a default also sends the cookie on a POST in the two minutes after it was set.
Your browser is the evidence in this part. If it sends something other than the matrix describes, record the browser and its version, and check MDN's compatibility data for that header or attribute.
================================================================
PART 6: POINT THE TEST AT YOUR OWN CODE
================================================================
1. Copy csrf-checks.test.mjs into your project's tests.
2. Replace startLabServer with your application started on a test port with a seeded test account, and replace /account/display-name with one of your own state-changing endpoints and a harmless field on the test account.
3. Keep one test per check with the other check's input held valid, so a failure names the check that stopped working.
4. Add the GET test for every state-changing endpoint, and a test that your session cookie's Set-Cookie header carries the SameSite value you chose.
5. Run it against a staging or local copy, never against real customers' accounts.What CSRF is
Picture a customer portal where a signed-in customer can change the email address their invoices go to.
The change is one request: the browser sends the new address to the server, together with the cookie that says who is signed in. Cross-site request forgery, shortened to CSRF, is when a different website gets that customer's browser to send the same request, with the same cookie, without the customer meaning to. The server sees a signed-in customer asking for a change, and makes it.
OWASP's Cross-Site Request Forgery Prevention Cheat Sheet defines the attack as one where a malicious web site, email, blog, instant message or program tricks an authenticated user's web browser into performing an unwanted action on a trusted site, and says an unprotected site cannot tell legitimate requests from forged authenticated ones.
It also sets the limit: the attacker can only use what the vulnerable application exposes and what the user is allowed to do. Depending on the user, that can mean transferring funds, changing a password, making a purchase or raising an account's privileges.
MITRE catalogues the weakness as CWE-352, Cross-Site Request Forgery, and describes it as a web application that does not, or cannot, sufficiently verify whether a request was intentionally provided by the user who sent it. It lists Session Riding and XSRF among its other names.
CWE-352 says the scope of an attack is limited only by the victim's privileges, and that when the victim is an administrator the consequences may include complete control over the web application.
The OWASP Top 10:2025 names CWE-352 among the notable weaknesses in A01 Broken Access Control, and MITRE lists it in its 2025 CWE Top 25 Most Dangerous Software Weaknesses.
There is no single setting that fixes it. This page explains the three checks that refuse a forged request (an anti-forgery token, a check of where the request came from, and the SameSite cookie attribute), what each one leaves behind, and how bearer tokens change the picture.
Three neighbouring topics have their own guides: cookie security covers every cookie attribute, CORS misconfiguration covers which other sites may read your responses, and session management covers how sessions start, rotate and end.
Why browsers make CSRF possible
The root of the problem is that the browser attaches cookies by itself.
The OWASP cheat sheet puts it in one line: browser requests automatically include all cookies, including session cookies. OWASP's test for CSRF, WSTG-SESS-05, describes the same mechanism: once the browser receives a site's cookie, it automatically sends it along with any further requests directed to that site.
The guide lists three ways the same GET request can arrive, through the application itself, from a URL typed into the browser and from a link on another site, and says the application cannot tell them apart.
So a session cookie proves which browser sent a request, not which page asked the browser to send it. WSTG-SESS-05 says CSRF relies on session management that uses only information known by the browser, which it describes as information such as cookies or HTTP-based authentication, for example Basic Authentication, that the browser stores and presents with each request.
MDN's CSRF guide gives the conditions in plainer words: in general, a site is open to CSRF if it uses HTTP requests to change state, uses only cookies to check that a request came from a signed-in user, and uses only parameters an attacker can predict.
The web was also built to let one site send requests to another. MDN's page on the same-origin policy says cross-origin writes, such as links, redirects and form submissions, are typically allowed, while cross-origin reads are typically disallowed. A form on any website can post to yours, and MDN's CORS guide explains that this is why a request that looks like a form submission needs no permission from the receiving server before it is sent.
The other site cannot read your response unless your server opts in with CORS headers, but the request still reaches your server.
Each defence on this page works by finding something a forged request cannot supply: a secret value from your own page, the browser's own statement of where the request came from, or the session cookie, which the browser declines to send.
CSRF prevention: the three checks
The OWASP cheat sheet's first instruction is to check whether your framework has built-in CSRF protection and use it.
Where it does not, add CSRF tokens to all state-changing requests and validate them on the server. Software that targets only modern browsers may rely on Fetch Metadata headers instead, with a fallback, and the cheat sheet asks for at least one defence-in-depth measure on top, SameSite among them. MDN's CSRF guide takes the same line, describing SameSite as an addition to a primary defence rather than a complete one.
A CSRF token is an unpredictable value the server places in its own page and expects back with each state-changing request. In what the cheat sheet calls the Synchronizer Token Pattern, the token is generated on the server, unique per user session, secret and unpredictable, and the server rejects any request whose token is missing or does not match the one stored in the session.
The token comes back in a hidden form field, a custom header or a JSON body.
It does not go in a cookie for this pattern, and it must not appear in a URL, because the cheat sheet notes that GET requests can leak tokens through browser history, log files and Referer headers.
It works because of the same-origin policy. MDN says the way to prevent cross-origin writes is to check an unguessable token in the request, and that you must prevent cross-origin reads of pages that require the token. Another site can make the browser send a request to you. Unless your CORS policy lets it read your pages, it cannot read your page to learn the token.
Stateless applications can use what the cheat sheet calls the Signed Double-Submit Cookie: the token carries an HMAC bound to the session, and the server reads it from a header or form field, never from the cookie alone. The cheat sheet discourages the naive version, which only checks that a cookie and a form field match, because an attacker who can write cookies on your domain, for example from a vulnerable sibling subdomain, can plant a matching pair.
For JavaScript clients, the cheat sheet also describes a custom request header with no token at all. A header such as X-CSRF-Token makes the browser treat the request as one to preflight, so a page on another origin cannot send it unless your CORS policy allows that origin. ASVS 5.0 requirement 3.5.1, at Level 1, accepts either approach: anti-forgery tokens, or extra header fields that are not CORS-safelisted request-header fields.
The second check asks the browser where the request came from. Browsers add a Sec-Fetch-Site header that MDN describes as indicating the relationship between a request initiator's origin and the origin of the requested resource.
It takes four values: same-origin, same-site, cross-site, and none for a user-originated action such as typing an address or opening a bookmark. The W3C Fetch Metadata Request Headers specification, a Working Draft dated 21 September 2026, defines how browsers set it.
MDN marks the header as available across browsers since March 2023, and the cheat sheet gives the same date for the Sec-Fetch headers in all major browsers.
The cheat sheet's policy starts there. Reject POST, PUT, PATCH and DELETE when Sec-Fetch-Site is cross-site, allow same-origin, and treat same-site as allowed only if you trust every sibling subdomain. Because some legacy browsers do not send the Sec-Fetch headers, it makes a fallback to the Origin header, or the Referer header when Origin is absent, a mandatory part of any Fetch Metadata check. It adds that a missing header, or Origin: null, is not evidence of a same-origin request.
Page scripts cannot fake either signal. The cheat sheet notes that Origin and Referer are forbidden headers that only the browser can set, and MDN lists Sec-Fetch-Site as a forbidden request header because of its Sec- prefix.
- Compare the whole origin. The cheat sheet's example is a check for example.org that a request from example.org.attacker.com must not pass. A starts-with or contains test fails that.
- Know your own origin from configuration. The cheat sheet calls a configured target origin the most secure option, and warns that behind a proxy the Host header may have been changed.
- Serve the whole site over HTTPS. MDN says Sec-Fetch-Site is only included in requests to potentially trustworthy URLs, and the cheat sheet lists HTTPS across the application as a requirement.
- Start in log-only mode, as the cheat sheet recommends, and keep an explicit list of endpoints you exempt, such as a webhook another server calls.
The third check lives in the cookie. MDN's Set-Cookie reference says SameSite controls whether a cookie is sent with cross-site requests, meaning requests from a different site, including the scheme. Strict sends the cookie only for requests from the same site that set it.
Lax also sends it on cross-site requests that are top-level navigations, such as following a link, and that use a safe method, which rules out POST, PUT and DELETE.
On cross-site requests, Lax leaves the cookie off fetch() calls, image and script loads and navigations inside an iframe. None sends the cookie with both same-site and cross-site requests and needs the Secure attribute.
The standard behind SameSite is still a draft. The IETF document that would replace RFC 6265, draft-ietf-httpbis-rfc6265bis-22, is an Internet-Draft. Its security considerations call SameSite a robust defence when deployed in strict mode and supported by the client, then advise that it should not be the extent of a site's CSRF defence and strongly encourage the usual server-side defences, such as CSRF tokens.
What happens to a cookie set without the attribute depends on the browser. MDN says some browsers use Lax as the default, and that when Lax is applied as a default, cookies are also sent on POST requests if they were set no more than two minutes earlier.
The OWASP cheat sheet says Chromium-based browsers treat such a cookie as Lax and Firefox and Safari do not. Its advice is to always set SameSite explicitly and not to assume every user gets its protection.
Strict has a cost. The cookie draft gives the example of a user who follows an emailed link to a project page and whose Strict session cookie is not sent on that cross-site navigation, and MDN's CSRF guide says such a user will not be recognised. The draft suggests two cookies: a Lax one that grants read access, and a Strict one that must be present before any change.
MDN suggests the same split. The cookie security guide covers how to choose each attribute; this page is about what SameSite does to a forged request.
Same site is not the same as same origin
SameSite is decided by site, and a site is wider than an origin.
MDN defines an origin as the scheme, hostname and port of a URL, and gives http://example.com and http://example.com:8080 as two URLs that are not the same origin because their ports differ. A site is defined by the registrable domain. MDN's glossary says support.mozilla.org and developer.mozilla.org are the same site, and that https://example.com:8080 and https://example.com are the same site because the port is ignored when determining the site.
The HTML Standard builds a site from the scheme and the registrable domain and ignores the port, and adds that same-site concepts should be avoided where possible in favour of same-origin checks.
The rules for SameSite cookies use the schemeful version, which also compares the scheme, so http://example.com and https://example.com count as different sites.
That gap matters for CSRF. Two ports on one host are the same site but different origins, and so are app.example.com and blog.example.com. A form on either can post to the other, and every SameSite value, Strict included, lets the session cookie through, because to the browser it is a same-site request.
The OWASP cheat sheet spells out the consequence: a cookie set on app.example.com with any SameSite value is still sent with requests from anything.example.com, so a vulnerability or a malicious actor on any sibling host can send requests your SameSite cookies accompany, and a taken-over subdomain inherits the same reach. MDN's CSRF guide concludes that relying on same-site protection means trusting all your site's subdomains.
Sec-Fetch-Site draws the finer line. MDN says same-origin means the same scheme, host and port, and same-site means the same site, including the scheme. The Fetch Metadata draft sets same-origin only when every URL in the request's URL list, redirects included, is same-origin with the request's origin.
A check that accepts only same-origin, as the lab on this page does, refuses the sibling subdomain and the other port. A check that also accepts same-site does not. Rows S7 and S8 of the matrix show both.
Before you decide whether to trust same-site requests, list what shares your registrable domain. The cheat sheet's list of hosts to think about includes multi-tenant services on a shared parent domain, user content served from subdomains, legacy subdomains, an acquired product on the same parent domain and third-party services on subdomains.
To that, add anything you run on another port of the same host. ASVS 5.0 requirement 3.5.4, at Level 2, asks that separate applications are hosted on different hostnames, which keeps them apart under the same-origin policy and hostname-based cookie rules.
Why a GET request must not change anything
The OWASP cheat sheet, MITRE and the ASVS all state this rule.
The OWASP cheat sheet says not to use GET requests for state-changing operations. CWE-352 lists not using the GET method for any request that triggers a state change among its mitigations. ASVS 5.0 requirement 3.5.3, at Level 1, asks that requests to sensitive functionality use methods such as POST, PUT, PATCH or DELETE rather than safe methods such as GET, or that strict validation of the Sec-Fetch headers takes their place.
A GET is the easiest request to forge. WSTG-SESS-05 shows an invisible img tag whose src points at an action on the target: the browser fetches it to display the image, and the request carries the session cookie.
MDN's CSRF guide uses the same example for a funds transfer. A link works as well, and a link is a top-level navigation with a safe method, which is exactly what SameSite=Lax lets through.
The cheat sheet puts this first in its list of SameSite's limitations: Lax only blocks unsafe methods, so it does not stop a state-changing operation that is reachable by GET.
A GET also carries less evidence. The Fetch Standard adds an Origin header to a cross-origin request made in CORS mode (response tainting cors), or to one whose method is neither GET nor HEAD, so a cross-site link or image request arrives with no Origin at all, and a check that relies on Origin has nothing to compare.
Sec-Fetch-Site is still sent, but the cheat sheet's own policy lets cross-site GET navigations through, so that other sites can link to yours.
Moving the change to POST is not the whole fix either. WSTG-SESS-05 says POST requests can be automated with JavaScript, so using POST alone is not enough. MDN warns that some web frameworks support method override, which lets a request sent with GET appear to the server as a POST, so check that any override in your framework does not accept a GET.
Next.js makes a related point for its own apps: its data security guide says mutations should never be a side effect of rendering, and shows a page that deletes a cookie when a logout search parameter is present as the example of what not to do.
Bearer tokens: what changes and what does not
An API can authenticate each call with a bearer token instead of a session cookie.
RFC 6750, the OAuth 2.0 bearer token standard, says clients should send the token in the Authorization request header field using the Bearer scheme. In a browser, that means your own JavaScript adds it to each request.
That changes the CSRF picture, because a bearer token is not something the browser sends on its own. It is not a cookie, and it is not the stored HTTP authentication that WSTG-SESS-05 says CSRF relies on. MDN's CSRF guide lists using only cookies to check who sent a request as one of the conditions under which, in general, the attack is possible.
A page on another site can still make the browser send a request to your API, but it cannot read your token: MDN's same-origin policy page says each origin gets its own separate storage, and JavaScript in one origin cannot read storage belonging to another.
The forged request arrives without the header and fails authentication. Setting G of the lab shows that result for every row.
A bearer token moves the risk rather than removing it. These are the gaps that stay open.
- Cross-site scripting. The OWASP cheat sheet warns that XSS can defeat all CSRF mitigation techniques, and a token kept where JavaScript can read it can be read by injected script too. OWASP's HTML5 Security Cheat Sheet says one cross-site scripting flaw can be used to steal all the data in local storage, and advises against keeping session identifiers there because the data is always accessible by JavaScript. The XSS guide covers prevention.
- A cookie fallback. If the same API also accepts the session cookie, for example because the web app and the API share a login, a forged request can take the cookie path and every row of the matrix applies again. Check every way each state-changing endpoint accepts a caller.
- A token kept in a cookie. RFC 6750 says implementations that store bearer tokens in cookies must take precautions against cross-site request forgery. At that point it is a session cookie by another name.
- A token in a URL. RFC 6750 says bearer tokens should not be passed in page URLs, such as query strings, because browsers, servers and other software may not adequately protect URLs in history, logs and other data structures.
Login CSRF: forging the sign-in itself
Sign-in forms get overlooked because the visitor is not signed in yet.
The OWASP cheat sheet says CSRF can still happen on a login form, with a different impact. Its example: an attacker uses CSRF to sign the victim into a shopping site with the attacker's own account, the victim then enters their card details, and the attacker may be able to buy items with the victim's stored card.
The same applies to anything else a victim saves while unknowingly signed in as someone else, such as an address or a document.
The cheat sheet's fix is a pre-session: create a session before sign-in and put a token in the login form, then at sign-in destroy that pre-session and create a new session, so it cannot be used for session fixation. A custom request header on an AJAX login also works. The cheat sheet notes that checking the Referer when Origin is absent is also used for requests made before a session exists, so an Origin or Sec-Fetch-Site check belongs on the login endpoint as much as on any other. How sessions rotate at sign-in is covered in the session management guide.
What each fix leaves behind
No check covers every row of the matrix, and each has gaps of its own.
These are the ones the sources name.
Script on your own page. The cheat sheet says XSS can defeat all CSRF mitigation techniques, and CWE-352 says most CSRF defences can be bypassed using attacker-controlled script, because script on your page can read the token. The cheat sheet also describes client-side CSRF, where your own JavaScript is tricked by attacker-controlled input, such as the URL, into sending a forged request that includes the token, and it says this variant can bypass token-based mitigations and SameSite cookies alike.
Leaks and implementation details. A token that reaches a URL, a log or a Referer header can be reused. Per-request tokens can break the Back button, because the previous page holds a token that is no longer valid. A naive double-submit cookie can be planted from a sibling subdomain. The cheat sheet covers all three.
Missing or altered headers. Legacy browsers may not send the Sec-Fetch headers, so the Origin fallback is required. The cheat sheet says proxies, gateways and load balancers may remove or modify Origin and Sec- headers, and that Origin can be null after a cross-origin redirect or from a sandboxed iframe, which an attacker can create, so null must never be on the allowed list.
It also notes that prerendering and other speculative navigation may send Sec-Fetch values that do not match the final navigation.
Same-site neighbours and plain HTTP. A check that accepts same-site trusts every sibling subdomain. Browsers send the Sec-Fetch headers only to potentially trustworthy URLs, so a public site served over plain HTTP gets none, which leaves only Origin to decide. If your responses differ on these headers, the cheat sheet recommends a Vary header such as Vary: Sec-Fetch-Site, Origin, so that caches keep them apart.
GET, siblings and defaults. Lax does nothing for a state-changing GET. No value does anything for a sibling subdomain or another port. Browser defaults differ, and MDN says a browser that applies Lax as a default also sends a cookie on POST requests within two minutes of setting it.
The cheat sheet adds that older or embedded clients may ignore the attribute entirely, and that SameSite does not protect against client-side CSRF.
Top-level navigations. The cookie draft says Lax provides reasonable defence in depth against CSRF attacks that rely on unsafe methods such as POST, but does not offer a robust defence against CSRF as a general category of attack, because attackers can still trigger top-level navigations or pop up new windows, and features such as prerendering can create same-site requests.
The cheat sheet sets out narrow conditions under which SameSite alone can be a reasonable defence, and all of them have to hold: the application shares no registrable domain with any host you do not fully control; no GET or other safe-method endpoint changes state; the session cookie is Strict, or Lax with the __Host- prefix and an audit of every GET handler; Origin or Referer verification is in place as well; and you accept the risk for users whose browsers do not enforce SameSite. Outside those conditions it treats SameSite as one layer alongside a token or a double-submit pattern.
Running the CSRF lab on your own machine
The lab is an illustration.
One invented account has a display name and one endpoint that changes it, so the most a forged request can do is rename a made-up account on your own machine. The server binds to 127.0.0.1, lets the system pick a free port, keeps everything in memory and uses only modules that ship with Node.js, so there is nothing to install.
It was written and run on Node.js 26.0.0, and every output in the asset comes from that run. Use it for learning and for testing code you own.
Be clear about what it proves. The scripted client stands in for the browser: for each matrix row it sends the cookie and headers that the documents in the matrix say a browser sends in that situation, under seven server settings.
The output shows what a server does with each set of headers. It does not show what a browser sends. The documents establish that, and the browser check lets you watch your own browser do it.
- Save the four files into an empty folder and open a terminal there.
- Run node run-matrix.mjs. For each of the eight situations it prints the request it sends and the server's response under settings A to G: no checks, SameSite=Lax only, SameSite=Strict only, the Origin and Sec-Fetch-Site check only, the token check only, all three together, and a bearer token instead of a cookie.
- Run node csrf-checks.test.mjs. All nine tests pass. Run it again with token-off, origin-off, samesite-off or get-on, and the tests for that check fail and the process exits with code 1, so a pipeline step running the test fails if someone switches a check off.
- Run node browser-check.mjs, open the three addresses it prints in turn, and post the form from each one.
Checking the browser side in developer tools
In browser-check mode the token and origin checks are off, so the result depends only on whether your browser sent the session cookie. Open the developer tools, choose the Network panel, post the form and click the request to /account/display-name. Under the request headers, read Origin, Sec-Fetch-Site and Cookie. The terminal prints the same three values for each post, with the server's result.
The first address is the account page on the lab's own origin; compare it with row S1. The second is another port on 127.0.0.1, which is a different origin but the same site; compare it with row S8. The third reaches that second server as localhost, which is a different site from 127.0.0.1, because the HTML Standard builds the site from the whole host when there is no registrable domain and the URL Standard gives an IP address none; compare it with row S2.
Then repeat with the Strict and unset options.
If your browser sends something the matrix does not describe, record the browser and version: your browser is the evidence for this part.
Pointing the regression test at your own code
Keep the nine tests and change two things: start your own application on a test port with a seeded test account in place of the lab server, and use one of your own state-changing endpoints in place of the display-name endpoint.
Keep one test per check, with the other check's input held valid, so a failure names the check that stopped working, and add the GET test for every state-changing endpoint.
CSRF protection in your framework
Start with what your framework already does, as the cheat sheet advises, because built-in defences are maintained by the framework's authors.
Its examples: .NET has built-in token protection and leaves key and token management to you, and from Go 1.25 the standard library's CrossOriginProtection type implements a Fetch Metadata defence. MDN gives Django's csrf_token template tag as an example of token support, and notes that using it means understanding every place your site sends state-changing requests.
In Next.js, Server Actions accept only POST and compare the Origin header with the Host header, or X-Forwarded-Host, aborting the request on a mismatch, according to the Next.js data security guide. The guide recommends serverActions.allowedOrigins to list safe origins for large applications that use reverse proxies or multi-layered backend architectures, where the server API differs from the production domain.
The Next.js guide on this site covers how that check is tested. For anything else in a Next.js app that changes state, such as a route handler, confirm which of the three checks it runs.
Whatever the framework, list your state-changing endpoints and confirm each is covered, including any added outside the framework's usual path, and keep the cheat sheet's explicit list of exemptions, such as a webhook another server calls, with what protects each one instead.
How to test for CSRF in your own application
OWASP's testing guide covers this in WSTG-SESS-05, Testing for Cross Site Request Forgery, with one objective: determine whether it is possible to initiate requests on a user's behalf that are not initiated by the user.
Its first step is an audit of session management. If the session relies only on client-side values, meaning cookies or HTTP authentication credentials, the guide says the application is vulnerable.
- List every endpoint that changes state: forms, API calls, Server Actions and route handlers, including sign-in, sign-out and settings.
- For each one, on a copy you own and with a test account, send the requests the regression test sends: no token, a wrong token, Sec-Fetch-Site cross-site and same-site, no Sec-Fetch-Site with a foreign or null Origin, and a GET with the same parameters. A refusal is the pass; a changed record is the evidence when it is not.
- Check content types. WSTG-SESS-05 shows a form with the text/plain encoding delivering a JSON-looking body, and the cheat sheet says an API that accepts text/plain would be open to CSRF. Its mitigation is to refuse the simple content types, application/x-www-form-urlencoded, multipart/form-data and text/plain, on endpoints that expect JSON. ASVS 5.0 requirement 3.5.2 asks for the same outcome when you rely on the CORS preflight.
- Read the Set-Cookie header of the session cookie and confirm SameSite is set on purpose. ASVS 5.0 requirement 3.3.2, at Level 2, asks that each cookie's SameSite value is set according to the cookie's purpose.
- Test only systems you own or are authorised in writing to test, using test accounts and test records.
Where an outside test fits
Your own tests check the endpoints you know about.
A Clever Ops web application and API penetration test covers authentication and sessions, what each role can see and change, and the API called directly rather than only through the screens. For a Next.js application, state-changing Server Action requests are sent with a foreign Origin header and with Origin set to null, and both should be rejected, as the Next.js guide in this library describes.
The website security check, which does not sign in, reviews the cookie settings anyone can see, including whether a SameSite value was chosen deliberately rather than left to the browser.
Each finding comes with evidence, a fix written for your stack and the criteria the retest will use. If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.
Frequently asked questions
Cross-site request forgery is when another website makes your signed-in visitor's browser send a request to your site that the visitor never meant to send, such as changing their email address. The browser attaches the session cookie by itself, so the server sees a signed-in user and acts. CWE-352 describes the weakness as an application that does not, or cannot, sufficiently verify whether a request was intentionally provided by the user who sent it.
A secret, unpredictable value the server puts in its own page and expects back with every state-changing request. The OWASP cheat sheet says it should be generated on the server, unique per session, secret and unpredictable, and that a request with a missing or mismatched token should be rejected. Browsers block another site from reading your page by default, and as long as you do not open that up (for example with a permissive CORS policy), it cannot include the token in a forged request.
They reduce it. Strict and Lax keep the cookie off cross-site POST requests, but Lax still sends it on a top-level GET navigation, and no SameSite value stops a request from a sibling subdomain or another port, because those are the same site. MDN, the OWASP cheat sheet and the cookie draft all describe SameSite as defence in depth alongside a token or an origin check.
Origin names the origin that caused the request, and your server compares it with its own. Sec-Fetch-Site states the relationship directly: same-origin, same-site, cross-site or none. Browsers send Sec-Fetch-Site only to potentially trustworthy URLs, and MDN says user agents do not add Origin to a cross-origin GET in no-cors mode. The OWASP cheat sheet treats Sec-Fetch-Site as the primary signal and, because some legacy browsers do not send it, makes a fallback to Origin, then Referer, mandatory.
Not immune, but a forged request has nothing to authenticate with if the token travels only in an Authorization header your own script adds, because the browser does not attach it and another origin cannot read your storage. It stops applying if the API also accepts a session cookie or the token is kept in a cookie, and cross-site scripting can steal a token that JavaScript can read.
It is necessary but not enough. A GET that changes state can be forged with a link, which gets through SameSite=Lax, or with an image tag, which carries the cookie when it has no SameSite restriction and the browser allows third-party cookies, so state changes belong on POST, PUT, PATCH or DELETE. But WSTG-SESS-05 notes that POST requests can be automated with JavaScript, so a POST endpoint still needs a token or an origin check.
A forged sign-in that logs the victim into the attacker's account, so whatever the victim then saves, such as card details, lands in an account the attacker controls. The OWASP cheat sheet recommends a token in the login form tied to a pre-session that is replaced by a new session at sign-in, or a custom request header on an AJAX login.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.