Skip to content

Sessions and login

Your application signs people in through the FlowCatalyst platform and keeps them signed in with a session cookie. Other services call it with platform access tokens. Both arrive at your routes as one Context with a principal, a client and permissions. The application is its own backend-for-frontend: the browser never sees a token, the platform hosts the login form, and the framework renders no login pages.

The normative text, shared by the Java and Go frameworks, is the sessions and login specification. In Go, Java is the reference implementation: where the specification is silent, the Go code follows the Java code, and shared conformance vectors are the truth Go must pass.

Piece Artifact
AuthModule: /auth/login, /auth/callback, /auth/session, /auth/logout, the ContextResolver, Sessions, PlatformTokens framework-auth
AuthDatabaseModule: the default session store (fw_session) framework-auth-database
RedisSessionStore framework-auth-redis
MemorySessionStore, CookieSessionStore framework-auth
TestOidcProvider (a real test identity provider) framework-auth test-jar

framework-auth depends on framework-core, framework-http and Jackson only, and brings no database. Calls to the platform (discovery, keys, the token endpoint) use the JDK’s HTTP client.

App.builder()
.module(new JettyHttpModule())
.module(new DatabaseModule())
.module(new AuthDatabaseModule()) // the default store: fw_session in the default database
.module(AuthModule.builder()
.application(new ApplicationCode("orders"))
.permissions(PermissionMapper.scopes().and(PermissionMapper.byRole(Map.of(
"orders:clerk", Set.of("orders:thing:create", "orders:thing:view")))))
.build())
.module(new OrdersModule())
.start();

AuthModule provides the ContextResolver, so every route declared with RouteOptions.requiresContext() is now authenticated. Do not provide your own as well (two providers fail start-up); see Your own resolver.

Configuration: connections and secrets only

Section titled “Configuration: connections and secrets only”
Key Environment variable Meaning
auth.issuer (required) AUTH_ISSUER The platform’s base URL, which is also its tokens’ iss
auth.client-id (required) AUTH_CLIENT_ID The OAuth client id of your login client
auth.client-secret AUTH_CLIENT_SECRET Only for a CONFIDENTIAL login client. Leave it unset or blank for a PUBLIC one
auth.public-base-url (required) AUTH_PUBLIC_BASE_URL Your application’s origin as browsers see it, for example https://orders.example.com. No path
auth.cookie-keys AUTH_COOKIE_KEYS Only for the cookie store

Everything else (timeouts, permissions, where to land, rate limits) is set on the builder, in code (see config and code). The module claims the auth component, so any other key under auth (a misspelt auth.isuer, an auth.idle-timeout) fails start-up as unknown.

Register the login client on the platform. An anchor administrator calls POST /api/applications/{id}/provision-login-client with redirectUris: ["https://orders.example.com/auth/callback"]. clientType is PUBLIC by default and needs no secret. Add a post-logout redirect URI to the client if you use single logout.

Plain http (http://localhost:8091) is accepted only when APP_ENV is local or test: the cookies then lose Secure and the __Host- prefix, and a warning says so at start-up. In any other environment an http auth.public-base-url or auth.issuer fails start-up. Start-up also fails, with every problem listed, for a public base URL with a path, offline_access in the scope, an idle timeout longer than the absolute one, and a bad cookie key list.

The browser (or your SPA) goes to /auth/login?returnTo=/orders. The framework:

  1. reads the platform’s discovery document (once; a failure answers 502 PLATFORM_UNAVAILABLE, or your failure page for a browser navigation);
  2. creates a login record (state, nonce, PKCE verifier, the returnTo) for 10 minutes and sets a binding cookie __Host-fw_login_<hash> for this browser;
  3. redirects to the platform’s /oauth/authorize with PKCE S256.
sequenceDiagram
  participant B as Browser
  participant A as Your application
  participant P as Platform
  B->>A: GET /auth/login?returnTo=/orders
  A-->>B: 302 to /oauth/authorize (state, nonce, PKCE) + binding cookie
  B->>P: sign in on the platform's login form
  P-->>B: 302 to /auth/callback?code&state
  B->>A: GET /auth/callback
  A->>P: exchange code (PKCE verifier)
  P-->>A: id_token
  A-->>B: 302 to returnTo + __Host-fw_session cookie

The callback completes only in the browser that started it (400 LOGIN_NOT_STARTED_HERE otherwise) and only once (400 INVALID_STATE on a replay). It exchanges the code and verifies the id_token: RS256 only; issuer, audience, azp, expiry with 60 seconds of allowance, and nonce; an access token is never taken for an id_token. It then starts a new session (any older session cookie is deleted first: rotation), sets __Host-fw_session and redirects to returnTo.

returnTo must be a same-origin path (/x, not //x, no \, no control characters, at most 2048 characters). Anything else lands on the default landing, /.

A failed callback answers the JSON error envelope by default: INVALID_CALLBACK, LOGIN_NOT_STARTED_HERE, INVALID_STATE, LOGIN_REFUSED, LOGIN_FAILED, INVALID_ID_TOKEN (with details.reason), PLATFORM_UNAVAILABLE. To send people to a page of yours instead:

AuthModule.builder().loginFailure(LoginFailureHandler.redirectTo("/signed-out"))
// a failed sign-in now answers 302 /signed-out?error=LOGIN_REFUSED

Also: .defaultLanding("/home"), a ReturnToPolicy of your own, and .loginTheme("acme"), which adds client=acme to the authorize URL so the platform shows that client’s login branding.

The same handler answers a sign-in that cannot even start, for a browser navigation only: a rate-limited /auth/login gives ?error=RATE_LIMITED, and a platform unreachable at discovery gives ?error=PLATFORM_UNAVAILABLE. A browser navigation is a GET or HEAD with no Authorization and Sec-Fetch-Mode: navigate (or, without that header, Accept containing text/html). An SPA’s fetch and any API client still get the JSON envelope. The UI package’s FwSignInFailedPage has a sentence for each code.

GET /auth/session always answers 200. An SPA reads it at start and when the tab regains focus:

{"authenticated":true,"principal":{"id":"prn_USER1","kind":"USER","name":"Ada Lovelace","email":"ada@example.test"},
"tier":"ANCHOR","client":"_platform","clients":["*"],"applications":["*"],"roles":["orders:clerk"],
"permissions":["orders:thing:create","orders:thing:view"],"authTime":"2026-10-13T08:00:00Z",
"expiresAt":"2026-10-13T16:00:00Z","idleExpiresAt":"2026-10-13T08:35:00Z",
"csrf":{"mode":"fetch-metadata","jsonBodies":true}}

or {"authenticated":false,"loginUrl":"/auth/login"}. Use permissions to show and hide things; every route still checks on the server. A token whose tier is not one the platform issues (ANCHOR, PARTNER, CLIENT) answers without tier.

This endpoint and logout are typed operations (getAuthSession and logout), so they are in your application’s OpenAPI document with fixed components (AuthSession, a union of AuthSessionAuthenticated and AuthSessionAnonymous told apart by authenticated, and AuthLogout), and the module contributes the session and bearer security schemes. See typed operations and OpenAPI.

routes.get("/api/me", handler, RouteOptions.requiresContext());
routes.post("/api/things", handler,
RouteOptions.requiresContext().with(Auth.require("orders:thing:create")));

Auth.current(request) returns the Authenticated (principal, roles, client, permissions, the source: session, bearer token or field worker’s token, and the expiries). Auth.requireSource(Authenticated.Source.FIELD) (or SESSION, BEARER) answers 403 FORBIDDEN unless the request was authenticated that way.

  • No session and no token is 401 UNAUTHENTICATED. For an HTML navigation the framework answers 302 /auth/login?returnTo=<the path and query> instead, so a server-rendered page sends people to sign in. An SPA’s fetch gets the 401 and navigates itself. (In Go, a 401 returned as an error is turned into the 302; a handler that writes a 401 itself is not redirected.)
  • Permission checks in a use case use context.hasPermission(...) in authorize; see context.
  • Field workers are covered in field workers.

The platform’s id_token carries roles (orders:clerk), not permissions, and only your application knows what its roles mean. So the mapping is code:

Helper (Java / Go) Grants
PermissionMapper.scopes() / auth.ScopesMapper() (the default) The scope of a bearer access token. Nothing for a browser session
PermissionMapper.byRole(Map.of(role, Set.of(...))) / auth.ByRole(...) The permissions of each role held
a.and(b) / a.And(b) The union
PermissionMapper.none() Nothing

With the default, a signed-in person can do nothing that needs a permission until you map your roles: a missing mapping fails closed. The mapping runs on every request. In Go a permission string the Context cannot hold (blank, or with an empty segment) is left out and logged at WARN.

A Context always has a client, and a ClientId holds the client’s identifier (its code, such as acme), not its clt_ id. The default selector takes the principal’s home client, translated to its identifier from the token’s clients entry clt_1:acme. Failing that, when clients names exactly one client with its identifier (a client’s service token), that identifier. Otherwise _platform (“no particular client”), as for an anchor user.

A selector of your own can take the client from a header or a path:

AuthModule.builder().clients((principal, request) -> new ClientId(request.header("X-Client")))

(Go: auth.Clients(...).) Whatever it returns, the framework checks that the principal may act for it (its clients claim holds *, the id, or id:identifier) and answers 403 CLIENT_NOT_PERMITTED otherwise. The selector is consulted for field workers too. The Context’s subject name is the principal’s display name when the token or session carries a name claim.

A request with Authorization: Bearer <platform access token> is authenticated by the token, not the cookie: RS256 against the platform’s published keys, issuer and audience equal to auth.issuer, and token_use api (a default login’s identity token is refused). An invalid token is 401 and never falls back to the cookie. Any other Authorization scheme is 401. When the platform’s keys cannot be read the answer is 503 UNAVAILABLE, so an outage is not reported as bad credentials. Keys are cached for an hour, read again when a token names an unknown key (at most once a minute), and kept while the platform is down. Java’s .bearerTokens(false) and Go’s auth.NoBearerTokens() accept browser sessions only.

To check platform tokens without sessions (one endpoint of a service that has no login), build the verifier yourself. Keep one per platform, because it caches the keys; with the auth module listed, use the provided one.

PlatformTokens tokens = PlatformTokens.create(issuer, Duration.ofSeconds(10), app.get(InstantSource.class));
switch (tokens.verify(bearer)) {
case TokenResult.Valid v when v.token().mayActFor(clientId) -> { /* go on */ }
case TokenResult.Valid v -> { return HttpErrors.forbidden("FORBIDDEN", "not for this client"); }
case TokenResult.Invalid i -> { return HttpErrors.unauthenticated("credentials are required"); }
case TokenResult.Unavailable u -> { return HttpErrors.error(503, "UNAVAILABLE", "try again"); }
}

create refuses an http:// issuer (IllegalArgumentException). In a local or test environment use PlatformTokens.createAllowingPlainHttp(issuer, timeout, clock); the call site is the opt-in.

mayActFor answers for a client. mayUse(applicationCode) answers for an application, from the applications claim: * allows every application, an entry <id>:<code> matches on the code after the first colon, an entry without a colon matches whole, and an empty code is never allowed. A token that must be for this service’s own application checks mayUse("orders").

The verifier’s rules, in order: at most 16 384 characters and three base64url parts; alg exactly RS256, decided before any key is looked at, so none, HS256 and every other value are refused (no algorithm confusion); crit absent; a non-empty kid; the key for that kid from the platform’s own key set (jku, x5u and jwk header parameters are never read); the signature; iss and aud equal to the issuer; exp, nbf and iat with a fixed 60-second allowance; token_use exactly api; a non-empty sub. Only RSA keys of at least 2048 bits are kept. Discovery is refused when its issuer differs, an endpoint is missing, the token endpoint or keys are off the issuer’s origin, or S256 is not offered.

The framework accepts a signed or sealed value only in the spelling it was issued in. Every base64url part must be canonical: only A-Z, a-z, 0-9, - and _, no = padding, no standard-alphabet + or /, no whitespace or line break anywhere, and no other last character that decodes to the same bytes. This applies to the platform access token, the id_token at the callback, the field access token, a device’s DPoP proof (and its key’s x and y), the application nonce, and the sealed session cookie. A part that breaks the rule gets the refusal that part already had: a bad header is malformed, a bad signature is signature, a bad proof is invalid_proof, and a sealed cookie that does not open is no session. The value is checked as received and never trimmed (the whitespace the HTTP syntax allows around a header value is still dropped before that).

Nothing the platform or the framework issued is affected: their encoders are standard unpadded base64url, and a test fixture of values issued before the rule still verifies, including sealed cookies a browser holds across a deploy. What stops working is a value someone re-spelled on the way, or a signer written by hand on an encoder that pads or leaves spare bits set, such as a hand-rolled DPoP proof. A token from a third party is not covered: the framework verifies none today, because it verifies the platform’s own id_token. The full rule and its test vectors are in the token spelling contract. The same rule applies to push tickets and stream tokens (see Push to clients).

A request with an unsafe method (POST, PUT, PATCH, DELETE) authenticated by the session cookie must come from your own pages: Sec-Fetch-Site same-origin or none, or, from an older browser without that header, an Origin equal to auth.public-base-url’s origin. A request with neither header is refused. Refusals are 403 CROSS_ORIGIN_REQUEST, logged at INFO with the method, path and the two header values (cut to 100 characters). A body must then be JSON (application/json or application/*+json), else 415.

There is no CSRF token to fetch or send, and no CORS: a browser’s fetch from your own origin passes as is. Bearer-token requests skip the check. For a public POST of your own (a sign-up form), put the public-form guard on the route (CsrfGuard.publicForm(base).middleware() in Java, httpfw.PublicFormGuard(base).Middleware() in Go). It lets a request with neither header pass, and the body must still be JSON.

Form routes. Server-rendered pages post forms natively. A route declared as a form route (RouteOptions.acceptForms() / httpfw.AcceptForms()) also accepts application/x-www-form-urlencoded and multipart/form-data from a session-cookie request. Everything before the body check is unchanged and runs first. A route not declared that way keeps the JSON-only rule, and the public-form guard stays JSON-only on every route.

POST /auth/logout (subject to the CSRF rules) deletes the session, clears the cookie and answers:

{"loggedOut":true,"endSessionUrl":"https://platform.example.com/auth/oidc/session/end?client_id=orders-web&post_logout_redirect_uri=https%3A%2F%2Forders.example.com%2Fbye"}

The clearing Set-Cookie is sent only to a request that carried a session cookie and passed the CSRF check, so a cross-site POST cannot make a browser drop its session. Navigate to endSessionUrl to end the platform session as well (single logout). Otherwise only your application is signed out.

When the platform’s discovery document has no end-session endpoint, or cannot be read, the answer is {"loggedOut":true} (the field is left out, never null). The same happens when the document names one that is not https (http only in local and test), is not on the issuer’s origin, or carries user-info: it is ignored and logged, because the browser is sent there. The sign-in’s authorization_endpoint must also be https outside those two environments. post_logout_redirect_uri is present when you set a post-logout redirect (.postLogoutRedirect("/bye"), auth.PostLogoutRedirect) and register that URL on the platform client.

Store How Revocable on logout
database Java: list AuthDatabaseModule (the default). Go: authdb.Factory(dbs). Table fw_session; the loop auth-session-purge deletes expired rows every 10 minutes, 1000 at a time yes
redis Java: .sessions(lookup -> RedisSessionStore.create(...)). Go: authredis.Factory(clients). Go needs Redis 6.2 or later (GETDEL) yes
cookie Java: .cookieSessions(). Go: auth.CookieSessions(). Needs auth.cookie-keys no: a copy of the cookie taken before logout works until it expires
memory Java: MemorySessionStore.create(...). Go: auth.MemoryStoreFactory(). One process only yes

The server stores keep only a SHA-256 of the cookie value (base64url), so a leaked table holds no usable cookie. A store that cannot answer fails the request with 500, never “no session”. The database table and the JSON records are identical in both languages.

The cookie store seals the record with AES-256-GCM, binding the record kind in as additional data (so a login record cannot be replayed as a session), with the expiry inside the plaintext. Cookie keys are <kid>:<base64url of 32 bytes>, comma-separated; the first seals, all open. Generate one with CookieKeys.generate("k1") (Go: auth.GenerateCookieKey("k1")). Rotate routinely: put a new key first, keep the old one for the absolute timeout, then remove it. A sealed value over 3 800 characters is an error.

Timeout Default Builder (Java / Go)
idle 30 minutes .idleTimeout(Duration) / auth.IdleTimeout
absolute 8 hours .absoluteTimeout(Duration) / auth.AbsoluteTimeout

The absolute timeout is never extended. A session’s last activity is written back at most once a minute. The session keeps no platform token: roles and permissions are those of the sign-in, so a role change or a deactivation at the platform takes effect at the next sign-in, at most the absolute timeout later. There is no refresh. Portal logins (/portal/*) are not supported.

/auth/login and /auth/callback are limited per client address: by default a memory limiter named auth, 20 a minute, burst 20. Replace it to share it across replicas or to key by the forwarded address behind a proxy:

AuthModule.builder().rateLimit(RateLimit.by(
RedisRateLimiter.create("auth", redis, RateLimitPolicy.of(20, Duration.ofMinutes(1))),
KeyResolvers.forwardedFor(1)).build())

In Go use auth.RateLimit(...) with a limiter keyed by ratelimit.ForwardedFor(n); NoRateLimit removes it. See rate limiting. Behind a proxy, replace the default: it keys on the TCP peer, which is the proxy, so all users share one bucket. The first time a request carries X-Forwarded-For under the default limiter, the module logs one warning saying so.

To accept credentials the framework does not know (a fixed operator token, say) next to platform tokens and sessions, turn off the provided resolver and delegate:

.module(AuthModule.builder().provideContextResolver(false).build())
// in your module's register:
app.provide(ContextResolver.class, lookup -> {
AuthContextResolver platform = lookup.get(AuthContextResolver.class);
return request -> isOperatorToken(request)
? Context.of(ClientSelector.PLATFORM).withPrincipal(new PrincipalId("operator")).withPermissions(Set.of("ingestor:*:*"))
: platform.resolve(request);
});

In Go, pass your own resolver to httpfw.WithResolver(...) and delegate to mod.Resolver().

Your routes with a signed-in user. The test helper creates a real session in your configured store and gives you the cookie. It works only when APP_ENV is test.

AuthTesting auth = AuthTesting.of(app);
String cookie = auth.cookie(AuthTesting.user("prn_T", "orders:clerk"));
TestResponse me = client.get("/api/me").header("Cookie", cookie).send();
client.post("/api/things").header("Cookie", cookie).header("Sec-Fetch-Site", "same-origin").jsonBody("{}").send();
String acmeCookie = auth.cookie(AuthTesting.clientUser("prn_C", "clt_1", "acme"));

Bearer tokens and the login flow. A test identity provider is a real HTTP server shaped like the platform (discovery, keys, authorize, token, end-session). It mints access tokens and can be told to misbehave.

TestOidcProvider provider = TestOidcProvider.start(clock);
provider.client("app-client", "", "https://app.example/auth/callback");
String token = provider.accessToken(Map.of("sub", "prn_SVC", "scope", "orders:thing:create"));
provider.idTokenSigning(TestOidcProvider.Signing.NONE); // and other ways to misbehave
provider.down(true);

TestOidcProvider is in the framework-auth test-jar (<type>test-jar</type>, <scope>test</scope>).

  • The platform must be reachable from your application at auth.issuer, the same URL browsers use. A separate internal URL is not supported.
  • There are no login, error or not-permitted pages: the platform hosts login, and anything else is your application’s. The UI package ships default sign-out, sign-in-failed and unavailable pages.
  • With the cookie store, logout cannot revoke a copied cookie, and a login record cannot be consumed atomically (the platform’s single-use code stops a replayed callback).
  • Go: a store shared by a live Java process and a live Go process has not been tested, and the module has been driven by a browser only against the test provider (Chromium), never a real platform.