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.
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
}- Safe requests (
GET,HEAD,OPTIONS) receive a random token in theXSRF-TOKENcookie, which your page's script can read. - Unsafe requests (
POST,PUT,PATCH,DELETE) must send the same value in theX-XSRF-Tokenheader. 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) orStrict: modern browsers then do not send it on cross-site POSTs at all. - Use
secure = trueso cookies travel only over HTTPS. - Never change data with
GETrequests (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
ignorePathsand 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.