Kest

Search

Search the documentation

Security

CSRF protection

Stop other websites from making your signed-in users act.

CSRF (cross-site request forgery) is an attack on applications that use cookies to recognise users. A browser sends your cookie with every request to your site, even a request triggered by a different site. So a page on evil.example can contain a hidden form that POSTs to https://bank.example/transfer, and the browser attaches the victim's session cookie: the bank sees a signed-in user and obeys.

Loading diagram…

You are exposed only if authentication is carried by a cookie. If clients send Authorization: Bearer <token> from JavaScript that they add themselves, another site cannot make the browser add it, so there is no CSRF. (If you use bearer tokens, you can skip this page.)

The defence: a token the attacker cannot read

Kest uses the double-submit cookie pattern:

app.http(adapter) {
    useSession { secure = true }
    useCsrf { ignorePaths = listOf("/webhooks") }          // paths that carry their own signature are skipped
}
  1. Safe requests (GET, HEAD, OPTIONS) receive a random token in the XSRF-TOKEN cookie, which your page's script can read.
  2. Unsafe requests (POST, PUT, PATCH, DELETE) must send the same value in the X-XSRF-Token header. A missing or different value is a 403.

An attacker's page can make the browser send the cookie, but it cannot read it (another origin), so it cannot copy the value into the header.

// the front end: axios and Angular do this by default; with fetch:
const token = document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1];
fetch("/orders", { method: "POST", headers: { "x-xsrf-token": token, "content-type": "application/json" }, body });

Names are configurable: cookieName, headerName.

Add more layers

  • Mark the session cookie SameSite=Lax (the default) or Strict: modern browsers then do not send it on cross-site POSTs at all.
  • Use secure = true so cookies travel only over HTTPS.
  • Never change data with GET requests (they are exempt from the check, and can be triggered by an image tag).
  • Webhooks and server-to-server calls have no browser cookie: add their paths to ignorePaths and verify them by signature (Webhooks).

Testing

Send a POST without the header and expect 403; read the cookie from a GET and send it back in the header and expect success.

Read more