Class Csrf

java.lang.Object
com.jsgalactic.axiom.security.Csrf
All Implemented Interfaces:
Middleware

public final class Csrf extends Object implements Middleware
Cross-site request forgery protection for browser clients that authenticate with cookies.

 // 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):

  1. Sec-Fetch-Site, when the browser sends it: same-origin and none pass, same-site only with Csrf.Builder.allowSameSite, anything else (including cross-site) fails. Disable with Csrf.Builder.fetchMetadata(boolean).
  2. Origin, when present: it must be one of Csrf.Builder.allowedOrigins or, if none are configured, have the same host and port as the Host header (null and malformed values fail). A request without Origin (older browsers, non-browser clients) is decided by the token alone.
  3. The token in the request header (X-CSRF-Token by default), compared in constant time with the expected one.
The first two are defence in depth: the token is the proof, and a missing or wrong token fails whatever the headers say.

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.

  • Method Details

    • synchronizer

      public static Csrf.Builder synchronizer(Sessions sessions)
      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

      public static Csrf.Builder doubleSubmit(byte[] key)
      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

      public String token(Context context)
      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

      public Response handle(Context context, Middleware.Next next) throws Exception
      Description copied from interface: Middleware
      Handles one request, usually by calling next.run().
      Specified by:
      handle in interface Middleware
      Parameters:
      context - the request-scoped context shared with the handler; status settings made here apply to the handler's result mapping
      next - the rest of the chain
      Returns:
      the response to use; never null
      Throws:
      Exception - to fail the request as a handler exception would
    • toString

      public String toString()
      Overrides:
      toString in class Object