Class JwtAuthenticator

java.lang.Object
com.jsgalactic.axiom.security.jwt.JwtAuthenticator
All Implemented Interfaces:
Authenticator

public final class JwtAuthenticator extends Object implements Authenticator
Authenticates Authorization: Bearer requests carrying a signed JWT (RFC 7519, JWS compact serialization), using only the JDK.

 var jwt = JwtAuthenticator.builder()
         .publicKey("2026-10", JwsAlgorithm.RS256, issuerKey)
         .issuer("https://login.example.com")
         .audience("notes-api")
         .build();
 var security = Security.of(jwt);
 

Verification, in this order; any failure is a 401 with code invalid_token and WWW-Authenticate: Bearer realm="...", error="invalid_token", whatever the reason, so a client cannot probe which check failed (the reason is attached as the exception's cause for server-side diagnosis only, and never contains token content):

  1. The token is at most JwtAuthenticator.Builder.maxTokenLength(int) characters (8 KiB by default), checked before anything is decoded.
  2. Three non-empty, unpadded, canonical base64url parts. Encrypted tokens (JWE, five parts or an enc header) are a documented non-goal and are rejected like any invalid token.
  3. The header is a strict JSON object (well-formed UTF-8, no duplicate names). Its alg must be an algorithm a key was registered for: the allow-list is exactly the registered algorithms, so none and anything unconfigured are refused. A crit or enc member is rejected; typ, if present, must be JWT or at+jwt. Header-embedded keys (jwk, jku, x5u, x5c) are never used.
  4. The key is chosen by kid when the token has one, otherwise it is the key registered without a key ID for the token's algorithm. The key must have been registered for exactly that algorithm, so an RSA or EC public key can never be used as an HMAC secret (algorithm confusion).
  5. The signature is verified; HMAC tags are compared in constant time. RSASSA-PSS uses the digest, MGF1 digest and salt length of RFC 7518, and EdDSA means Ed25519 only.
  6. Only then is the claims set parsed. exp is required; exp, nbf and iat are integer NumericDates, checked with the configured clock skew (30 seconds by default, at most five minutes): the token is rejected at or after exp + skew, before nbf - skew, or when issued after now + skew. iss must equal a configured issuer, aud (a string or an array) must contain a configured audience, and sub must be a non-empty string.
The identity's principal is sub. Roles come from the roles claim and permissions from the scope claim by default; each may be a space-separated string or an array of strings, at most 256 entries. Other claims are not exposed unless the application asks: JwtAuthenticator.Builder.exposeClaims(java.lang.String...) copies named scalar claims to SecurityIdentity.attributes(), JwtAuthenticator.Builder.attributes(java.util.function.Function<com.jsgalactic.axiom.security.jwt.JwtClaims, java.util.Map<java.lang.String, java.lang.String>>) maps claims with application code, and JwtAuthenticator.Builder.tokenCheck(com.jsgalactic.axiom.security.jwt.TokenCheck) adds a revocation or jti replay check that runs last (see TokenCheck).

Credentials. A request without an Authorization header, or with a scheme other than Bearer, carries no credentials for this authenticator: authenticate(com.jsgalactic.axiom.http.Request) returns empty. A Bearer header with a missing or malformed token is invalid (401). Repeated Authorization fields are joined by the transport and therefore rejected.

Key sets. JwtAuthenticator.Builder.jwks(JwksSource, JwksOptions) adds the keys of a JSON Web Key Set fetched from a configured URL or file, cached, refreshed and rotated within bounds; keys embedded in tokens (jku, jwk, x5u, x5c) remain unused.

Lifecycle. Thread-safe once built. Statically registered keys are fixed at build time; a configured key set is the only mutable state, replaced as a whole when a fetch succeeds. The authenticator holds HMAC secrets for its lifetime.

  • Method Details

    • builder

      public static JwtAuthenticator.Builder builder()
      Starts a configuration. At least one key, one issuer and one audience are required.
      Returns:
      a new builder
    • authenticate

      public Optional<SecurityIdentity> authenticate(Request request)
      Description copied from interface: Authenticator
      Verifies the request's credentials.
      Specified by:
      authenticate in interface Authenticator
      Parameters:
      request - the immutable request; headers are untrusted client input
      Returns:
      the verified identity, or empty when the request carries no credentials for this scheme
    • challenge

      public String challenge()
      Description copied from interface: Authenticator
      Returns the WWW-Authenticate challenge sent when a policy requires an identity and the request carries no credentials, for example Bearer realm="api". A constant chosen by the application, never a value taken from a request.
      Specified by:
      challenge in interface Authenticator
      Returns:
      challenge: an auth scheme, optionally followed by a space and parameters, in visible ASCII
    • refreshKeys

      public boolean refreshKeys()
      Fetches the configured key set now, regardless of the refresh schedule and rate limit, for example at startup to fail fast on a misconfigured URL. A failed fetch keeps the last good key set. Without a key set source this does nothing.
      Returns:
      true if a new key set was installed, false if the fetch or the set was unusable (the reason is attached to the 401 of the next token that needs it)
    • verify

      public SecurityIdentity verify(String token)
      Verifies a compact JWS token as described above and maps it to an identity.
      Parameters:
      token - the token, without the Bearer prefix
      Returns:
      the verified identity
      Throws:
      UnauthorizedException - with code invalid_token if the token is not valid