Skip to content

CIS security guide: authentication, authorization and BFF

Source-audited implementation reference, 2026-10-19. This describes current source, compatibility paths and operating limits; it does not assert every environment has deployed the same revision. Current build: Spring Boot 4.1.2, Spring Security/MVC 7, Java 25. The BFF is a servlet gateway using filters and Java HttpClient, not a reactive Spring Cloud Gateway application.

This is the single maintained security reference for cis-auth and cis-bff. It includes browser pages, all supported grant flows, API access, configuration, deployment, error handling and a source inventory. The older separate security notes have been consolidated here; historical audit observations are distinguished from current behavior.

Contents

For the end-to-end technical walkthrough, start with the request lifecycle.

For first-time reading, follow sections 1-3, then the page walkthrough in section 20. For implementation work, use the endpoint map and the inventory in sections 13 and 23. For operations, use sections 17-19. All example secrets and tokens are placeholders.

1. Responsibilities and boundaries

Component Responsibility
Angular portals Navigate to login, display application, call BFF with credentials and CSRF
cis-auth Verify identity/account policy; issue tokens; manage clients, keys, revocation and impersonation
cis-bff Own browser callback, store tokens in Redis, manage cookies/session CSRF, proxy APIs and pass bearer tokens through
cis-api / cis-workflow Validate JWTs and enforce business endpoint permissions
Oracle UAM users/roles/history/policy, OAuth clients/authorizations/consents, keys, audit and rotation state
Redis BFF sessions/transactions/leases/rate counters; revocation/indexes and event channel

A user password, OAuth client secret, OAuth token and BFF session cookie are different credentials. A client secret identifies a confidential application, not a person. The cookie references server-held token state; it is not the JWT. RSA private-key encryption does not imply encryption of every OAuth token stored in Oracle or Redis.

Service Host development address Container back channel
BFF http://localhost:8080 cis-bff:8080
Auth http://localhost:8085 cis-auth:8085 in local Compose
API http://localhost:8089 cis-api:8089
Workflow http://localhost:8090 cis-workflow:8090
Internal Angular http://localhost:4201 Browser destination
External Angular http://localhost:4200 Browser destination

Browser-facing URLs and private container endpoints are intentionally different. UAT BFF callback: https://bff.cis.accesscam.org/bff/auth/callback. Production: https://bff.cis.accesscam.org/bff/auth/callback. Portal destinations are separate settings; use different UAT frontend hosts there if your deployment requires them.

2. Choose the correct flow

Requirement Flow Caller receives
Internal/external Angular Authorization Code + PKCE through confidential BFF Session cookie and sanitized profile
External browser user with an enrolled passkey Optional WebAuthn login within the same authorization-code flow; see section 24 Same BFF session cookie and profile
Existing integration submits user credentials Compatibility password grant, directly or through BFF Direct auth: tokens; BFF: cookies/profile
Service/job without a human Client credentials Application access token
REST caller already has a token Bearer API access, not a grant Resource response; no BFF session
Continue a browser session BFF-managed refresh Renewed server-held tokens

New browser work should use authorization code. Password grant remains available for compatibility. Client credentials must not be used to impersonate a human or put an application secret in Angular.

3. Authorization-code flow with PKCE and BFF callback

Registration and actors

Angular is the frontend; BFF is the confidential OAuth client; cis-auth is the authorization server. Both configured browser clients require authorization_code, PKCE and the exact BFF callback registration.

Portal Configured client Persisted client realm
Internal cis-bff-internal-client INTERNAL
External cis-bff-external-client EXTERNAL

IDs/secrets come from CIS_BFF_INTERNAL_CLIENT_ID / CIS_BFF_INTERNAL_SECRET and CIS_BFF_EXTERNAL_CLIENT_ID / CIS_BFF_EXTERNAL_SECRET. Secrets remain server-side. CIS_BFF_CALLBACK_URI is the OAuth redirect. CIS_BFF_INTERNAL_FRONTEND_URL and CIS_BFF_EXTERNAL_FRONTEND_URL are where users land afterward. CORS permission does not register an OAuth callback.

Each step

  1. Angular navigates the browser to GET /bff/auth/authorize with clientId and optional rememberMe. Omitting clientId selects the configured confidential external client.
  2. BffAuthenticationFacade accepts only configured internal/external confidential IDs, loads authenticated metadata, checks the expected realm and confirms the BFF callback is registered. Caller-supplied redirectUri is rejected at this entry point.
  3. BFF generates random state/verifier, computes the S256 challenge, and stores a five-minute BffAuthorizationTransaction in Redis. It contains client, verifier, callback, expiry, remember choice and server-selected portal destination. The HttpOnly CIS_OAUTH_STATE cookie contains state, not the verifier or client secret.
  4. BFF redirects to browser-facing auth /oauth2/authorize with response_type=code, client ID, callback, scopes, state and PKCE challenge. The flow has now started.
  5. Auth validates registration/realm and creates a browser-bound login challenge. The login page renders internal staff/LDAP or external CIS account presentation from the registered realm, not from the frontend hostname or an arbitrary form field.
  6. Browser POSTs credentials to auth /login with its challenge and Spring CSRF token. BrowserAuthenticationProvider invokes shared realm strategies/account policies, rejects a principal from another realm and uses generic browser failure text.
  7. After successful login, BrowserLoginHandlers returns a no-store HTML continuation page (HTTP 200). A same-origin external script navigates to the saved authorization URL; a Continue link supports browsers with JavaScript disabled. This ends the form POST before cross-origin OAuth redirects, preserving CSP form-action 'self'. The browser resumes the saved /oauth2/authorize request. Seeing this URL is expected: auth must issue a code before redirecting. Auth's browser HttpSession is distinct from the later BFF Redis session.
  8. Auth redirects the browser to BFF /bff/auth/callback?code=...&state=....
  9. BFF compares state to the browser cookie before consuming the Redis transaction. It rejects expired, missing, replayed or configuration-mismatched transactions. The OAuth-state cookie is cleared after consuming a matching transaction.
  10. BFF POSTs the code, exact callback and server-held verifier to auth /oauth2/token, authenticating with its confidential client credentials. Auth validates the code, redirect, client and PKCE; token customization rechecks current user policy/roles.
  11. BFF stores access/refresh tokens, identity and CSRF state in Redis, sets session and CSRF cookies, then redirects to the stored configured portal destination. Code/state/access/refresh tokens are not appended to the Angular return URL.
  12. Angular calls GET /bff/auth/me with credentials, reads the sanitized profile and exposed X-XSRF-TOKEN response header, and sends that header on mutations.
sequenceDiagram
    participant Browser as Angular / browser
    participant BFF as BFF 8080
    participant Redis
    participant Auth as Auth 8085
    participant Identity as LDAP and Oracle / Oracle
    Browser->>BFF: GET /bff/auth/authorize
    BFF->>Auth: Protected client metadata lookup
    BFF->>Redis: Save state, verifier and portal destination
    BFF-->>Browser: State cookie and auth authorization redirect
    Browser->>Auth: Authorization request, then login form
    Auth->>Identity: Verify identity, realm and account policy
    Auth-->>Browser: 200 continuation page after successful POST
    Browser->>Auth: Separate navigation to saved authorization request
    Auth-->>Browser: Redirect with code to BFF callback
    Browser->>BFF: GET /bff/auth/callback with code and state
    BFF->>Redis: Validate and consume browser-bound transaction
    BFF->>Auth: Code, verifier and confidential authentication
    Auth-->>BFF: OAuth tokens
    BFF->>Redis: Persist BFF session
    BFF-->>Browser: Session cookies and configured portal redirect
    Browser->>BFF: GET /bff/auth/me with credentials
    BFF-->>Browser: Profile and CSRF response header

Local browser entry points:

  • http://localhost:8080/bff/auth/authorize?clientId=cis-bff-internal-client
  • http://localhost:8080/bff/auth/authorize?clientId=cis-bff-external-client&rememberMe=true

Use top-level browser navigation. REST Client and browser cookie stores are different. Angular no longer receives the OAuth callback or relays a code in the current flow.

State, failure and browser concurrency

Unknown client/caller redirect override is 400; a configured client with an incorrect registered callback/realm produces a service-unavailable configuration error. Invalid browser state cannot consume another transaction. A consumed transaction is single-use, even if provider authorization or code exchange fails; restart sign-in afterward.

One CIS_OAUTH_STATE cookie is used per BFF hostname: parallel starts can replace it. One CIS_SESSION cookie is used per BFF hostname: separate portal clients do not imply independent simultaneous internal/external identities in one browser cookie jar.

4. Password grant: direct API and compatibility BFF login

sequenceDiagram
    participant Caller as Existing caller
    participant BFF
    participant Auth
    participant Identity as LDAP or Oracle identity
    participant Store as Oracle and Redis
    Caller->>BFF: POST /bff/auth/login with user credentials and realm
    BFF->>Auth: Password grant with server-held client authentication
    Auth->>Identity: Verify selected realm and account policies
    Identity-->>Auth: Current user and authorities
    Auth->>Store: Persist authorization and revocation index
    Auth-->>BFF: Access and refresh tokens
    BFF->>Store: Store browser session in Redis
    BFF-->>Caller: Session cookies, profile and CSRF header
    Note over Caller,Auth: Direct integrations can call auth instead and receive tokens directly

Direct password grant

This compatibility flow uses PasswordGrantAuthenticationConverter, PasswordGrantAuthenticationProvider and RealmStrategyRegistry in cis-auth.

  1. A confidential integration POSTs form data to auth /oauth2/token, authenticating its client and providing grant_type=password, username/password, scopes and optionally realm. It is a user grant, not client_credentials.
  2. The provider validates the authenticated client's allowed grant/scopes and invokes the realm registry. For this legacy path, an explicit requested realm wins, then internal/external client-name hints, then stored user type; otherwise external.
  3. The selected strategy verifies credentials, Oracle user/realm consistency, account policies and role names. Browser realm selection instead comes from client settings.
  4. Auth generates/signs tokens, persists authorization state and registers user JTIs in Redis. The direct integration receives OAuth JSON and must protect its tokens. No BFF browser session is created by calling auth directly.
POST http://localhost:8085/oauth2/token
Authorization: Basic <base64(client-id:client-secret)>
Content-Type: application/x-www-form-urlencoded

grant_type=password&username=<user>&password=<password>&realm=EXTERNAL&scope=read

The example has placeholders only. Use HTTPS outside loopback. TLS protects transport; the receiving application still sees credentials, so request bodies must not be logged.

BFF password-login compatibility

  1. Existing callers POST JSON username/password/realm to /bff/auth/login.
  2. BFF chooses its configured internal credentials for INTERNAL, otherwise external, and invokes the auth password grant over the back channel.
  3. Auth performs the same user verification described above.
  4. BFF persists tokens in Redis and returns profile/cookies/CSRF header, not raw tokens.

The endpoint still receives a user's password. It is retained, not used by the new browser callback flow. Migrating browser callers does not itself disable this API.

Legacy public SPA code exchange

The cis-bff--public-client registrations use authentication method none, PKCE and Angular callbacks on 4200/4201. Legacy POST /bff/auth/authorization-code completes compatible existing state and returns cookies/profile; it rejects BFF-owned transactions. Deprecated facade start helpers and CIS_BFF_PUBLIC_ settings are not the current /bff/auth/authorize entry. Use confidential client IDs for the new BFF flow.

5. Client-credentials flow: services and jobs

No human password, LDAP bind, browser callback, PKCE browser state or BFF session cookie is involved. The access token represents an application client.

  1. Provision a confidential client with client_credentials and minimal scopes.
  2. The service authenticates to auth /oauth2/token and requests that grant/scopes.
  3. Auth verifies client secret, enabled state, grant and allowed scopes.
  4. It issues a signed access token and persists authorization. Client/JTI claims identify the token. User enrichers require a CIS user principal: do not assume a machine token has user roles, province or human identity just because it is valid.
  5. The service calls an API with Authorization: Bearer, through BFF /api/** or a directly exposed resource server where allowed. The resource server enforces access.
  6. Obtain another client-credentials token on expiry; this is not a browser-session refresh.
POST http://localhost:8085/oauth2/token
Authorization: Basic <base64(service-client:service-secret)>
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials&scope=read

BFF metadata discovery uses this flow with the dedicated metadata client and scope oauth.public-clients.read. It calls /api/v1/auth/internal/public-clients/{clientId} to retrieve ID, redirects, scopes, enabled/PKCE status and realm, never secrets. The legacy endpoint name says public-clients but also accepts PKCE confidential BFF clients with client_secret_basic. Its service credential is not a frontend secret.

sequenceDiagram
    participant Service as Service client / BFF metadata client
    participant Auth
    participant API as Protected API / metadata endpoint
    Service->>Auth: POST /oauth2/token with client_credentials and client authentication
    Auth->>Auth: Check enabled registration, secret, grants and scopes
    Auth-->>Service: Application access token
    Service->>API: Authorization: Bearer access token
    API->>API: Validate JWT and required scope/authority
    API-->>Service: Authorized response
    Note over Service,API: No human login page, browser cookie or LDAP bind

6. Shared identity verification and account policy

AbstractRealmAuthenticationTemplate validates input, verifies credentials/loads the Oracle user, checks user type against the selected realm, runs ordered applicable policies, resolves role names and creates AuthenticatedUserPrincipal.

Realm Credential authority CIS requirement
INTERNAL Configured LDAP via ActiveDirectoryLdapPortAdapter Oracle CIS user of internal type must exist; successful LDAP bind does not provision an account
EXTERNAL Oracle stored password with configured password encoder / BCrypt compatibility External user type, account rules and role hydration

External authentication performs a dummy password match for a nonexistent user, persists failed retry counts/lockout and resets retries after success. The retry limit comes from PASSWORD_RETRY_COUNT or the configured fallback. The internal LDAP strategy does not implement that external Oracle retry-count loop.

Policy Applies to Result
AccountNonLockedPolicyRule Both Reject locked account
AccountActivePolicyRule Both Reject pending approval/inactive account
PasswordExpiryPolicyRule External Check latest history against PASSWORD_EXPIRED_POLICY/fallback; missing history is not automatically expiry
FirstTimeLoginPolicyRule External Reject reset-password/first-login flag

Authentication exceptions do not roll back persisted retry updates. Browser login presents generic credential/account errors. Password token API responses can include structured lockout/remaining-attempt/first-login/LDAP-registration details. Those are different presenters of shared checks, not separate identity authorities.

7. API access: dual-mode BFF

GatewayAuthModeFilter applies to /api/** and selects handlers by priority.

Request Mode Behavior
BFF session cookie Cookie/session Resolve/renew Redis session, enforce mutation CSRF, inject server-held bearer, remove browser Cookie header
Bearer without BFF session cookie REST pass-through Preserve token; no BFF cookie-session CSRF or session refresh
Both credentials Cookie mode wins Bearer cannot bypass session expiry/CSRF
Neither Anonymous forwarding Downstream endpoint decides whether anonymous access is allowed

CookieSessionAuthHandler enumerates the injected Authorization name as well as returning its value; otherwise the proxy would omit it on ordinary Angular requests. An expired cookie does not fall back to another submitted bearer. Bearer pass-through does not establish a Spring Security user inside BFF or authenticate /bff/auth/me.

BffRouteRegistry matches configured workflow/API patterns, optionally strips prefixes, retains query strings and falls back to the API server. CisApiReverseProxyFilter uses Java HttpClient, copies allowed request/response headers and downstream status, streams the body, forwards DELETE bodies and removes hop/Connection-nominated headers. Cookie stripping is specifically part of cookie mode, not a universal assertion that no possible REST cookie header can reach an upstream.

Downstream application errors normally retain their own status/body. Gateway permitAll allows forwarding; it does not grant access to business data. API/workflow resource servers must validate tokens and enforce endpoint permissions. REST calls still rely on Redis rate limiting when enabled, even though they do not use a BFF session.

8. Refresh-token flow

BFF session renewal

  1. A cookie API request or POST /bff/auth/refresh reads Redis session state.
  2. BffSessionState compares access expiry with the configured refresh skew. /refresh does not unconditionally exchange a fresh token; GET /me does not force renewal.
  3. If renewal is needed but no refresh token exists, BFF deletes the session and returns refresh-unavailable/session-expired rather than inventing a token.
  4. It obtains a 30-second Redis refresh lease with a unique owner. A concurrent loser gets retryable 503 instead of exchanging the same rotating refresh token twice.
  5. The winner rereads session state, calls auth with the original client ID and the configured confidential secret when appropriate, then builds refreshed state.
  6. A Lua compare-and-save checks ownership and session existence. An expired lease owner cannot overwrite another winner or resurrect a deleted session.
  7. Lease release checks ownership. Cleanup failure is logged and the lease expires; it must not replace a successful result or the original failure.

Redis session TTL is updated using normal/remember choice. Remember state has a separate marker/TTL. Browser cookies receive Max-Age when issued; proxy token refresh does not automatically extend browser cookie expiry. Do not describe this as an unbounded sliding browser session.

Auth grant validation, policy recheck and rotation

Authorization-code/refresh customization reloads the current user, account policies and roles, checks browser-client realm and rejects refreshing impersonation identities. Client enabled/deleted state and denylist checks are separate from possession of a refresh string. The confidential BFF authenticates with its server secret; legacy public refresh uses PublicRefreshClientAuthentication instead.

OracleOAuth2AuthorizationService handles CLOB token lookup and framework authorization mapping. When a refresh token changes, RefreshTokenFamilyStore records a SHA-256 history entry in OAUTH2_REFRESH_HISTORY. Replay of a consumed token can revoke its entire authorization family. Sensitive issuance/rotation/revocation operations share a database mutation lock. This is not an atomic distributed Oracle/Redis transaction.

9. Logout and revocation flows

BFF logout

POST /bff/auth/logout uses cookie-session CSRF. BFF resolves the session, notifies auth about its token, removes resolved local session state and clears session/CSRF cookies. Remote notification is best effort. Local logout is not proof that all other authorizations/tokens were revoked. Auth browser SSO logout is separate: this endpoint does not automatically call identity-provider/global logout.

Custom token revocation

Auth POST /api/v1/auth/sessions/revoke-token accepts a token value and optional JTI hint. The route is deliberately permitAll: possession of a recognized token selects what can be revoked. The facade does not trust a standalone/unrelated JTI. It resolves the authorization in Oracle, blacklists the access JTI and removes the authorization, including its refresh credentials. Unknown tokens are idempotent no-ops. Framework OAuth revocation/introspection endpoints also exist; they are not this custom API.

Administrative user-session revocation

An authorized administrator POSTs /api/v1/auth/admin/sessions/revoke-user. The facade locks mutations, resolves the user, recovers access JTIs from Oracle, removes all that principal's authorization rows, revokes indexed Redis JTIs and publishes a user revocation event. Redis broadcast happens after database transaction commit. BFF's subscriber attempts to evict indexed sessions for the user.

Redis Pub/Sub has no durable replay/outbox here. Event broadcast and bulk eviction can log failures; request-time JTI/client checks remain necessary. Deleting OAuth authorizations does not itself destroy every auth browser HttpSession. Redis and Oracle failures must not be mistaken for successful global logout.

10. Administrator impersonation flow

  1. Browser POSTs /bff/auth/impersonate with positive targetUserId or nonblank targetUsername and valid cookie-session CSRF.
  2. BFF loads/renews the caller and checks exact authorities ROLE_ADMIN, ROLE_SUPER_ADMIN, ADMIN or SUPER_ADMIN. Substrings such as SUPERVISOR are insufficient.
  3. BFF calls auth /api/v1/auth/impersonate with the administrator's bearer. Auth derives the acting identity from the authenticated principal, not a submitted admin username.
  4. Auth rechecks administrator/target policy and issues actor-bearing impersonation credentials. BFF creates a separate Redis session linked to the original admin session, switches cookies and returns a sanitized profile.
  5. POST /bff/auth/impersonate/exit verifies current impersonation state, loads the original administrator session, deletes the impersonated BFF session and restores administrator cookies/profile. An expired original session cannot be restored.

Impersonation is not a normal indefinitely refreshable identity. Removing a local session is not evidence of downstream token invalidation; review the separate token lifecycle if investigating access using a copied REST token after exiting impersonation.

11. Signing-key rotation and JWT validation

RsaKeyPairFactory creates RSA material. AesPrivateKeyCipherAdapter uses the configured Spring encryptor password/salt for new private-key storage in RSA_KEY_PAIRS. Its legacy decryption fallback can accept unencrypted Base64/PEM material; do not assume all older rows are encrypted. All instances need compatible encryption configuration.

Scheduled or administrator KeyRotationFacade acquires the shared mutation lock, deactivates active keys with grace, purges expired grace keys, creates a new active key and publishes a local rotation event. Registration policy limits access-token lifetime relative to grace so valid tokens do not unnecessarily outlive verification keys.

OracleRsaKeyPairJwkSource returns active/grace descriptors. Despite its name, CachingJwkSourceDecorator currently rereads delegate descriptors instead of retaining a stale cross-node key list. Signing uses the active key ID; /oauth2/jwks publishes public verification keys. There is no general Redis-broadcast RSA cache-invalidation contract implemented merely because a local rotation event exists.

RotatingJwtDecoder in auth validates RS256, timestamps and configured issuer, then requires a JTI, available/enabled client and absence of token/client revocation. Revocation-store failure rejects validation. Downstream API/workflow validators have their own configurations; auth decoder behavior alone is not proof of their entire permission/revocation contracts.

JWT customization assigns JTI/client_id/clientRegistrationId and, for a CIS user, identity, authority, province, realm and impersonation actor claims. User claims come from Oracle-backed principal construction/rechecks, not from arbitrary browser fields. BFF's optional JWT payload parsing is profile extraction, not independent signature validation; its upstream OAuth responses must be trusted and transported securely.

12. Client administration and complete token settings

Client management supports create, list/get, secret rotation and delete. Registration policy checks grants/authentication methods, required realm, PKCE for public clients, HTTPS/loopback redirects, secret lengths and access lifetime versus key grace. Generated/supplied secrets are returned at creation/rotation time; summaries do not return them. RotatingClientSecretEncoder provides an overlap envelope for old/new hashes. Public clients using none have no rotatable secret.

The controller has no generic PUT/PATCH for callback updates. Change an existing registration through approved provisioning/migration, not undocumented delete/recreate. Deletion sets persistent client-revocation markers and removes related authorizations/ consents. New registration IDs distinguish recreated clients from old tokens.

Secret rotation is a separate lifecycle flow: an administrator authenticates, requests rotation, receives the newly generated/supplied raw secret once, distributes it through server secret management, and moves callers to it during the configured overlap. The metadata client's optional secret-file supplier can reload its credential on subsequent lookup; ordinary internal/external BFF environment secrets require the matching runtime configuration/restart. Secret rotation is not RSA signing-key rotation and does not by itself mean every existing access token was revoked.

Why authorizationCodeTimeToLive was null

Handwritten TOKEN_SETTINGS JSON omitted framework-required defaults. Loading that map is not equivalent to calling TokenSettings.builder(). The resulting null TTL failed during authorization-code generation, before the BFF could receive a code. All six local client registrations had incomplete settings, not only the internal BFF.

Required setting Current seed/backfill contract
Authorization-code TTL Five minutes
Device-code TTL Five minutes; this does not enable device grant support
Access-token TTL Preserve explicit value: user-client seeds one hour, metadata client five minutes
Refresh-token TTL Preserve explicit value: user-client seeds 30 days; missing values use framework fallback
Access-token format Self-contained
Refresh-token reuse False in module defaults; preserve explicit stored overrides
ID-token signature algorithm RS256
X.509-bound access tokens False; not a statement that mTLS client authentication is configured

R__01_seed_oauth2_registered_clients.sql now contains complete typed JSON. R__03_backfill_oauth2_token_settings.sql merges defaults below existing settings for rows missing required fields. It changes TOKEN_SETTINGS only. Typed duration, algorithm and access-token-format representations matter to JDBC deserialization.

EnabledRegisteredClientRepository fills absent/null known defaults when reading or saving older partial registrations, preserves explicit custom values, and still rejects disabled clients. It does not hide malformed JSON, invalid types or arbitrary invalid values. The tested local backfill updated six rows on 2026-10-19. This manual local repair does not mark a Flyway migration applied; its idempotent deployment backfill remains safe to run through the normal migration path.

13. Endpoint reference

BFF

Method / path Meaning and protection
GET /bff/auth/authorize Confidential browser start; clientId/rememberMe optional; caller redirectUri rejected
GET /bff/auth/callback Browser-bound single-use state, confidential code exchange, cookies and portal redirect
GET /bff/auth/me Session profile and exposed CSRF token; unauthenticated 401
POST /bff/auth/refresh Session renewal if near expiry; cookie CSRF
POST /bff/auth/logout Cookie-session logout/CSRF
POST /bff/auth/impersonate Session CSRF plus exact administrator checks
POST /bff/auth/impersonate/exit Session CSRF and original-admin-session restoration
POST /bff/auth/login Compatibility JSON username/password flow
POST /bff/auth/authorization-code Legacy SPA exchange; rejects BFF-owned transactions
/api/** Cookie/bearer/anonymous proxy dispatch; final permissions downstream
Actuator Operational exposure per configuration; not all probes imply authenticated access

Auth

Method / path Meaning and protection
GET /oauth2/authorize Authorization request, registered redirect, PKCE, browser realm handling
POST /oauth2/token Registered OAuth grants and client authentication
/oauth2/jwks and configured OIDC/protocol endpoints Framework protocol behavior; public keys, discovery/userinfo, revocation/introspection as configured
GET/POST /login Auth browser page/form, server challenge and form CSRF
/logout, /signed-out, /login-assets/** Auth browser session/logout/assets; Spring logout CSRF behavior remains enabled
GET /api/v1/auth/internal/public-clients/{clientId} Bearer oauth.public-clients.read scope; enabled PKCE client metadata, no secret
POST /api/v1/auth/sessions/revoke-token Token-possession revocation; optional JTI is only a hint
POST /api/v1/auth/admin/sessions/revoke-user Administrator user authorization/token revocation
POST /api/v1/auth/impersonate Administrator bearer identity, principal-derived acting user
GET/POST /api/v1/auth/admin/clients Administrator list/create
GET/DELETE /api/v1/auth/admin/clients/{clientId} Administrator get/delete
POST /api/v1/auth/admin/clients/{clientId}/rotate-secret Administrator confidential-secret rotation
POST /api/v1/auth/admin/keys/rotate Administrator signing-key rotation

Admin routes require the exact four authority names listed in the impersonation section. The metadata scope is a separate authority and is not equivalent to merely being authenticated as a human. Framework OAuth endpoints follow their own chain, not the custom management-controller response contract.

14. Security filters and persisted state

Auth has three ordered security chains:

  1. OAuth/OIDC endpoint matcher: realm/mutation filters, client authentication, custom password grant, public-refresh compatibility, protocol handlers and conditional browser session creation. Its protocol CSRF configuration is separate from the browser form chain.
  2. Browser /login, /logout, /signed-out and assets: server challenge, realm provider, form CSRF and session-fixation protection; browser HttpSession allowed.
  3. Management/resource API: stateless JWT, admin/scoped matchers, health/info and token-possession revocation exceptions. CORS is disabled in this auth API chain.

BFF uses credentialed CORS, stateless Spring Security policy and custom Redis sessions. Its custom filter sequence is security headers, correlation, exception boundary, rate limiter, session-mutation CSRF, gateway mode selection, then proxy. Servlet registration is disabled for component filters already installed inside Spring Security. Otherwise a component could run outside the intended exception/security boundary.

State Owner / storage Lifetime or purpose
Browser auth login challenge Auth HttpSession Expiring, bounded server-owned contexts; not BFF session state
BFF OAuth transaction Redis session-prefix + oauth:transaction: Five minutes, consumed once
BFF session Redis session-prefix + session ID Configured normal/remember session TTL
Refresh lease Redis session-prefix + refresh-lease: Owner-checked, 30 seconds
Remember marker Redis session-prefix + remember: Separate configured TTL
User-session index Redis user-session prefix Enables bulk BFF eviction
Rate counter Redis rate-limit prefix and bucket/IP Atomic fixed 60-second expiry
Token denylist / user token index Auth Redis configured prefixes Token lifetime/revocation rules, Lua coordination
Client deletion markers Auth Redis client/legacy-client suffixes Persistent registration/client identity rejection
OAuth clients/authorizations/consents Oracle Durable protocol/client state; token columns are sensitive
Refresh replay history Oracle OAUTH2_REFRESH_HISTORY Hashed consumed-token history through token expiry
Security mutation lock Oracle AUTH_SECURITY_LOCK Database serialization of sensitive mutations
RSA signing keys Oracle RSA_KEY_PAIRS Active plus grace verification material
User/role/config/password history Existing Oracle UAM tables Identity/account-policy authority
Auth audit Oracle AUDIT_LOG Event persistence; details representation discussed below

Prefixes must match across writers and consumers. Lua makes particular operations atomic; it does not make every session/index write or Oracle/Redis operation a single distributed transaction. Oracle/JDBC authorization token storage is sensitive; RSA-key encryption is not evidence that all token values are encrypted at rest.

15. Cookies, CORS and frontend behavior

CIS_SESSION is HttpOnly. The CSRF cookie is separate/readable. Secure, SameSite, Max-Age and optional Partitioned attributes come from configuration. Current dev uses loopback/nonsecure/Lax; UAT/prod use Secure/Lax. SameSite is not unconditionally Strict. Auth browser session cookies and BFF session cookies serve different purposes.

The BFF module env variable CIS_BFF_CORS_ALLOWED_ORIGIN_PATTERNS is localhost-based in dev and https://*.cis.accesscam.org in UAT/prod. Methods, request headers, credentials and exposed response headers are environment-backed too. Compose selects cis-bff/.env.; root orchestration env files are not a substitute for module settings. The allowed wildcard deliberately trusts its subdomains.

A CSRF cookie on the BFF hostname cannot be read directly by Angular on another host. After login/redirect, make credentialed GET /bff/auth/me, read X-XSRF-TOKEN and supply it on mutations. The current CORS exposure allows that response header. Reading a header on an Angular HTTP response is different from top-level navigation following a redirect. Never expose OAuth access/refresh tokens merely to work around CSRF.

Cookie + bearer selects cookie mode, so the bearer cannot bypass CSRF. CORS does not authenticate REST callers, register OAuth redirects or replace mutation CSRF.

16. Errors, resilience, health, metrics and audit

BFF generated errors use ProblemDetail. MVC failures retain 400/404/405/406/415 and protocol headers such as Allow. Domain codes/account attributes are preserved where part of the compatibility contract. LDAP registration profile data is intentionally included by that specific compatibility response. Generic internal messages are sanitized. Dependency transport failure is 503; proxy I/O/connect is 502; proxy timeout is 504; unexpected bugs are 500. The filter boundary delegates pre-controller exceptions to MVC. A committed stream cannot be rewritten as a new JSON error.

Auth has distinct browser, OAuth token and REST error presenters. Browser feedback is generic; token errors follow OAuth handling and may carry domain fields; REST advice uses its own structured domain response. An incomplete client token-settings map is a configuration error, not invalid user credentials.

Rate limiting is an atomic fixed Redis window, not a sliding token bucket. Its stricter budget covers login, authorize, legacy code exchange and refresh; callback currently uses the general budget. Missing Redis results fail closed. Client-IP extraction trusts forwarded headers, so ingress must sanitize those headers.

Circuit breakers wrap upstream calls; an HTTP 500 response is not automatically a thrown transport failure in this proxy. Body streaming occurs after header acquisition; initial HTTP timeout is not a guaranteed deadline for an entire long-lived streamed body. There is no implied automatic retry of arbitrary non-idempotent requests.

Correlation IDs are generated or accepted only with bounded safe characters, returned and forwarded. Proxy metrics are bff.proxy.latency and bff.proxy.requests.total, with route/status/family tags as implemented; rate-limit rejections have a counter. The downstream health indicator makes auth decisive and records API results in its details; it is not a strict all-upstream readiness gate. Redis has a separate probe.

BFF audit events are asynchronous log records, not an Oracle audit table. Auth's listener persists AUDIT_LOG and uses Map.toString for details, not guaranteed JSON. It is annotated Async but the auth application does not itself enable async processing; do not promise off-thread behavior without additional configuration evidence. Event logging is not proof of durable distributed delivery or completed global revocation.

17. Migration and troubleshooting

Auth owns FLYWAY_SCHEMA_HISTORY_AUTH; other modules have separate histories. Applied versioned migrations remain immutable. Client seeds/settings use repeatable idempotent scripts. Do not run every module's migration inventory indiscriminately in a shared schema.

Symptom What to check
External page for internal login Confidential internal client ID and persisted authentication realm
CSP blocks login form redirect Restart auth with the continuation-page change; begin a fresh challenge; keep strict form-action policy
Login resumes auth /oauth2/authorize Expected code-issuance step; investigate only if it fails to continue
Angular receives /oauth/callback Legacy public-client registration; current flow registers BFF callback
Invalid/missing state Same browser cookie store, expiry, replay, parallel starts, exact callback/return settings
authorizationCodeTimeToLive cannot be null Complete typed TOKEN_SETTINGS, R__03 backfill, not only one manually added TTL
Angular reaches API without bearer Cookie wrapper's header enumeration, session refresh and selected proxy mode
403 on browser POST/PUT/PATCH/DELETE Credentialed session and matching CSRF header
REST works but browser CORS fails Actual origin plus module CORS methods/headers/exposure and cookies
503 on concurrent refresh Lease contention/expiry; retry instead of concurrently redeeming one refresh token
Token works after a local logout elsewhere Separate authorization, remote best-effort revoke, auth SSO session and downstream denylist contract
Signature failures after rotation Issuer, key grace, encryption configuration and downstream JWKS refresh

Do not troubleshoot by disabling signature checks, realm restrictions, client authentication or CSRF. Trace the selected flow, registered client, persisted settings, cookie jar and environment configuration. Avoid logging raw credentials/tokens.

18. Validation strength and open operating contracts

The BFF callback revision passed 106 BFF tests and 15 focused auth tests. The subsequent token-settings fix passed 13 focused seed/JDBC deserialization, missing-default/disablement and authorization-code security-chain tests, with zero failures/errors/skips. Those are snapshots, not a production certification. The earlier full auth suite was stopped while waiting for an isolated Oracle test container and is not claimed as passed.

The local Oracle token-settings-only repair updated six clients after compatibility tests passed. Existing explicit lifetimes/rotation and unrelated registration columns were preserved. No production database was changed. A browser/LDAP sign-in against the deployed build, CORS/cookie behavior, multi-node sessions and every downstream permission still require environment validation.

Known operating boundaries, not claimed fixes: Pub/Sub has no replay, bulk BFF eviction can log failure, auth browser HttpSession is separate from BFF Redis state, same-host cookies are shared by portals, IP headers require trusted ingress, and stream failures cannot replace committed responses. Spring annotations/class names are not proof of async execution, cache coherence, durable events or end-to-end revocation guarantees.

Scope of account UI and authentication factors

The modules enforce account flags and password-age rules; that is not evidence they implement every registration, password-reset or approval UI. BrowserAuthenticationProvider adds a password-factor authority, not an implemented second-factor/MFA enrollment flow. Account lifecycle work owned by other modules must be traced separately.

19. Environment configuration and rollout

Environment files and URL ownership

Use the module's .env.dev, .env.uat or .env.prod; matching .example templates are the checked-in configuration contract. Root environment files control Compose orchestration and published ports, and do not replace the module environment files. Spring does not automatically load arbitrary .env files. Gradle bootRun selects module environment files with -Penv=dev, -Penv=uat or -Penv=prod; other launchers must supply the variables explicitly. The inventory below maps variables to consumers.

Setting Development UAT Production
CIS_BFF_CALLBACK_URI http://localhost:8080/bff/auth/callback https://bff.cis.accesscam.org/bff/auth/callback https://bff.cis.accesscam.org/bff/auth/callback
CIS_BFF_INTERNAL_FRONTEND_URL http://localhost:4201/ https://internal.cis.accesscam.org/ https://internal.cis.accesscam.org/
CIS_BFF_EXTERNAL_FRONTEND_URL http://localhost:4200/ https://external.cis.accesscam.org/ https://external.cis.accesscam.org/
CIS_BFF_CORS_ALLOWED_ORIGIN_PATTERNS Configured localhost origins https://*.cis.accesscam.org https://*.cis.accesscam.org

Use separate UAT portal destinations if your frontend deployment uses different hosts. Callback and portal settings require HTTPS except loopback development, reject query, fragment and user-info components, and require the callback path /bff/auth/callback. A configuration change invalidates older pending browser transactions: start again.

AUTH_SERVER_URL is the BFF server-to-server token/metadata endpoint. In host development it is http://localhost:8085; in local Compose it is http://cis-auth:8085. CIS_BFF_AUTHORIZATION_BASE_URL is browser-facing and remains http://localhost:8085 for that Compose setup. Browsers cannot normally resolve Docker service names, and localhost inside a container points to that container. Use trusted HTTPS in deployment; CIS_BFF_ALLOW_INSECURE_BACK_CHANNEL is an explicit local-development opt-in.

Metadata credentials are separate from internal/external BFF user-client credentials. Configure CIS_BFF_METADATA_CLIENT_SECRET or CIS_BFF_METADATA_SECRET_FILE to match the dedicated auth registration. The file source is reread on discovery refresh; environment credentials require process replacement after rotation. Missing deployment secrets must be supplied, never copied from development examples. Client-secret overlap must cover metadata cache lifetime and rollout delay, within the auth policy limits.

Discovery, cache and registration changes

Condition Result
Fresh metadata Reuse within configured TTL
Expired metadata, service available Refresh against the scoped metadata endpoint
Transport/5xx failure within stale grace Previously validated metadata may be reused
No cached entry or grace exhausted Fail closed with dependency error
Authentication/authorization failure or missing registration Evict/reject; no stale fallback
Disabled client or changed realm Auth rechecks current registration regardless of BFF cache

The current metadata endpoint accepts eligible PKCE public clients and confidential BFF clients using client_secret_basic. A cached entry cannot make auth accept an unregistered callback, disabled client or wrong realm. Direct SQL enablement changes do not themselves broadcast logout of already-issued sessions/tokens.

Rollout checklist

  1. Verify BFF 8080, auth 8085, API 8089, workflow 8090 and Angular 4201/4200 for local host development. Check published ports separately from container ports.
  2. Apply the module's migrations through its configured Flyway history. Keep applied versioned migrations unchanged. Auth requires its security-lock schema/row and refresh-history migrations before the coordinating implementation serves traffic.
  3. Apply repeatable client seeds and token-settings backfill through the normal migration process. The seed upgrades recognized obsolete local callback URLs, preserves custom deployment URLs and existing secrets, and does not configure your UAT callback for you.
  4. Register the exact environment BFF callback for both confidential clients and require PKCE. Legacy public Angular callbacks are compatibility registrations only.
  5. Match client credentials, Redis namespaces, issuer and signing-key encryption settings across the processes that use them. Retain revocation markers and key grace material.
  6. When introducing security-mutation coordination, replace all auth nodes with compatible versions; older nodes do not participate in its Oracle lock. Deploy the matching BFF.
  7. Restart auth/BFF and use a fresh browser authorization. Verify each portal, callback, /me, API mutation CSRF, refresh and logout with the same browser cookie store.
  8. Test LDAP, cookies/CORS, multi-node behavior and downstream permissions in the target environment. Unit/security-chain tests do not establish those deployment contracts.
python scripts/config/check_auth_env.py
python scripts/config/check_auth_env.py --examples-only
.\gradlew.bat :cis-auth:test --tests '*AuthorizationCodeSecurityIntegrationTest' --console=plain
.\gradlew.bat :cis-bff:test --console=plain

The environment checker reports key problems without printing secret values. Full auth integration tests may start isolated Oracle/Redis containers; plan for Docker availability. These are verification commands, not a statement that every command was rerun for this documentation-only consolidation.

20. Browser pages and annotated walkthrough

Capture status and how to read these notes

The descriptions below were checked against the current templates, renderer and handlers. They are source-based page notes, not screenshots or proof of a completed live login. This session has no available browser connection, so actual page captures could not be added. When captures are available, embed them here beside these notes rather than creating another reference document. Keep image assets under docs/assets/images/security/; use empty credential fields and omit cookies, tokens, real user profiles and challenge values. Record the environment, build/date and page state with each capture.

Page A: Internal staff login

Open http://localhost:8080/bff/auth/authorize?clientId=cis-bff-internal-client by browser navigation. BFF starts authorization and auth sends the browser to its challenged login page; opening /login directly is not the entry point.

Visible area / control Meaning and behavior
CIS / Connected services Local branding; page and assets are served by cis-auth
Internal staff badge Comes from the registered client's INTERNAL realm
Welcome back / client name Escaped registered display name identifies the application
Organisation username Staff organization account; LDAP verifies credentials
Password / Show Masked password with visibility toggle; visibility does not change transport
Sign in securely Posts to same-origin auth /login with hidden challenge and Spring CSRF
Progress message Button disables while submitting; pageshow restores controls
Trusted-address note User should check the real auth origin before entering credentials

LDAP success still requires a matching CIS internal user and account-policy checks. There is no realm dropdown or failed-login fallback to external database authentication.

Page B: External portal login

Open http://localhost:8080/bff/auth/authorize?clientId=cis-bff-external-client. The shared template displays External portal, CIS username, the registered client name and external account help text. ExternalDbAuthStrategy verifies the CIS database password hash and account policies. The page appearance follows the registered realm; CORS and frontend domain names do not choose the credential store.

Page C: Failed sign-in

The challenged login page shows: "We couldn't sign you in. Check your details and try again." The browser message deliberately does not distinguish unknown username, bad password, lockout or other account-policy failures. A valid challenge may be retried; no password is returned in the rendered form. Compatibility REST responses can retain specific domain codes and account attributes under their separate contract.

Page D: Successful sign-in continuation

POST /login succeeds with HTTP 200 and a no-store page titled Continue sign-in. It says "Sign-in successful. Continuing to your application." and has a Continue link. The local continue.js navigates to the saved same-origin authorization URL using location.replace; the link works when JavaScript is unavailable. The URL contains the captured OAuth request, never the submitted password.

This deliberately ends the credential form submission before OAuth redirects to another origin. Chrome can otherwise apply form-action 'self' to the full redirect chain and block the BFF callback. Keep the strict policy. The continuation uses an external local script and an HTML-escaped, server-built target; it does not allow arbitrary form targets.

Seeing /oauth2/authorize briefly is expected: auth must create the code before calling BFF. BFF then exchanges the code on its back channel and redirects to its configured internal/external portal. Angular receives its normal page, then calls /bff/auth/me.

Page E: Expired, missing or consumed challenge

Auth renders Start sign-in again and explains that the request is missing, expired, already used or unavailable. Return to the portal and start at BFF authorize. Do not reuse an old challenged URL or manufacture a challenge. A successful submission consumes the challenge, preventing its reuse even after browser back navigation.

Page F: Signed out

Auth's CSRF-protected POST /logout redirects to /signed-out, which displays "You are signed out". This ends auth's browser session. BFF logout separately clears its own Redis session/cookies; it does not automatically visit this page or perform single logout across every portal.

Browser verification notebook

Check Expected observation
Internal start Internal staff page, or matching-realm SSO
External start External portal page, or matching-realm SSO
Wrong password Generic error without a credential echo
Successful POST Continuation page, separate authorize navigation, BFF callback, configured portal
Portal URL after completion No OAuth code, state or access/refresh token
Credentialed /me Sanitized profile and exposed X-XSRF-TOKEN header
Cookie mutation without CSRF Rejected; repeat with current CSRF succeeds if otherwise authorized
Reused/expired challenge or state Rejected; new authorization succeeds
BFF logout BFF session unusable; auth SSO may still exist
Auth logout Local signed-out page; does not prove all distributed sessions revoked

Capture the pages with notes, rather than raw network exports containing authorization headers or cookies. The latest continuation change passed all 10 authorization security integration tests; a real-browser capture/verification remains outstanding.

Angular integration after the redirect

The frontend starts navigation with its configured confidential BFF client ID. It does not supply redirectUri, receive a code, or hold a client secret. Example for internal:

const start = new URL('/bff/auth/authorize', environment.bffBaseUrl);
start.searchParams.set('clientId', 'cis-bff-internal-client');
start.searchParams.set('rememberMe', String(rememberMe));
window.location.assign(start.toString());

After arriving back at the portal, fetch /bff/auth/me with credentials included and read the X-XSRF-TOKEN response header. Keep that value in application state and send it on cookie-authenticated mutations. An Angular interceptor must cover the configured cross-origin BFF URL; the default same-origin XSRF behavior alone may not cover it. This is an integration contract, not a change to the separate Angular repositories.

SSO and direct protocol controls

A matching-realm auth HttpSession can avoid another credential prompt. A different realm requires its own authentication. Direct valid authorization requests enforce prompt=none (no form; login_required if authentication is needed), prompt=login (fresh credentials), max_age (freshness), and prompt=consent (preserved through login). Invalid combinations, unknown prompts, duplicate critical parameters and invalid redirects/PKCE are rejected. The BFF convenience endpoint exposes clientId and rememberMe, not a general prompt/max_age forwarding API. Fresh authentication removes prompt=login/max_age from the resumed request so it does not loop; consent remains subject to registered policy and existing grants.

21. Security controls and audit record

This section records the resulting controls, not the obsolete pre-fix implementation. It supersedes the separate discovery, hardening and BFF exception audit notes. Historical test counts describe those revisions and are not cumulative coverage or certification.

Finding Result
A GET against a POST-only endpoint reached the generic exception handler and returned 500. The advice extends Spring MVC's ResponseEntityExceptionHandler, retaining framework statuses and headers, including 405 and Allow.
Missing/invalid parameters, unsupported media types, method validation and explicit status exceptions could fall through to 500. Framework exception handling preserves their statuses. Public details are sanitized; body-validation field messages remain available without rejected values.
Cookie authentication, Redis rate limiting and CSRF failures occur before MVC advice. A filter boundary delegates exceptions to MVC's configured resolver. Committed responses and unresolved failures are rethrown.
Component filters also auto-registered in the servlet chain, allowing rate limiting to run outside the security exception boundary. Servlet registration is explicitly disabled for filters already installed in Spring Security.
Security entry/denial responses and session CSRF failures had different error paths. Entry/denial handlers and session CSRF use the common problem response handling. CORS rejection remains controlled by Spring's CORS processor.
Token parsing errors were caught again and converted into 401; auth-server outages also became 401. Domain errors retain their meaning; unavailable/rate-limited auth token services return 503, malformed successful token responses return 502, and missing access tokens are rejected. Known account-state responses remain intact.
Proxy timeout was caught as a generic I/O error; raw exception strings were interpolated into JSON. Timeout returns 504; connection failure returns 502; unexpected failure returns 500. Generated errors use the MVC serializer and sanitized messages. A partial committed stream is never rewritten.
Invalid requested redirect/client input raised a generic programming exception. Expected redirect/client validation failures use explicit 400 domain exceptions. Programming exceptions still return sanitized 500 responses.
Session serialization failures were logged while login could continue as if storage succeeded. Persistence serialization failure propagates; session establishment cannot report success after that failure.
Impersonation/revocation back-channel requests had no explicit transport timeouts. Both use bounded connection/read timeouts. Impersonation transport and malformed response errors are sanitized.

Additional auth/BFF controls verified in the source audit:

  • OAuth security mutations use an Oracle row lock across cooperating auth nodes. Client authentication happens before token mutation locking; response buffering prevents a successful token response escaping before transaction commit. This serializes mutations and requires throughput testing for the intended deployment.
  • Refresh reloads current account policies/roles; persisted principals use an explicit deserialization allowlist. Consumed refresh tokens have hashed replay history.
  • Revocation reads/writes fail closed. Token indexing retains expiry plus validation clock allowance. Lua preserves the longest blacklist/index lifetime; legacy unknown-expiry JTIs are handled conservatively instead of guessing a safe expiry.
  • Standard/custom/user revocation removes the appropriate persisted authorizations and refresh capability. Untrusted JTI hints cannot revoke unrelated tokens. Oracle CLOB lookups use DBMS_LOB.COMPARE. In-flight accepted requests can still finish.
  • Client create/delete/secret rotation participate in mutation coordination. Token issuance revalidates client snapshots after locking. Permanent client markers and internal registration IDs prevent recreating an external client ID from reviving old tokens.
  • Key bootstrap/rotation coordinate across nodes; failed replacement rolls back deactivation. The active signing key is selected explicitly and retired verification keys remain for grace.
  • Cookie wrappers enumerate the injected bearer header and remove browser cookies before forwarding. Cookie authentication wins over a simultaneous bearer header.
  • OAuth state-cookie comparison occurs before Redis transaction consumption. Refresh commits only while the lease/session is still owned; lease cleanup cannot replace the original failure or invalidate a successful result.
  • Rate increments/expiry are atomic, missing expiry is repaired, and absent Redis results fail closed. Trusted ingress must sanitize forwarded IP headers.
  • Proxy DELETE bodies are preserved, hop-by-hop and Connection-nominated headers stripped, correlation IDs bounded, and metrics recorded even on generated proxy errors.
  • Impersonation uses authenticated administrator identity and exact authorities, validates target ID/username and avoids null audit-map crashes. Transport calls have bounded timeouts.

Registration limits, supported grants/authentication combinations, key-grace relationships, secret overlap, enabled-client behavior and partial token-settings compatibility remain explained in sections 6 and 11-12. Pub/Sub replay, bulk-eviction failures, committed-stream limits, session sharing and downstream validation limits remain in sections 8-9 and 16-18. No historical audit finding is permission to relax those controls during troubleshooting.

22. Complete request lifecycle and fish diagram

How to use this technical guideline

Read the six-stage spine from left to right. Branches identify the controls at that stage; this is a fish-style flow diagram, not a cause-and-effect analysis. The image summarizes multiple HTTP requests across one signed-in session. A business API request is a separate exchange from the browser login and token endpoint exchanges.

CIS request lifecycle fish diagram: browser start, auth verification, BFF callback, BFF forwarding, cis-api execution and response

Open scalable SVG. The diagram is based on repository source; it is not a screenshot of a running service. The diagram's API revocation check has the implementation limits described below.

Stage 1: Browser asks BFF to start authentication

  1. Internal Angular navigates to BFF 8080 /bff/auth/authorize?clientId=cis-bff-internal-client; external Angular selects cis-bff-external-client. This is top-level navigation.
  2. BFF checks its configured client choice, discovers the enabled registered client's realm/redirects/scopes, and verifies its own exact callback. Discovery uses a separate service token with oauth.public-clients.read; a fresh cache can avoid that HTTP call.
  3. BFF creates state and a PKCE verifier, stores the transaction/portal destination in Redis for five minutes, sets the browser-bound OAuth state cookie, and redirects to auth's browser-facing /oauth2/authorize. The verifier and client secret stay server-side.

Result: an authorization request exists; the user does not yet have a BFF session.

Stage 2: Auth verifies the user and issues an authorization code

  1. Auth checks client/redirect/scopes/PKCE and the persisted realm. A sufficiently recent matching-realm auth session may satisfy SSO. Otherwise it creates an auth-session-bound login challenge and renders the internal/external login page on auth 8085.
  2. The browser posts username/password, hidden challenge and Spring CSRF token to auth /login. Internal verification uses LDAP plus a CIS internal-user record; external verification uses the CIS database password. Both apply the relevant account policies.
  3. Successful login returns HTTP 200 with the no-store continuation page. Its local script, or the fallback Continue link, navigates to the saved relative authorization request. This breaks the form-POST redirect chain while retaining strict form-action CSP.
  4. Auth creates the short-lived authorization code and redirects the browser to BFF /bff/auth/callback?code=...&state=.... Auth's browser HttpSession belongs to auth; it is distinct from the BFF Redis session that will be created next.

Result: the browser carries a one-time code to BFF. Angular does not receive that callback.

Stage 3: BFF exchanges the code and creates its session

  1. BFF compares the returned state to its browser cookie before consuming the transaction. It checks expiry, configured callback and stored portal destination. Missing, mismatched, expired or reused state fails; the caller must restart authorization.
  2. BFF calls auth /oauth2/token over AUTH_SERVER_URL with authorization_code, code, exact callback and stored PKCE verifier, authenticating with its server-held client secret. Auth validates the code/client/verifier and current user policy/roles, signs the JWT, persists authorization state in Oracle and maintains its revocation index in Redis.
  3. BFF stores access/refresh tokens, expiry, JTI, identity and session CSRF state in Redis, sets the HttpOnly session cookie and CSRF cookie, and redirects to its configured portal.
  4. Angular calls credentialed /bff/auth/me and reads the sanitized profile and exposed X-XSRF-TOKEN header. OAuth tokens are not returned to Angular or appended to the portal URL.

Result: browser has a session identifier; BFF holds tokens; auth owns durable OAuth state.

Stage 4: BFF processes a business request

  1. Angular sends its business request to BFF /api/**, with credentials included and the current X-XSRF-TOKEN header for POST/PUT/PATCH/DELETE. A cross-origin browser may first issue a CORS preflight. Successful preflight is permission to send, not authentication.
  2. BFF applies CORS/security headers, safe correlation ID, its exception boundary and the Redis rate limiter. The separate BffSessionCsrfFilter protects BFF session mutations; CookieSessionAuthHandler performs the CSRF check for cookie-authenticated /api/**.
  3. GatewayAuthModeFilter chooses cookie mode first. It loads the Redis session and checks its JTI and client-deletion markers. A corrupt/missing/revoked session cannot provide a bearer token. A simultaneous caller bearer header does not bypass cookie-mode failure.
  4. If access-token expiry is within the configured skew, BFF acquires a 30-second owner lease, rereads the session and calls auth's refresh grant using the original client. Auth rotates tokens and rechecks user/client policies; BFF commits only while it still owns the lease and the session exists. Contention/commit failures are retryable 503s. A valid sufficiently fresh access token skips this entire auth call.
  5. CookieSessionAuthHandler then verifies mutation CSRF, removes the browser Cookie header and replaces/enumerates Authorization with the session's bearer token. In this current implementation token renewal can occur before this API mutation CSRF check.
  6. BffRouteRegistry picks the first configured matching route, optionally strips its configured prefix and preserves the query string. Without a match, it uses the configured cis-api base URL. Workflow routes can select cis-workflow instead; confirm route settings. The proxy strips hop-by-hop headers and sends the method/body and correlation ID through a bounded HTTP call wrapped by the route circuit breaker.

Result: cis-api receives a bearer-authenticated HTTP request, not the browser's BFF cookie. A normal fresh-token request is browser -> BFF -> cis-api; it does not visit auth per request.

Stage 5: Cis-api authenticates, authorizes and executes

  1. ResourceServerSecurityConfig uses NimbusJwtDecoder and its configured JWKS endpoint to verify the signature, configured issuer/resource audience and timestamp constraints. Signed iat plus exp, sub, client_id and jti are required; missing/blank claims are rejected. Public keys can be cached; JWKS lookup is not a token introspection or a password check for each business request.
  2. JwtToSecurityUserConverter maps verified claims into SecurityUser and granted authorities for the current request. Cis-api creates no BFF session and does not trust browser-supplied identity headers as a replacement for the bearer token.
  3. RedisTokenRevocationFilter checks the JWT JTI and client-registration deletion marker against the configured revocation prefix (with a legacy client-ID marker fallback). Revocation/deletion returns 401; Redis failure or an indeterminate result returns 503, and neither reaches business execution. Anonymous public requests do not require Redis.
  4. URL security requires authentication except for its explicit public allowlist. Method annotations/custom permission expressions apply where declared; service/domain rules still determine record access and valid operations. Authentication alone does not prove a caller has every business permission, and not every method has an explicit role check.
  5. Spring binds and validates controller inputs, calls the endpoint's service, repository and database, then maps/serializes the result. Transaction boundaries and response wrappers are endpoint-specific. Do not assume every request writes data or opens a distributed transaction spanning BFF, auth, Redis and Oracle.

Result: cis-api produces its endpoint response or security/validation/domain error.

Stage 6: Response, subsequent requests and session termination

  1. BFF copies allowed upstream response headers/status and streams the body back. The BFF correlation ID remains authoritative, and proxy route/status/latency metrics are recorded. A completed cis-api error response retains its original body/status; BFF does not convert every upstream error into its own ProblemDetail envelope.
  2. Angular handles the returned status/body. Missing/invalid authentication requires a new sign-in; a retryable infrastructure failure is different. Do not blindly retry a mutation whose database commit outcome is unknown, especially after a timeout or disconnected stream.
  3. Future API calls repeat stages 4-6. Explicit BFF refresh uses the same session renewal logic; /me itself does not silently renew the token. Remember-me session policy does not override auth refresh-token expiry or account disablement.
  4. A CSRF-protected BFF logout resolves the session, attempts remote token revocation, deletes resolved local session state and clears cookies. Remote notification is best effort. Successful local logout does not prove that auth's separate browser SSO session or every distributed session has ended. Auth browser logout and administrator user revocation have their own flows in section 9.

Detailed service sequence: login, API, renewal and logout

sequenceDiagram
    autonumber
    participant Browser as Angular / browser
    participant BFF as cis-bff :8080
    participant Redis
    participant Auth as cis-auth :8085
    participant API as cis-api :8089
    participant DB as Oracle / identity services
    Browser->>BFF: GET /bff/auth/authorize with configured clientId
    opt Metadata cache needs refresh
        BFF->>Auth: Client-credentials token and scoped metadata lookup
        Auth-->>BFF: Eligible registration metadata
    end
    BFF->>Redis: Store state, verifier and portal destination
    BFF-->>Browser: State cookie and auth authorization redirect
    Browser->>Auth: GET /oauth2/authorize
    Auth-->>Browser: Challenged realm-specific login page unless SSO applies
    Browser->>Auth: POST /login with credentials, CSRF and challenge
    Auth->>DB: Verify realm identity and CIS account policies
    Auth-->>Browser: 200 continuation page
    Browser->>Auth: Separate GET of saved authorization request
    Auth-->>Browser: Redirect to BFF callback with code and state
    Browser->>BFF: GET /bff/auth/callback
    BFF->>Redis: Check browser-bound state and consume transaction
    BFF->>Auth: Code exchange with confidential credentials and PKCE
    Auth->>DB: Persist OAuth authorization and current user claims
    Auth->>Redis: Index issued token for revocation
    Auth-->>BFF: Access and refresh tokens
    BFF->>Redis: Persist session, token state and CSRF
    BFF-->>Browser: Cookies and configured portal redirect
    Browser->>BFF: GET /bff/auth/me with cookies
    BFF-->>Browser: Profile and X-XSRF-TOKEN response header
    Browser->>BFF: Business /api/** with cookies and mutation CSRF when needed
    BFF->>Redis: Rate limit, session and revocation checks
    opt Token needs renewal
        BFF->>Redis: Acquire owner lease and reread session
        BFF->>Auth: Refresh grant using original client
        Auth->>DB: Recheck policy, rotate tokens and record replay history
        Auth->>Redis: Update token index
        Auth-->>BFF: Rotated tokens
        BFF->>Redis: Commit if lease and session still owned, release lease
    end
    BFF->>BFF: Check API mutation CSRF, remove cookie, inject bearer, resolve route
    BFF->>API: Original API method/path/body with bearer and correlation ID
    opt JWKS cache needs a signing key
        API->>Auth: Fetch public JWKS
        Auth-->>API: Public verification keys
    end
    API->>API: Verify signature, issuer, audience and required claims, map principal
    API->>Redis: Check JTI and client revocation, fail closed if unavailable
    API->>API: Enforce URL/method policy and validate input
    API->>DB: Endpoint service and repository operation
    DB-->>API: Result
    API-->>BFF: Endpoint status, headers and body
    BFF-->>Browser: Stream response, record proxy metrics
    Browser->>BFF: POST /bff/auth/logout with session CSRF
    BFF->>Auth: Attempt token revocation when session token was resolved
    Auth->>DB: Remove matching OAuth authorization / refresh capability
    Auth->>Redis: Record revocation and publish notification
    BFF->>Redis: Delete resolved local session
    BFF-->>Browser: Logout response and cookie clearing
    Note over Browser,Auth: Auth browser SSO logout is separate

This sequence shows the successful path. Failed state/CSRF, rejected policy, dependency failure or revocation stops later steps; auth browser SSO can skip credential entry. Redis Pub/Sub is best effort, not a durable event queue or a prerequisite for each call.

Concrete API trace and credential boundaries

For a read-only protected example, use BFF GET /api/v1/province/list/address?provinceId=<existing-id>. The default core route preserves that path and query to cis-api. ProvinceResource validates the provinceId and calls ProvinceService for the address result. Existence of an ID and endpoint-specific permissions must be checked in the target environment. /api/v1/province/list is an explicitly public endpoint and should not be used as proof that protected authentication works.

Hop Credential or data Where it ends
Browser -> auth login User password, auth form CSRF and login challenge Auth identity verification
Browser -> BFF callback One-time authorization code and state BFF consumes state and exchanges code
BFF -> auth token endpoint Client authentication, code/verifier or refresh token Auth token processing
Browser -> BFF API HttpOnly session cookie; mutation CSRF header BFF session and CSRF checks
BFF -> cis-api Server-held access token in Authorization; correlation ID API JWT/security chain
Cis-api -> repository/database Validated business arguments under endpoint policy Endpoint-specific persistence operation
Cis-api -> BFF -> browser Endpoint status/headers/body Frontend handling; no OAuth token exposure

REST bearer callers skip the cookie-session branch: BFF passes their token through, without creating a BFF principal/session or performing cookie CSRF. Cis-api still verifies it. Anonymous calls may be forwarded; the downstream public allowlist decides access. Neither branch makes BFF the final business authorization authority.

Failure checkpoints and recovery

Checkpoint Visible outcome / action
Invalid callback/state or consumed transaction Reject; begin fresh browser authorization
Expired/missing BFF session or revoked JTI API session access fails with 401; sign in again
Missing/mismatched API mutation CSRF BFF 403 before business forwarding
Disallowed browser origin CORS rejects/withholds browser access; inspect preflight and origin settings
Rate budget exhausted BFF 429; respect rate policy
Redis/auth dependency or renewal lease contention Controlled dependency/renewal error, commonly 503; use bounded retry where safe
Invalid/expired JWT, wrong issuer/audience, or token/client revocation Cis-api 401; do not treat it as a business permission failure
Downstream permission denial Cis-api 403; inspect URL/method/domain policy
Invalid endpoint input Downstream validation response; correct the request
Proxy circuit open / transport failure / timeout BFF 503 / 502 / 504 respectively, if response is uncommitted
Response already streaming when connection fails Partial/failed response; BFF cannot replace it with a clean error body
Local logout succeeded but auth browser still signed in Separate SSO session; integrate its logout when required

Current implementation limits to account for

The diagram describes actual checks, not a claim of uniform enforcement everywhere:

  • The earlier missing issuer/audience and fail-open revocation gaps are fixed in source. API validation now requires the configured issuer/audience, timestamp checks and required claims. Redis checks use the verified JWT token object, not erasable password-token credentials. Known revocation returns 401 with a Bearer invalid_token challenge; Redis exceptions/null results return 503 with Retry-After and a sanitized ProblemDetail. Filter servlet auto-registration is disabled so the check runs in the intended security chain.
  • JwtToSecurityUserConverter maps the authorities claim; it does not automatically turn every OAuth scope into a SCOPE_ authority. Machine tokens have no guaranteed human profile.
  • API CSRF and CORS are disabled at its resource-server chain; the intended browser boundary is the configured BFF. Direct ingress and public endpoint policy must be reviewed separately.
  • Cookie API handling may refresh tokens before its mutation CSRF verification. BFF session mutation endpoints use their earlier dedicated CSRF filter. Do not describe identical ordering for these two request types.
  • Login does not rerun on each business call, and JWKS retrieval does not mean auth approves every API operation. A committed business mutation may outlive the caller's HTTP timeout.

These observations document current source behavior. The issuer/audience and revocation changes require deployment of the updated auth/API builds; they do not certify every resource server or historical token as compliant.

Source map for this walkthrough

Responsibility Current implementation
Browser start/callback, refresh and logout BffAuthenticationFacade
BFF custom filter ordering BffSecurityConfig
API cookie/bearer dispatch GatewayAuthModeFilter
Session lookup, conditional renewal, API CSRF and bearer injection CookieSessionAuthHandler
Redis session/JTI/client checks RedisBffSessionStoreAdapter
Routing and streaming proxy BffRouteRegistry, CisApiReverseProxyFilter
API JWT and URL security ResourceServerSecurityConfig
API principal/authorities JwtToSecurityUserConverter
API request-time revocation RedisTokenRevocationFilter
API method authorization support MethodSecurityConfig, RestPermissionEvaluator
Example endpoint and service ProvinceResource, ProvinceService

Resource-server hardening and rollout contract

This implements the issuer/resource-audience checks described by RFC 9700 section 2.3, the JWT access-token validation guidance, and Spring Security token validator composition. Fail-closed Redis checks are this application's revocation availability policy, not a claim that OAuth mandates a particular Redis design or an HTTP 503 status for every deployment.

OAuth 2.1 remains an IETF draft. Its password grant is omitted. This repository retains the legacy password compatibility flow described in section 4, so these fixes must not be described as whole-system OAuth 2.1 certification or full RFC 9068 JWT-profile compliance. Removal of legacy password clients requires a separate consumer migration; it is not silently disabled by this hardening.

Variable Auth API Meaning
CIS_AUTH_ISSUER_URI cis.auth.issuer-uri cis.auth.issuer-uri Exact public issuer; host dev 8085, UAT and production auth ingress
CIS_AUTH_RESOURCE_AUDIENCE cis.auth.resource-audience cis.auth.audience Stable API resource identifier, currently cis-api
CIS_AUTH_JWK_SET_URI Not used for auth's signing-key storage cis.auth.jwk-set-uri Public keys; local Compose uses http://cis-auth:8085/oauth2/jwks
CIS_AUTH_REVOKED_TOKEN_PREFIX cis.auth.redis.revoked-token-prefix cis.auth.redis.revoked-token-prefix Shared revocation namespace

All dev/UAT/prod module files and examples carry these settings. Local Compose overrides API's JWKS back channel to the Docker service while retaining the published public issuer. Issuer validation never substitutes the private JWKS hostname for the public token issuer.

Auth issues the configured API audience only when the token's authorized scopes include read or write. Current API user/client registrations already use these resource scopes; new API consumers must explicitly be registered/requested for them. Metadata-only and openid/profile-only tokens retain their OAuth client audience and are rejected at cis-api. ID tokens do not gain API audience/client_id access claims. Refresh and impersonation use the same access-token customizer. Audience membership does not replace endpoint permissions.

Deploy auth first so newly issued/refreshed API tokens have the resource audience, then API with matching trust settings. Restart both with their environment files. Old access tokens with the former client audience are rejected once API enforcement is active; refresh after auth deployment or start a fresh browser login. There is no permissive legacy audience fallback. A BFF session whose old token is still fresh does not automatically refresh simply because API now returns 401, so fresh sign-in is the reliable rollout path.

Regression coverage includes signed-JWT wrong/missing audience/issuer/claims, bad signature, expired/future token, known JTI/client/legacy-client revocation, Redis exceptions/nulls, anonymous public access, credential-erasure-safe principal mapping, all three environment contracts, and scope-selected audiences across password/code/refresh/client credentials. These tests use local JWKS and mocked Redis transport; live failover and deployment remain separate operational checks.

Page captures for this walkthrough

Use the page-by-page notes in section 20 for the internal login, external login, failed login, continuation, expired challenge and signed-out states. No browser connection was available for this update, so actual screen captures remain pending. The embedded fish diagram is an illustration, not a substitute for screenshots or proof of live browser behavior. Add future captures beside the relevant section 20 notes, with build/environment/date and empty credential fields.

23. Component and configuration inventory

The following source map and environment bindings are part of this guide. Paths are relative to this document. Inventory checked on 2026-10-19; linked source is authoritative when names or Javadoc promises differ from actual execution. No secret values are included.

cis-auth: 114 production Java source files

Component / source Responsibility
AuditLogPublisher Source-defined component or port; see linked implementation.
AuditLogEntity Source-defined component or port; see linked implementation.
AuditLogEventListener Auth AUDIT_LOG persistence; details use Map.toString and Async annotation alone does not enable async execution.
AuditLogRepository Source-defined component or port; see linked implementation.
CisAuthApplication Starts auth, enables scheduling/caching and binds CisAuthProperties; no explicit EnableAsync annotation.
AuthorizationServerSecurityConfig Builds the three auth security chains, client/authorization services, token generators, decoders and protocol handlers.
BrowserLoginSettings Bounds pending browser authentication requests independently of the Angular applications.
CisAuthProperties Type-safe, validated configuration properties for the cis-auth Authorization Server. Binds issuer URI, RSA key management, LDAP connection thresholds, Redis namespaces, and security policies.
LdapRealmConfig Spring configuration bean establishing pooled LDAP context source and LdapTemplate for the internal AD realm.
AuthCredentialsCommand Encapsulates raw authentication credentials submitted by an OAuth2 client or user.
AuthenticatedUserPrincipal Represents an authenticated CIS principal containing user identity, roles, provinces, and realm context.
AuthRealm Enumeration identifying CIS authentication realms: INTERNAL (Active Directory LDAP) and EXTERNAL (Oracle DB BCrypt).
BrowserLoginContext Immutable session-bound challenge; authorization destination is captured only from a validated request.
CisUserStatus Lifecycle statuses for CIS users (PENDING, ACTIVE, INACTIVE, LOCKED, DELETED).
CisUserType User classification types across the CIS system (INTERNAL, EXTERNAL, SYSTEM).
ClientRegistrationCommand Inbound command for administrative registration of an OAuth2 client.
ClientRegistrationResponseDto Outbound response DTO containing registered client details and the unhashed raw client secret. Note: The raw secret is only returned once upon registration or rotation.
ClientSummaryDto Summary DTO of an OAuth2 client for query operations (omitting secret hash for security).
PublicClientMetadataDto Public-client discovery payload includes its server-owned authentication realm.
RotateSecretCommand Command to trigger rotation of an OAuth2 client's secret. If newSecret is null or blank, a cryptographically secure secret is generated automatically.
RotateSecretResponseDto Response returned following client secret rotation, exposing the newly generated raw secret.
LdapUserProfile Immutable value object holding user attributes extracted from corporate Active Directory.
RsaKeyDescriptor Cryptographic descriptor holding RSA key pair metadata, public key, private key, and validity status.
AuditLogEvent Source-defined component or port; see linked implementation.
AccountLockedException Domain exception thrown when an authentication attempt is made against a locked user account.
AccountPendingOrInactiveException Domain exception thrown when a user account has not yet been approved or is inactive.
CisSecurityDomainException Base exception for all domain-specific security, authentication, and authorization failures in cis-auth.
ClientAlreadyExistsException Domain exception thrown when attempting to register a client with an already existing clientId.
ClientNotFoundException Domain exception thrown when an OAuth2 client is not found in the registration repository.
FirstTimeLoginException Domain exception thrown when an external user must reset their password on first login.
ImpersonationSecurityException Exception thrown when administrative user impersonation validation fails.
InvalidClientRegistrationException Source-defined component or port; see linked implementation.
InvalidCredentialsException Domain exception thrown when invalid credentials are provided, carrying remaining retry count.
LdapUserNotRegisteredException Domain exception thrown when an LDAP-authenticated user has no corresponding record in the CIS UAM database.
PasswordExpiredException Domain exception thrown when a user's password age exceeds the configured system policy threshold.
ImpersonationFacade Revalidates authenticated admin and target before issuing actor-bearing impersonation credentials.
KeyRotationFacade Serializes active-key replacement, grace deactivation/purge and local rotation event publication.
SessionTerminationFacade Token-possession or admin user revocation across Oracle authorization state and Redis denylist/indexes.
CisRoleEntity JPA Entity mapping the CIS ROLES table.
CisSystemConfigEntity JPA Entity mapping system-wide security thresholds and configuration keys from SYSTEM_CONFIGURATION.
CisUserEntity JPA Entity mapping the core user record in USERS.
CisUserPasswordHistoryEntity JPA Entity tracking historical hashed passwords in USER_PASSWORD_HISTORY to prevent password reuse.
CisUserRoleEntity JPA Entity mapping user-role assignments in USER_ADDITIONAL_ROLE.
RsaKeyPairEntity JPA Entity storing versioned RSA key pairs, active status, and AES-256 encrypted private keys in RSA_KEY_PAIRS.
CisRoleRepository Spring Data JPA repository for querying roles.
CisSystemConfigRepository Spring Data JPA repository for querying system configuration parameters.
CisUserPasswordHistoryRepository Spring Data JPA repository for historical password retrieval.
CisUserRepository Spring Data JPA repository for user lookup by username, email, or user ID.
RsaKeyPairRepository Spring Data JPA repository managing cryptographic key pairs in Oracle DB.
ActiveDirectoryLdapPortAdapter Configured LDAP credential bind and profile extraction behind the LDAP port.
AesPrivateKeyCipherAdapter Spring text encryption for private keys with explicit legacy unencrypted-material fallback.
EnabledRegisteredClientRepository Honors client enabled flag and supplies missing token defaults while preserving explicit stored settings.
LdapAuthenticationPort Port interface defining Active Directory LDAP authentication contract.
OracleOAuth2AuthorizationService Oracle CLOB-aware token lookup, framework authorization mapping, invalidation and refresh-family hooks.
PrivateKeyCipherPort Port interface defining cryptographic cipher operations for asymmetric private keys.
RedisTokenRevocationStoreAdapter Lua-backed user/JTI registration/revocation and persistent client markers; failure is not accepted as verification.
RefreshTokenFamilyStore Hashes consumed refresh tokens into Oracle history and resolves replay families under the mutation lock.
RotatingClientSecretEncoder Current/previous secret hash envelope with bounded credential overlap.
RotatingJwtDecoder Current-key RS256/issuer/time validation plus enabled-client and token/client revocation checks.
SecurityMutationLock Serializes security mutations across auth nodes. The row lock lasts until transaction completion.
TokenRevocationStorePort Port interface defining token and session revocation storage contract.
AccountActivePolicyRule Validates that a user account is in ACTIVE status before permitting token issuance.
AccountNonLockedPolicyRule Validates that a user account is not locked before permitting token issuance.
AuthorityClaimEnricher Enriches JWT tokens with user roles and granted authorities.
CompositeJwtTokenCustomizer JTI/client identity plus ordered user-claim enrichment; refresh/code user policy and role reload.
FirstTimeLoginPolicyRule Validates whether an external user is required to reset their password on first login.
IdentityClaimEnricher Enriches JWT tokens with user ID, username, and email claims.
ImpersonationClaimEnricher Enriches JWT tokens with RFC-8693 actor and impersonation claims when acting on behalf of another user.
JwtClaimEnricher Interface for modular JWT token claim customization steps.
PasswordExpiryPolicyRule Validates that user password age has not exceeded system policy thresholds.
ProvinceAndRealmClaimEnricher Enriches JWT tokens with user province assignment and authentication realm context.
UserAccountPolicyRule Interface for modular user account validation policy rules.
BrowserLoginContextService Creates/resolves/consumes bounded expiring auth HttpSession challenges and revalidates registered client/realm.
ClientAuthenticationRealm Authoritative cis.authentication-realm reader for registered browser clients.
ClientManagementPort Port defining administrative OAuth2 registered client lifecycle operations.
ClientManagementService Transactional client create/read/secret rotation/delete with validation, revocation and auditing.
ClientRegistrationPolicy Validates client methods/grants/scopes/redirects/secrets, browser realm/PKCE and TTL/grace compatibility.
RegisteredClientMapper Constructs complete framework settings for new clients and maps secret-safe summary/registration responses.
CachingJwkSourceDecorator Despite its name, currently delegates current descriptor reads instead of retaining a stale cross-node cache.
JwkKeySourcePort Port interface supplying Nimbus JWKSource and active signing key descriptors.
OracleRsaKeyPairJwkSource Loads current active/grace RSA descriptors and bootstraps signing material as implemented.
AuthDomainEventPublisher Publishes local key/user events and broadcasts user revocation after commit; broadcast failure logs are best effort.
RsaKeyRotatedEvent Domain event fired when an RSA key pair is rotated in the cluster.
UserSessionRevokedEvent Domain event fired when a user session or token is invalidated across the cluster.
AuthenticatedPrincipalFactory Factory constructing AuthenticatedUserPrincipal domain instances from entity records.
RsaKeyPairFactory Factory generating new cryptographically secure 2048-bit RSA key pairs.
KeyRotationScheduler Invokes key rotation on the configured schedule.
AuthenticationRealmStrategy Strategy interface for realm-specific user authentication.
BrowserAuthenticationProvider Authenticates browser challenge context through shared realm rules and returns password-factor authorities.
ExternalDbAuthStrategy Oracle password verification, timing fallback, failed retries/lockout and success reset.
InternalLdapAuthStrategy LDAP verification followed by required Oracle internal CIS registration and policy checks.
PasswordGrantAuthenticationConverter Parses the compatibility password grant into its authentication command/token.
PasswordGrantAuthenticationProvider Validates authenticated client/grant, verifies user through realm strategy and issues/persists tokens.
PasswordGrantAuthenticationToken Authentication token holding password grant credentials in the Spring Security context.
PublicRefreshClientAuthentication Compatibility authentication for public refresh-token requests with registered public-client checks.
RealmStrategyRegistry Selects realm strategy; legacy fallback heuristics are distinct from browser registered-realm binding.
RotatingPublicRefreshTokenGenerator Refresh-token generation for public compatibility while retaining confidential-client generation behavior.
AbstractRealmAuthenticationTemplate Invariant credential/user-type/policy/role/principal sequence; persists external failed attempts across auth errors.
AuthExceptionHandlerAdvice REST domain/security error conversion; separate from browser and OAuth token endpoint presenters.
AuthorizationMutationFilter Coordinates protocol mutations with transaction/shared database lock.
AuthorizationRealmFilter Binds browser authorization/login to registered realm and prevents inappropriate cross-realm session reuse.
BrowserAuthenticationDetailsSource Supplies validated browser login context to the authentication provider.
BrowserLoginHandlers Consumes successful login challenge and resumes saved authorization; routes login failures and restart errors.
LoginPageRenderer Escapes/populates the auth-owned template with realm/client/challenge/CSRF presentation.
OAuth2TokenEndpointErrorResponseHandler Token endpoint OAuth/domain response handling, separate from MVC controller advice.
BrowserLoginResource Serves the realm-specific local sign-in view from a session-bound challenge.
ClientManagementResource REST controller exposing administrative endpoints for programmatic OAuth2 client registration and lifecycle management.
ImpersonationResource REST controller providing administrative user impersonation endpoints.
KeyRotationResource REST controller exposing administrative endpoints for manual RSA key rotation.
PublicClientMetadataResource Scope-protected enabled/realm-aware PKCE metadata; public and confidential-basic clients, never secrets.
SessionRevocationResource REST controller exposing endpoints for token and user session revocation.
ImpersonateUserRequestVm Request payload for administrative user impersonation.
RevokeTokenRequestVm View model payload for token revocation requests.
RevokeUserSessionsRequestVm View model payload for user session revocation requests.

cis-bff: 43 production Java source files

Component / source Responsibility
BffAuditEvent Immutable domain event representing an auditable security or session lifecycle event in CIS-BFF. Encapsulates the security action, identity of the principal, target session,
BffAuditLogListener Asynchronous BFF event logging, not database audit persistence.
BffAuditLogPublisher Publisher service dispatching security audit events across the CIS-BFF boundary. Decouples security-critical components such as the authentication facade and
CisBffApplication Starts the servlet BFF, binds properties and enables asynchronous event handling.
BffCorsSettings Explicit environment-backed cross-origin policy for BFF browser clients.
BffOAuthSettings Public browser endpoints are independent of private back-channel routing.
BffSecurityConfig Credentialed CORS, custom-filter ordering, problem handlers and disabled duplicate servlet registrations.
CisBffProperties Type-safe, validated configuration properties for the cis-bff Dual-Mode Gateway. Binds upstream service URLs, multi-service route definitions, OAuth2 client credentials per realm,
RedisPubSubConfig Spring configuration establishing Redis Pub/Sub subscription for auth domain events. Binds RedisAuthEventSubscriber to the cluster-wide revocation channel.
BffAuthorizationCodeCommand Legacy SPA code-exchange payload, distinct from the GET BFF-owned callback.
BffAuthorizationTransaction Immutable Redis state, PKCE verifier, client/callback, expiry/remember choice and server-selected frontend URI.
BffImpersonateCommand Command payload for requesting administrative user impersonation in the BFF.
BffLoginCommand Legacy password request and sanitized nested user-profile response; does not expose raw OAuth tokens in the profile.
BffSessionState Immutable token-bearing Redis session and impersonation link; determines refresh need and produces refreshed copies.
OAuthTokenExchangeResult Immutable representation of an OAuth2 token exchange response from cis-auth.
PublicClientMetadata Public-client metadata obtained from the authenticated authorization server.
BffLdapUserNotRegisteredException Exception thrown when an LDAP user authenticates successfully against Active Directory but does not yet possess a corresponding user profile in the CIS database.
BffSecurityException Domain exception thrown when BFF authentication, session lookup, or CSRF verification fails. Carries an error code, target HTTP status, message, and contextual domain attributes
BffAuthenticationFacade Owns browser start/callback, session establishment/read/refresh/logout, compatibility login and impersonation.
AuthServerClientPort Port interface defining back-channel HTTP communications between cis-bff and cis-auth. Encapsulates OAuth2 password grant exchange, refresh token renewal, and token revocation.
BffSessionStorePort Port interface defining Redis session persistence operations for cis-bff. Isolates core BFF session logic from the underlying Redis storage mechanics.
RedisBffSessionStoreAdapter Custom Redis session/index/transaction/remember persistence and owner-checked refresh Lua operations.
RestAuthServerClientAdapter Back-channel service/password/code/refresh requests, revocation notification, impersonation and OAuth error translation.
BearerPassThroughAuthHandler Passes bearer-only REST calls through; does not validate JWT or create a BFF Spring principal.
CookieSessionAuthHandler Session/CSRF check, refresh and request wrapper that enumerates/injects Authorization and strips Cookie headers.
GatewayAuthModeHandler Handler interface for Dual-Mode Gateway authentication dispatching. Evaluates whether an incoming HTTP request should be processed as an Angular SPA Cookie
RedisAuthEventSubscriber Best-effort revocation-event deserialization and indexed BFF session eviction; failures are logged.
BffCookieFactory Creates/clears session, CSRF and OAuth-state cookies from configured attributes.
DownstreamServicesHealthIndicator Auth/API probes; overall health is auth-driven and API result appears in details.
RedisSessionStoreHealthIndicator Reports BFF session-store probe health; not proof an end-to-end login succeeds.
BffGatewayMetrics Proxy latency/request counters and rate-limit rejection metric registration.
PublicClientRegistry Authenticated PKCE-client discovery with bounded in-memory TTL/stale grace; never retrieves client secrets.
BffResilienceManager Per-route circuit-breaker registry and execution wrapper; transport exceptions differ from HTTP error statuses.
BffRouteRegistry Pattern-based route selection, prefix manipulation, target/query construction and API fallback.
BffExceptionHandlerAdvice ProblemDetail conversion for MVC, domain, dependency and security failures; preserves framework status/header semantics.
BffExceptionTranslationFilter Routes uncommitted filter exceptions to MVC advice without rewriting committed responses.
BffRateLimitingFilter Atomic fixed-window Redis counters and 429 responses; depends on trusted forwarded-IP ingress handling.
BffSecurityHeadersFilter Applies browser/security headers and no-store controls to auth/API responses.
BffSessionCsrfFilter Protects browser session mutations separately from API cookie-mode CSRF and PKCE callbacks.
CisApiReverseProxyFilter Java HTTP proxy, headers/body/status streaming, timeout/transport classification and gateway metrics.
CorrelationIdFilter Bounds/sanitizes or generates correlation ID, returns it and manages MDC cleanup.
GatewayAuthModeFilter Chooses cookie mode before bearer mode on /api/**; permits anonymous forwarding when neither applies.
BffAuthResource HTTP adapter for BFF browser/session/compatibility endpoints; delegates orchestration to the facade.

Environment placeholders and their consumers

These names are read from application.yaml; values belong in each module .env.dev, .env.uat or .env.prod (with tracked .example templates). This inventory records bindings, not live secrets or an assurance that all templates are configured for your deployment. Direct annotation/property lookups and operational JVM/container settings must also be checked when changing runtime configuration. The main reference explains key groups.

cis-auth YAML bindings

Environment variable Application property
CIS_AUTH_CLIENT_SECRET_OVERLAP cis.auth.client-secret-overlap
CIS_AUTH_DEFAULT_MAX_PASSWORD_RETRIES cis.auth.policy.default-max-password-retries
CIS_AUTH_DEFAULT_PASSWORD_MAX_AGE_DAYS cis.auth.policy.default-password-max-age-days
CIS_AUTH_DEFAULT_REVOCATION_TTL cis.auth.redis.default-revocation-ttl
CIS_AUTH_ISSUER_URI cis.auth.issuer-uri
CIS_AUTH_RESOURCE_AUDIENCE cis.auth.resource-audience
CIS_AUTH_LOGIN_CONTEXT_TTL cis.auth.browser-login.context-ttl
CIS_AUTH_LOGIN_MAX_PENDING cis.auth.browser-login.max-pending
CIS_AUTH_REVOCATION_CHANNEL cis.auth.redis.revocation-channel
CIS_AUTH_REVOKED_TOKEN_PREFIX cis.auth.redis.revoked-token-prefix
CIS_AUTH_USER_SESSIONS_PREFIX cis.auth.redis.user-sessions-prefix
FLYWAY_ENABLED spring.flyway.enabled
HIBERNATE_FORMAT_SQL spring.jpa.properties.hibernate.format_sql
HIKARI_CONNECTION_TIMEOUT spring.datasource.hikari.connection-timeout
HIKARI_IDLE_TIMEOUT spring.datasource.hikari.idle-timeout
HIKARI_LEAK_DETECTION_THRESHOLD spring.datasource.hikari.leak-detection-threshold
HIKARI_MAX_LIFETIME spring.datasource.hikari.max-lifetime
HIKARI_MAX_POOL_SIZE spring.datasource.hikari.maximum-pool-size
HIKARI_MIN_IDLE spring.datasource.hikari.minimum-idle
HIKARI_POOL_NAME spring.datasource.hikari.pool-name
HIKARI_VALIDATION_TIMEOUT spring.datasource.hikari.validation-timeout
LDAP_BASE_DN cis.auth.ldap.base-dn
LDAP_CONNECT_TIMEOUT_MS cis.auth.ldap.connect-timeout-ms
LDAP_ENABLED cis.auth.ldap.enabled
LDAP_MANAGER_DN cis.auth.ldap.manager-dn
LDAP_MANAGER_PASSWORD cis.auth.ldap.manager-password
LDAP_READ_TIMEOUT_MS cis.auth.ldap.read-timeout-ms
LDAP_URL cis.auth.ldap.url
LDAP_USER_SEARCH_BASE cis.auth.ldap.user-search-base
LDAP_USER_SEARCH_FILTER cis.auth.ldap.user-search-filter
MANAGEMENT_ENDPOINTS_WEB_EXPOSURE_INCLUDE management.endpoints.web.exposure.include
MANAGEMENT_HEALTH_SHOW_DETAILS management.endpoint.health.show-details
REDIS_HOST spring.data.redis.host
REDIS_PASSWORD spring.data.redis.password
REDIS_PORT spring.data.redis.port
REDIS_TIMEOUT spring.data.redis.timeout
RSA_ENCRYPTOR_PASSWORD cis.auth.keys.encryptor-password
RSA_ENCRYPTOR_SALT cis.auth.keys.encryptor-salt
RSA_KEY_GRACE_PERIOD cis.auth.keys.grace-period
RSA_KEY_ROTATION_CRON cis.auth.keys.rotation-cron
RSA_KEY_SIZE_BITS cis.auth.keys.key-size-bits
SERVER_COMPRESSION_ENABLED server.compression.enabled
SERVER_PORT server.port
SPRING_DATASOURCE_PASSWORD spring.datasource.password
SPRING_DATASOURCE_URL spring.datasource.url
SPRING_DATASOURCE_USERNAME spring.datasource.username
VIRTUAL_THREADS_ENABLED spring.threads.virtual.enabled

cis-bff YAML bindings

Environment variable Application property
AUTH_SERVER_URL cis.bff.auth-server-base-url
CIRCUIT_BREAKER_ENABLED cis.bff.resilience.circuit-breaker-enabled
CIRCUIT_BREAKER_FAILURE_RATE_THRESHOLD cis.bff.resilience.failure-rate-threshold
CIRCUIT_BREAKER_OPEN_WAIT cis.bff.resilience.wait-duration-in-open-state
CIRCUIT_BREAKER_SLOW_CALL_THRESHOLD cis.bff.resilience.slow-call-duration-threshold
CIS_API_URL cis.bff.api-server-base-url
CIS_API_URL cis.bff.routes.target-url
CIS_BFF_ALLOW_INSECURE_BACK_CHANNEL cis.bff.allow-insecure-back-channel
CIS_BFF_API_PATH_PATTERN cis.bff.routes.path-pattern
CIS_BFF_API_PREFIX_TO_STRIP cis.bff.routes.prefix-to-strip
CIS_BFF_API_ROUTE_ID cis.bff.routes.id
CIS_BFF_API_STRIP_PREFIX cis.bff.routes.strip-prefix
CIS_BFF_API_TIMEOUT cis.bff.routes.timeout
CIS_BFF_AUTHORIZATION_BASE_URL cis.bff.authorization-base-url
CIS_BFF_CALLBACK_URI cis.bff.callback-uri
CIS_BFF_CORS_ALLOWED_HEADERS cis.bff.cors.allowed-headers
CIS_BFF_CORS_ALLOWED_METHODS cis.bff.cors.allowed-methods
CIS_BFF_CORS_ALLOWED_ORIGIN_PATTERNS cis.bff.cors.allowed-origin-patterns
CIS_BFF_CORS_ALLOW_CREDENTIALS cis.bff.cors.allow-credentials
CIS_BFF_CORS_EXPOSED_HEADERS cis.bff.cors.exposed-headers
CIS_BFF_EXTERNAL_CLIENT_ID cis.bff.external-client.client-id
CIS_BFF_EXTERNAL_CLIENT_SCOPE cis.bff.external-client.default-scope
CIS_BFF_EXTERNAL_FRONTEND_URL cis.bff.external-frontend-url
CIS_BFF_EXTERNAL_SECRET cis.bff.external-client.client-secret
CIS_BFF_INTERNAL_CLIENT_ID cis.bff.internal-client.client-id
CIS_BFF_INTERNAL_CLIENT_SCOPE cis.bff.internal-client.default-scope
CIS_BFF_INTERNAL_FRONTEND_URL cis.bff.internal-frontend-url
CIS_BFF_INTERNAL_SECRET cis.bff.internal-client.client-secret
CIS_BFF_METADATA_CACHE_TTL cis.bff.metadata.cache-ttl
CIS_BFF_METADATA_CLIENT_ID cis.bff.metadata.client-id
CIS_BFF_METADATA_CLIENT_SECRET cis.bff.metadata.client-secret
CIS_BFF_METADATA_SECRET_FILE cis.bff.metadata.secret-file
CIS_BFF_METADATA_STALE_GRACE cis.bff.metadata.stale-grace
CIS_BFF_PUBLIC_CLIENT_ID cis.bff.public-client.client-id
CIS_BFF_PUBLIC_CLIENT_SCOPE cis.bff.public-client.default-scope
CIS_BFF_PUBLIC_REDIRECT_URI cis.bff.public-client.redirect-uri
CIS_BFF_REFRESH_SKEW cis.bff.redis.refresh-skew
CIS_BFF_REMEMBER_ME_TTL cis.bff.remember-me-ttl
CIS_BFF_REVOCATION_CHANNEL cis.bff.redis.revocation-channel
CIS_BFF_REVOKED_TOKEN_PREFIX cis.bff.redis.revoked-token-prefix
CIS_BFF_SESSION_KEY_PREFIX cis.bff.redis.session-key-prefix
CIS_BFF_SESSION_TTL cis.bff.redis.session-ttl
CIS_BFF_USER_SESSIONS_KEY_PREFIX cis.bff.redis.user-sessions-key-prefix
CIS_BFF_WORKFLOW_PATH_PATTERN cis.bff.routes.path-pattern
CIS_BFF_WORKFLOW_PREFIX_TO_STRIP cis.bff.routes.prefix-to-strip
CIS_BFF_WORKFLOW_ROUTE_ID cis.bff.routes.id
CIS_BFF_WORKFLOW_STRIP_PREFIX cis.bff.routes.strip-prefix
CIS_BFF_WORKFLOW_TIMEOUT cis.bff.routes.timeout
CIS_WORKFLOW_URL cis.bff.routes.target-url
COOKIE_CSRF_HEADER_NAME cis.bff.cookie.csrf-header-name
COOKIE_CSRF_NAME cis.bff.cookie.csrf-cookie-name
COOKIE_MAX_AGE cis.bff.cookie.max-age
COOKIE_PARTITIONED cis.bff.cookie.partitioned
COOKIE_SAME_SITE cis.bff.cookie.same-site
COOKIE_SECURE cis.bff.cookie.secure
COOKIE_SESSION_NAME cis.bff.cookie.session-cookie-name
MANAGEMENT_ENDPOINTS_WEB_EXPOSURE_INCLUDE management.endpoints.web.exposure.include
MANAGEMENT_HEALTH_SHOW_DETAILS management.endpoint.health.show-details
RATE_LIMIT_ENABLED cis.bff.rate-limit.enabled
RATE_LIMIT_KEY_PREFIX cis.bff.rate-limit.key-prefix
RATE_LIMIT_LOGIN_RPM cis.bff.rate-limit.login-requests-per-minute
RATE_LIMIT_RPM cis.bff.rate-limit.requests-per-minute
REDIS_HOST spring.data.redis.host
REDIS_PASSWORD spring.data.redis.password
REDIS_PORT spring.data.redis.port
REDIS_TIMEOUT spring.data.redis.timeout
SERVER_PORT server.port
VIRTUAL_THREADS_ENABLED spring.threads.virtual.enabled

Configuration maintenance rules

  • Browser callback/portal URLs are independent from the private auth back channel and token issuer.
  • Internal/external BFF client IDs and secrets must match their Oracle registrations. Metadata service credentials are separate.
  • BFF CORS is selected by environment and does not register OAuth redirects.
  • Redis password, database/address and key prefixes must agree among the actual writers/readers; similar variable names are not proof.
  • Signing-key encryption password/salt must remain compatible across nodes and existing encrypted rows.
  • Access-token lifetime must fit key grace; token-settings JSON must contain typed framework defaults.
  • Flyway histories are module-specific. Never edit applied versioned migrations to correct seed settings.
  • Do not paste .env credentials, private keys or real OAuth tokens into examples or troubleshooting output.

24. External-user passkeys: complete flow and rollout

Passkeys are optional for external CIS accounts. Internal users continue to authenticate with LDAP. Existing password grants, password login, OAuth authorization code/PKCE, refresh, BFF cookies and API bearer contracts remain available.

The Gradle version catalog owns spring-security-webauthn and spring-session-data-redis. Their versions come from the existing Spring Boot dependency platform; cis-auth uses the catalog aliases without independent version pins.

Fishbone overview

Read the spine from left to right. Branches identify the controls at each stage. Enrollment is a prerequisite for first use; later sign-ins use an existing credential.

External CIS passkey flow: browser start, enrollment, fresh challenge, assertion verification, CIS session and existing BFF callback

Open scalable SVG. The diagram describes source behavior, not a deployed browser capture.

What each branch guarantees

Branch What happens Why it matters
Enrollment The user proves the existing password, selects management, and creates a discoverable credential with local user verification. An unattended old session or a passkey-only session cannot silently add another credential.
Account and realm CIS resolves the opaque credential handle to a stable user ID and reloads current external account policies and roles. A previously enrolled key cannot bypass account disablement, onboarding or realm boundaries. Username changes do not transfer credential ownership.
Browser and origin The ceremony runs on the authentication host over HTTPS, with configured origins/RP ID, CSRF protection and a bounded JSON body. A credential signed for a different site, challenge or relying party cannot authenticate here. Biometric verification stays on the device.
Credential and challenge Oracle holds durable credential records; Redis holds expiring browser-bound ceremonies. GETDEL consumes a ceremony once. Oracle row locks serialize authentication/revocation. Replayed or cross-browser submissions fail, and concurrent revocation cannot be overwritten by a stale credential save.
OAuth continuation Only the original validated authorization request resumes, using the existing CIS principal, state, redirect URI and PKCE flow. Applications keep their existing OAuth/BFF contracts and do not need to receive WebAuthn assertions or biometric information.
Operations and recovery Operators enable the feature deliberately, keep password recovery available, and use credential revocation and existing session termination controls. Lost devices, compromised credentials, rollback and ordinary LDAP users have explicit paths.

Authentication decision flow

flowchart TD
    Start["Application starts existing OAuth authorization"] --> Realm{"External realm?"}
    Realm -->|No| LDAP["Existing internal LDAP login"]
    Realm -->|Yes| Flag{"Passkeys enabled?"}
    Flag -->|No| Password["Existing external password login"]
    Flag -->|Yes| Choice{"User chooses a method"}
    Choice -->|Password| Password
    Choice -->|Passkey| Options["Validate browser context and CSRF; issue challenge"]
    Password --> Manage{"Manage passkeys selected?"}
    Manage -->|No| OAuth["Existing authorization code and BFF callback"]
    Manage -->|Yes| Recent["Require recent password, own external account and no impersonation"]
    Recent --> Create["Create credential with required local user verification"]
    Create --> Register["Consume ceremony; verify attestation; store public credential"]
    Register --> Continue["User selects Continue"]
    Continue --> OAuth
    Options --> Device["Browser selects credential and requests local verification"]
    Device --> Assertion{"Valid signed assertion?"}
    Assertion -->|No or cancelled| Retry["Fresh challenge or password fallback"]
    Retry --> Choice
    Assertion -->|Yes| Account{"Current external account policies pass?"}
    Account -->|No| Reject["Reject sign-in; existing recovery or account process"]
    Account -->|Yes| Session["Rotate session and CSRF; save CIS principal and WebAuthn factor"]
    Session --> OAuth
    LDAP --> OAuth

Detailed enrollment flow

sequenceDiagram
    actor User
    participant App as Application / BFF
    participant Auth as cis-auth browser login
    participant Device as Browser / authenticator
    participant Redis as Shared Redis
    participant DB as Oracle
    User->>App: Start external sign-in
    App->>Auth: Existing authorization request (state, redirect, PKCE)
    Auth->>Auth: Validate client and external realm
    Auth->>Redis: Store auth-host session and pending login context
    Auth-->>User: Password form and manage-passkeys option
    User->>Auth: Password + management option + CSRF token
    Auth->>DB: Verify password, check current account policies and roles
    Auth->>Auth: Rotate session, bind browser revocation version
    Auth-->>User: Passkey management page
    User->>Auth: POST register/options + CSRF
    Auth->>Auth: External owner, current session, recent password, no impersonation
    Auth->>DB: Get/create opaque user handle
    Auth->>Redis: Store expiring registration options for browser and user
    Auth-->>Device: RP, user handle, random challenge, required UV/resident key
    Device->>User: Ask for local PIN / fingerprint / face verification
    Device->>Device: Create credential and keep private key
    Device->>Auth: POST register/verify + attestation + label + CSRF
    Auth->>Redis: Atomically consume registration ceremony
    Auth->>DB: Lock user handle, check ownership and credential quota
    Auth->>Auth: Verify challenge, origin, RP, algorithm, UP and UV
    Auth->>DB: Store credential public material
    Auth->>Auth: Publish lifecycle audit event
    Auth-->>User: Credential added, continue link
    User->>Auth: Continue captured authorization request
    Auth-->>App: Existing OAuth code / callback flow

The enrollment request never accepts an authoritative user ID from the browser. The current authenticated CIS principal determines ownership. Options expose the account's username for the authenticator's account picker, while durable ownership uses the stable CIS ID and an opaque handle. No anonymous registration or internal enrollment endpoint is provided.

Detailed passkey sign-in flow

sequenceDiagram
    actor User
    participant App as Application / BFF
    participant Auth as cis-auth
    participant Device as Browser / authenticator
    participant Redis as Shared Redis
    participant DB as Oracle
    User->>App: Start external sign-in
    App->>Auth: Existing authorization request
    Auth->>Auth: Validate enabled client, realm, redirect and PKCE parameters
    Auth->>Redis: Capture browser login context
    Auth-->>User: Existing login page with Use a passkey
    User->>Auth: POST login/options + login_challenge + CSRF
    Auth->>Redis: Store random, expiring assertion challenge bound to browser/context
    Auth-->>Device: Request options (RP ID, challenge, required UV)
    Device->>User: Choose a credential and verify locally
    Device->>Device: Sign authenticator data and client-data hash
    Device->>Auth: POST login/verify + assertion + CSRF
    Auth->>Redis: Atomically consume the pending ceremony
    Auth->>DB: Lock active credential and resolve its stable owner
    Auth->>Auth: Verify userHandle, signature, challenge, origin, RP, UP and UV
    Auth->>Auth: Check counter and backup flags
    Auth->>DB: Reload external account status, policies and current roles
    Auth->>DB: Update credential usage, audit successful sign-in
    Auth->>Auth: Revalidate/consume captured OAuth context
    Auth->>Redis: Rotate session ID and CSRF, save CIS principal with WebAuthn factor
    Auth-->>Device: Same-origin captured authorization continuation
    Device->>Auth: Navigate to original authorization request
    Auth-->>App: Existing authorization code and state
    App->>Auth: Existing code exchange with PKCE verifier
    Auth-->>App: Existing tokens
    App-->>User: Existing application session

Discoverable login sends no username lookup request. Credential selection happens on the device, then CIS checks that the returned user handle owns the selected credential. A successful login has the WebAuthn factor, not the password factor. Password and WebAuthn timestamps both satisfy OAuth max_age; only a recent password factor permits credential changes.

Failure, recovery and revocation paths

Situation Server behavior User/operator path
Unsupported browser or public HTTP host Passkey controls cannot start a ceremony. Use the existing password flow; use HTTPS, or the exact HTTP localhost development exception.
Device prompt cancelled or timed out No successful authentication is installed. Retry to obtain a fresh challenge, or use the password.
Expired, replaced or already consumed ceremony Verification fails; a consumed challenge cannot be reused. Request new options. Multiple attempts in the same context replace the pending ceremony.
Wrong origin, RP ID, signature, challenge, UP/UV or owner handle Reject the assertion with a uniform error. Restart sign-in; investigate repeated failures through normal security monitoring.
Internal realm or internal account Reject passkey enrollment/login for that realm/account. Continue LDAP authentication.
Disabled, locked, unapproved or reset/expiry-blocked external account Current account policies reject sign-in; Oracle credential usage changes roll back. Resolve the account condition through the existing account/password process.
Stale password, passkey-only or impersonated management session Reject enrollment/revocation. Sign out and start an external password login with the management option.
Another user's credential ID is submitted for revocation Ownership check rejects it. Manage only credentials listed for the current user.
Lost device Another enrolled passkey or password remains usable. Log in with the fallback and revoke the lost credential.
Credential compromise Revocation retains a tombstone and blocks future use. Also invoke existing session termination if active sessions/tokens may be compromised.
Redis unavailable Ceremony/session operations fail closed; no substitute local challenge cache is used. Restore Redis; password browser sessions also depend on shared Redis while enabled.
Oracle unavailable Credential/account operations fail; no successful session is installed. Restore database service and retry.
Non-increasing counter on a single-device credential Reject when a nonzero counter fails to increase. Investigate or recover using another credential/password.
Synced credential has a zero counter Fresh signed ceremonies can succeed with zero counters. This is expected for supported synced passkeys; replay protection still comes from one-use challenges.
Feature rolled back Passkey endpoints and shared-session configuration are removed by the flag; credential records remain. Restart existing password login; preserve Oracle data for later re-enablement.

Account recovery is intentionally the existing recovery process. This implementation adds audit lifecycle events, not automatic email notifications or a separate recovery-code system.

State ownership and trust boundaries

Component Owns Does not own
Device / passkey provider Private key, local biometric/PIN verification and any provider-managed synchronization CIS roles, account status or OAuth authorization decisions
Auth-host browser session CIS principal, authentication factor/time, captured client/realm/redirect, browser revocation version and CSRF state Authenticator private key or biometric templates
Oracle Opaque identity handles, public credential material, counters/backup flags, usage metadata, revocation tombstones, users/roles/policies and existing OAuth records Pending WebAuthn challenge expiry/consumption
Redis Shared auth-host sessions, expiring one-use ceremonies, existing rate limits and revocation state Permanent credential ownership
Application / BFF Existing state/PKCE verification, OAuth callback, tokens and application session handling Direct validation of WebAuthn signatures or storage of biometric data

Registration and authentication cryptography use the Spring WebAuthn4J relying-party implementation. CIS adds realm/account policy, stable identity mapping, challenge/session binding, ownership, quota, current-counter handling and existing OAuth continuation. Authentication and revocation lock the credential row; registration locks the stable user-handle row to enforce the active-key limit under concurrency.

User flow

  1. Start sign-in from the application as usual.
  2. On the external authentication page, select Manage passkeys after password sign-in, then sign in with the existing password.
  3. Add a named passkey on the authentication host, complete the device prompt, then select Continue to your application.
  4. On subsequent sign-ins, select Use a passkey. The browser offers registered discoverable credentials and local device verification. Password login remains available.
  5. To list or revoke a credential, repeat the password sign-in with the management option. Changes require a password authentication within five minutes by default. A passkey-only session cannot enroll another passkey.

An account can hold up to ten active credentials by default. Register a backup device or synced passkey. CIS stores public credential material, not biometrics or authenticator private keys. Account onboarding, forced password reset, password expiry, disabled/locked status and external realm eligibility are checked again before passkey sign-in succeeds.

Revocation blocks future use of that credential. It does not terminate existing application sessions; use the existing session termination controls when compromise is suspected. Existing password recovery remains the fallback. Impersonated sessions cannot manage passkeys.

Deployment

The feature is off by default. Configure the target cis-auth/.env.<environment> file, which is already consumed by local and deployment Compose env_file entries:

CIS_AUTH_PASSKEYS_ENABLED=true
CIS_AUTH_PASSKEYS_RP_ID=auth.example.org
CIS_AUTH_PASSKEYS_ALLOWED_ORIGINS=https://auth.example.org
CIS_AUTH_PASSKEYS_CHALLENGE_TTL=PT3M
CIS_AUTH_PASSKEYS_RECENT_AUTHENTICATION=PT5M
CIS_AUTH_PASSKEYS_MAX_CREDENTIALS=10

Replace example values with the actual stable public authentication hostname. Origins have a scheme and optional port, with no path or trailing slash. Wildcards are rejected. Use separate RP IDs for UAT and production. Changing an RP ID later generally requires users to enroll again. Public hosts require HTTPS. The only HTTP exception is exact localhost with RP ID localhost, following the WebAuthn localhost secure-context exception.

For local IDE testing on port 8085, set these values in cis-auth/.env.dev, restart cis-auth, then begin a new external login from the application:

CIS_AUTH_PASSKEYS_ENABLED=true
CIS_AUTH_PASSKEYS_RP_ID=localhost
CIS_AUTH_PASSKEYS_ALLOWED_ORIGINS=http://localhost:8085

The external login page then displays Use a passkey and Manage passkeys after password sign-in. Enroll first using the password and management option. Restarting replaces the auth-host session setup, so do not reuse an old login_challenge URL. Keep localhost consistent; IP addresses and LAN hostnames do not receive this HTTP exception. The checked-in dev example stays disabled until explicitly enabled.

Apply auth migration V8__external_passkeys.sql through the auth Flyway runner (FLYWAY_SCHEMA_HISTORY_AUTH) before enabling. It adds AUTH_PASSKEY_USER and AUTH_PASSKEY_CREDENTIAL; no existing user records or applied migrations are modified. Credential JSON is a CLOB, credential IDs are indexed by SHA-256, and revoked records are retained.

When enabled, auth-host HTTP sessions are stored in Redis under cis:auth:http-session, with a 30-minute inactivity timeout and the host-only CIS_AUTH_SESSION cookie (Secure, HttpOnly, SameSite=Lax). Only the validated HTTP localhost development origin omits Secure so its cookie can round-trip over local HTTP; public HTTPS deployments retain it. Existing auth-host sessions need a fresh login at the switch. BFF session storage is unchanged. Replicas must use the same Redis and compatible session-serialized classes; treat an incompatible rolling upgrade as requiring reauthentication.

Ceremonies use a separate cis:auth:passkeys namespace and atomic Redis GETDEL consumption. Redis 6.2 or newer is required. Redis must be private, authenticated, monitored and shared by all auth replicas. Redis failures fail authentication closed. Protect transport according to the existing Redis deployment policy. Rolling back the feature flag removes passkey access without deleting credential data.

The existing direct-auth Redis request limiter also covers passkey endpoints. JSON bodies are limited to 64 KiB, CSRF protection is required on every mutation, and challenges expire server-side. Repeated options requests replace the pending ceremony for that browser/context. Challenges are bound to the browser, purpose and captured OAuth client/realm; management additionally binds to the current user. User verification is required at registration and authentication.

PASSKEY_REGISTERED, PASSKEY_LOGIN and PASSKEY_REVOKED use the existing audit event pipeline. Route lifecycle events to operational monitoring as appropriate. This feature does not introduce an email delivery service or a new account recovery mechanism.

HTTP surface

All endpoints are on the authentication host, not the resource API or an Angular origin.

Endpoint Access
POST /passkeys/login/options?login_challenge=... External browser authorization context + CSRF
POST /passkeys/login/verify?login_challenge=... Same context + one-use challenge + signed assertion + CSRF
GET /passkeys Current external browser session
GET /passkeys/credentials Own credentials in a current external browser session
POST /passkeys/register/options Recent password-authenticated external browser session + CSRF
POST /passkeys/register/verify Same session, stored registration challenge and CSRF
POST /passkeys/revoke Recent password-authenticated external owner + CSRF

Login uses Spring Security's WebAuthn4J relying-party verifier, then installs the existing CIS principal with FACTOR_WEBAUTHN. It rotates the session ID and CSRF state, binds the existing browser revocation version and resumes only the captured authorization request. OAuth max_age recognizes both password and WebAuthn authentication times. Enrollment always requires the password factor.

Validation

Run from the repository root:

./gradlew.bat :cis-auth:test --tests '*Passkey*Test' --tests '*AuthorizationCodeSecurityIntegrationTest'
./gradlew.bat :cis-auth:test :cis-bff:test

Oracle and Redis integration tests require Docker. The software authenticator tests generate real ES256 signatures and none attestation. Browser-chain tests cover registration, credential listing/revocation, OAuth continuation, session fixation, CSRF, realm isolation and replay. Container tests exercise Oracle CLOB persistence/rollback/revocation and Redis session serialization, challenge expiry and atomic consumption.

Before enabling in UAT, perform an HTTPS browser check using Windows Hello, a mobile synced passkey and an alternate browser/device. Verify password fallback, internal LDAP login, application callback, refresh, logout, revoked credentials and account disablement. Automated server tests do not certify the physical device UX or the deployed proxy/cookie/domain configuration.