Class Csrf
- All Implemented Interfaces:
Middleware
// with server-side sessions: one random token per session
var csrf = Csrf.synchronizer(sessions).allowedOrigins("https://app.example.com").build();
// without a session: an HMAC-signed token in a cookie, echoed in a header
var csrf = Csrf.doubleSubmit(secretKey).build();
app.use(sessions);
app.use(security.authenticate());
app.use(csrf);
app.get("/form", ctx -> render(csrf.token(ctx))); // embed the token in the page
What is checked. Requests with a safe method (GET, HEAD,
OPTIONS, TRACE) pass untouched; they must not change state. Every other method must
pass, in this order, each failure being 403 application/problem+json with code
csrf_rejected (one code, so clients cannot tell which check failed):
Sec-Fetch-Site, when the browser sends it:same-originandnonepass,same-siteonly withCsrf.Builder.allowSameSite, anything else (includingcross-site) fails. Disable withCsrf.Builder.fetchMetadata(boolean).Origin, when present: it must be one ofCsrf.Builder.allowedOriginsor, if none are configured, have the same host and port as theHostheader (nulland malformed values fail). A request withoutOrigin(older browsers, non-browser clients) is decided by the token alone.- The token in the request header (
X-CSRF-Tokenby default), compared in constant time with the expected one.
Synchronizer token (synchronizer(com.jsgalactic.axiom.security.Sessions)). One random 256-bit token per session, kept
in the session. token(Context) returns it (creating the session and token on first use)
for embedding in a page or API response; it stays valid for the life of the session and is
discarded when the session signs in (Session.authenticate(com.jsgalactic.axiom.context.SecurityIdentity)), so fetch a fresh one after
login. Use Sessions before this middleware.
Double-submit cookie (doubleSubmit(byte[])). No server state: the token is
issued-at . nonce . HMAC-SHA256(key, binding, issued-at, nonce), set as a cookie (named
__Host-csrf by default, readable by scripts unless Csrf.Builder.httpOnly is set) and echoed
by the client in the header. A request passes when the header equals the cookie and the token's
HMAC verifies for the request's binding, so an attacker who can plant a cookie (a sub-domain)
still cannot forge a token bound to another user. The binding is the authenticated principal by
default (Csrf.Builder.binding); tokens older than Csrf.Builder.maxAge (12 hours by default)
are refused. The cookie is issued on any response when the request has no valid one and the
response sets no other cookie (a response carries one Set-Cookie); after sign-in the old
token no longer matches the new binding, so the next safe request obtains a fresh one. Changing
the key invalidates all tokens at once.
Requests that carry credentials a browser never attaches on its own (an Authorization
header) are not exposed to CSRF; Csrf.Builder.exemptWhen(java.util.function.Predicate<com.jsgalactic.axiom.http.Request>) lets an application skip the check
for them.
Immutable configuration, thread-safe, shared by all requests.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final classBuildsCsrf; used during configuration, not thread-safe.Nested classes/interfaces inherited from interface com.jsgalactic.axiom.context.Middleware
Middleware.Next -
Method Summary
Modifier and TypeMethodDescriptionstatic Csrf.BuilderdoubleSubmit(byte[] key) Starts a configuration with HMAC-signed double-submit cookies.handle(Context context, Middleware.Next next) Handles one request, usually by callingnext.run().static Csrf.Buildersynchronizer(Sessions sessions) Starts a configuration that keeps one random token in each session.Returns the token the client must send with unsafe requests.toString()Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface com.jsgalactic.axiom.context.Middleware
afterError
-
Method Details
-
synchronizer
Starts a configuration that keeps one random token in each session.- Parameters:
sessions- the sessions in use; its middleware must run before this one- Returns:
- a builder
-
doubleSubmit
Starts a configuration with HMAC-signed double-submit cookies.- Parameters:
key- the signing key, at least 32 random bytes; copied- Returns:
- a builder
- Throws:
IllegalArgumentException- if the key is shorter than 32 bytes
-
token
Returns the token the client must send with unsafe requests.- Parameters:
context- the context of a request inside this middleware- Returns:
- the token; with the synchronizer variant this creates the session's token on first use
- Throws:
IllegalStateException- if this middleware is not active for the request
-
handle
Description copied from interface:MiddlewareHandles one request, usually by callingnext.run().- Specified by:
handlein interfaceMiddleware- Parameters:
context- the request-scoped context shared with the handler; status settings made here apply to the handler's result mappingnext- the rest of the chain- Returns:
- the response to use; never null
- Throws:
Exception- to fail the request as a handler exception would
-
toString
-