CSRF protection
此内容尚不支持你的语言。
csrfProtection is a stateless CSRF defence: the token is
payload.hmac(secret, payload), so a cookie an attacker plants from a
sibling subdomain fails verification. Safe methods mint/refresh the token;
unsafe methods (POST/PUT/PATCH/DELETE) must present a matching
cookie and header.
import { csrfProtection, CsrfOptions, withMiddleware } from 'actor-ts/http';
const csrf = csrfProtection( CsrfOptions.create().withSecret(process.env.CSRF_SECRET!),);
const routes = withMiddleware(csrf, appRoutes);On a safe request the token is set as a (non-HttpOnly) cookie and also
forwarded to the handler, which reads it with readCsrfToken(req) and
templates it into a form field or <meta> tag. The browser echoes it back
in the X-CSRF-Token header (or a configured form field) on the next
unsafe request.
Configuration
Section titled “Configuration”| Builder method | Field | Default |
|---|---|---|
withSecret(s) | secret | required, ≥ 16 bytes |
withCookieName(n) | cookieName | 'csrf-token' |
withHeaderName(n) | headerName | 'x-csrf-token' |
withCookie(attrs) | cookie | Path=/, Secure, SameSite=Lax |
withVerifyOrigin(flag?) | verifyOrigin | true — also check Origin/Referer |
withAllowedOrigins(...o) | allowedOrigins | extra accepted origins |
withFormField(name) | formFieldName | off — read the token from a urlencoded body field too |
The lightweight alternative — requireSameOrigin
Section titled “The lightweight alternative — requireSameOrigin”If you only need modern-browser protection, requireSameOrigin() rejects
unsafe-method requests whose Origin/Referer host isn’t the request host:
import { requireSameOrigin, withMiddleware } from 'actor-ts/http';
const routes = withMiddleware(requireSameOrigin(), appRoutes);csrfProtection is the belt-and-suspenders option (it runs this check too);
requireSameOrigin alone is lighter but relies on the browser sending a
correct Origin/Referer.
