contexa-common

Connecting Your Existing Login (Authentication Bridge)

How Contexa reads, on every request, the login, authorization and delegation information your application already has, and uses it as facts of a decision. It covers what the application must do, where and in which order Contexa reads, how to tell it about MFA, gateway headers, direct handoff and extension points.

At a glance

When Contexa is on in its default mode (@EnableAISecurity, the application owns login: HOST_OWNED), your Spring Security keeps handling login. On every request Contexa reads the result through the authentication bridge (BridgeResolutionFilter) and makes three stamps, which become facts of the decision prompt.

From login information to decision factsThe bridge only reads. It does not change the application's login, session or response.
  1. Request
  2. ApplicationSpring Security puts the logged-in user in the SecurityContextThe application's own authentication
  3. ContexaThe authentication bridge makes three stampsAuthentication, authorization and delegation stamps + a coverage report, kept in the request attributes ctxa.bridge.*
  4. Facts of the decision promptLogin method, MFA, authorities, delegated scope, and where each came from

What the application must do

  1. Have Spring Security and your own SecurityFilterChain. Without your chain, Spring Boot's default security (every request authenticated) applies, and Contexa logs a warning at startup to tell you. With no users of your own either, the start is refused.
  2. Put the logged-in user in the SecurityContext as an authenticated Authentication. The bridge makes stamps only when an authenticated (non-anonymous) Authentication is present. Otherwise it makes nothing, and protected methods (@Protectable) are refused in the SHADOW and ENFORCE modes (ENFORCE is the default); under DISABLED and OBSERVE they are not refused.
  3. Tell it about MFA and the login method. Put a value such as mfaVerified on the Authentication's details or principal; with OAuth2 or OIDC the token's amr claim is enough (Telling it about MFA).
  4. If a session object holds roles or delegation information, just match the key names. The bridge scans session attributes for the user object (Finding the user in the session or request attributes).
A legacy application without Spring Security. Add Spring Security, declare a chain that keeps your existing access rules (for example anyRequest().permitAll()), and in a filter of that chain put the user your existing login verified into the SecurityContext. Calling direct handoff alone records evidence for that request only and does not fill the SecurityContext, so it is not enough for @Protectable.

What the bridge does not do

  • When the application owns login (HOST_OWNED) it does not interfere with the application's authentication, authorization or session. It saves nothing to the session and writes no headers.
  • When your application owns login, the bridge filter is registered as a servlet filter ordered right after your Spring Security chain (the chain's order + 1, before Contexa's enforcement filters), so it runs after your Spring Security chain has finished. Contexa's enforcement filters, controllers and @Protectable methods can read the stamps, but URL authorization inside your chain runs before they exist (Spring Boot's filter ordering). When Contexa owns login (CONTEXA_OWNED) it sits in Contexa's chain (after SecurityContextHolderFilter for session flows, after BearerTokenAuthenticationFilter for token flows).
  • The exception: the user mirror writes user rows to the Contexa database even when the application owns login.

Where and in which order it reads

StampWhere it reads (order)When several places answer
Authentication stamp
(who, and how they logged in)
SecurityContext → session → request attributes → headersThe first result with a user ID is used.
Authorization stamp
(what they may do)
All of SecurityContext, session, request attributes and headersAll are merged. If allow (ALLOW) and deny (DENY) both appear, it is deny. If none answers, it is derived from the authentication stamp's authorities.
Delegation stamp
(who delegated what)
Access token → session → request attributes → headers → the agent's own accountThe first result is used.

@EnableAISecurity(authObjectLocation = ...) only changes the order in which the authentication stamp tries the session, request attributes and headers (it turns none of them off). Each stamp records its source (SECURITY_CONTEXT, SESSION, REQUEST_ATTRIBUTE, HEADER, EXPLICIT_HANDOFF and so on), so the prompt carries where each fact came from.

Finding the user in the session or request attributes

When no user is found in the SecurityContext, the bridge looks for a user object in the session, then in the request attributes, in three steps.

  1. The name you give. With contexa.bridge.authentication.session.attribute (for request attributes contexa.bridge.authentication.request-attributes.attribute) that attribute is looked at first and used at once when it holds a user ID.
  2. Candidate names. For the session currentUser, authenticatedUser, sessionUser, userSession, principal, user, securityUser, authenticatedPrincipal; for request attributes currentUser, authenticatedUser, requestUser, principal, user, authenticatedPrincipal, authUser.
  3. Auto-discovery. With auto-discover (on by default) every other attribute is scanned too.

In steps 2 and 3 only objects with a user ID (userId, username, id, loginId, email) are candidates, and the one with the highest score below is used. When the session holds several objects that look like users, it is safer to give the name of step 1 or object-type-name (the class's full or simple name).

What the object hasScore
A user ID10 (without it, not a candidate)
The class named by object-type-name+8
Authorities (roles, authorities, permissions, scopes)+4
A display name, a login method+2 each
Assurance level, MFA flag, authentication time, extra attributes (department, tenantId, ...)+1 each

Putting values into request attributes one by one

Instead of a user object you can put the values one by one into request attributes. The authentication stamp reads these names when no user object is found in the request attributes; the authorization and delegation stamps always read them. Put them in from one of your application's filters.

request.setAttribute("ctxa.auth.principalId", user.getId());
request.setAttribute("ctxa.auth.authenticated", true);
request.setAttribute("ctxa.auth.authorities", "ROLE_USER,ROLE_FINANCE");
request.setAttribute("ctxa.auth.mfaCompleted", true);
StampRequest attribute names
Authenticationctxa.auth.principalId (required), displayName, authenticated, authorities, tenantId, organizationId, orgId, type, assurance, mfaCompleted, time
Authorizationctxa.authz.effect, privileged, policyId, policyVersion, scopeTags, roles, authorities
Delegationctxa.delegation.enabled, agentId, objectiveId, objectiveFamily, objectiveSummary, allowedOperations, allowedResources, approvalRequired, privilegedExportAllowed, containmentOnly, expiresAt
  • When ctxa.auth.authenticated is present and not true, the request has no user.
  • Several values, such as authorities, go in as one comma-separated text.
  • The names can be changed by settings (for example contexa.bridge.authentication.request-attributes.flat-principal-id). All of them are in the Settings Index.

Telling it about MFA and the login method

From the SecurityContext's Authentication the details are read first, then the principal. If the object has a claims or attributes map (JWT claims, OAuth2 user attributes), that map is searched.

  1. A value the application gives comes first. MFA completion is read from mfa · mfaVerified · mfaCompleted · secondFactorVerified, the login method from authenticationType · authMethod · loginMethod and others.
  2. Otherwise it is derived from the amr claim (RFC 8176), with the source marked DERIVED_FROM_AMR.
amr valueLogin method
pwdPASSWORD
otp, sms, telONE_TIME_CODE
pop, hwk, swkPASSKEY
face, fpt, iris, retina, vbmBIOMETRIC
  • MFA rule: MFA is complete when amr holds mfa or two or more different methods. Example: ["pwd","otp"] → MFA complete, method PASSWORD+ONE_TIME_CODE. ["otp","sms"] → one method, so not MFA.
  • Authentication time is read from authenticationTime · authenticatedAt · loginTime · auth_time. The token issue time (iat) is deliberately not used because it changes when a token is reissued.
  • Assurance level is used only when authenticationAssurance · authLevel · loa · acr has a value (it is not derived from amr).
  • From the session, request attributes and headers amr is not interpreted; only MFA flags are read (mfaVerified, ctxa.auth.mfaCompleted, X-Contexa-Mfa-Completed).

Passing it through gateway headers

If an API gateway attaches user information as X-Contexa-* headers, turn header reading on. To prevent forgery it is off by default, and even when on, headers are trusted only when all of the following hold.

  • The request came from a trusted proxy (contexa.bridge.network.trusted-proxies, IPs and CIDRs). With an empty list, or with the trusted proxy check (contexa.bridge.network.trusted-proxy-validation-enabled) off, headers are always refused.
  • The header's user ID is the user the application authenticated (SecurityContext), and the tenant and organization values match.
contexa:
  bridge:
    network:
      trusted-proxies: [10.0.0.0/8]
    authentication:
      headers:
        enabled: true      # X-Contexa-Principal-Id, X-Contexa-Mfa-Completed, ...
    authorization:
      headers:
        enabled: true      # X-Contexa-Authz-Effect, X-Contexa-Authz-Roles, ...
    delegation:
      headers:
        enabled: true      # X-Contexa-Delegated, X-Contexa-Agent-Id, ...

Contexa only reads these headers; it never writes them to responses.

Direct handoff

Your login code can tell Contexa about the user directly.

ContexaAuthBridge.handoff(request, response,
        ContexaAuthHandoff.of(user, authorities, Map.of("department", "R&D"))
                .withAuthenticationType("PASSWORD+ONE_TIME_CODE")
                .withMfaVerified(true));
  • It records authentication evidence for that request (source EXPLICIT_HANDOFF). If the bridge filter finds a different user in the same request, a conflict is marked.
  • When the application owns login (HOST_OWNED) it does not fill the SecurityContext. Only when Contexa owns login (CONTEXA_OWNED) does it fill the SecurityContext and save it to the session.
  • Without @EnableAISecurity it throws IllegalStateException; if no user ID can be determined, IllegalArgumentException.

Coverage: how much the bridge knew

For every request the bridge computes how complete its information is and puts it in the prompt (bridge <level>), so the model knows what it does not know.

LevelScoreMeaning
NONE0No authenticated user found
AUTHENTICATION_ONLY40Only who the user is
AUTHORIZATION_CONTEXT75 (minus for each missing part)Authorities and the authorization result too
DELEGATION_CONTEXT90Delegation information too

User mirror

The bridge keeps a mirror row for an externally logged-in user in the Contexa database's user table, so the admin console and policies can refer to that user. The key is brg_ + SHA-256 (authentication source, organization, user ID); the row has a random password and cannot be used to log in directly. When the same user comes again within 60 seconds (contexa.bridge.sync.min-refresh-interval-seconds) and nothing changed, the row is not written again. The same value is also how long the result of that check is remembered: for an application that owns login (HOST_OWNED), a request of the same user with the same facts (authentication source, name, authorities, attributes, client IP and the rest the check compares) is answered from memory, without reading the Contexa database, until that time has passed. With a value of 0 or less nothing is remembered. The email is read from the authentication attributes email, mail or userEmail; without one it is <key>@shadow.contexa.local (contexa.bridge.sync.synthetic-email-domain). To turn it off, set contexa.bridge.sync.enabled=false.

A value from your application that is longer than its column (a department that is a long directory name, a phone number with an extension, a long avatar URL) is cut to the column, so one long value never fails the copy. An address longer than 255 characters is replaced by the made-up one. A user ID longer than 255 characters gets no copy (one warning is logged); the user is still decided on and enforced, but has no factor of its own for the step-up.

Settings you will change most

SettingDefaultMeaningWhen to change
contexa.bridge.enabledtrueTurns the bridge filter on (when off, only direct handoff works)To turn the bridge off (fewer decision facts)
contexa.bridge.ownershipHOST_OWNED (CONTEXA_OWNED with mode=FULL)Who owns login. When set, it wins over the annotationCONTEXA_OWNED when Contexa should own sign-in
contexa.bridge.populate-security-contexttrueUnder CONTEXA_OWNED, fills an empty SecurityContext with the user the bridge found (never under HOST_OWNED)false when Contexa owns sign-in but your application fills the SecurityContext
contexa.bridge.authentication.session.object-type-nameNoneThe class name of the session's user object (+8 score)When the session holds several objects that look like users
contexa.bridge.authentication.session.auto-discovertrueScan session attributes beyond the candidate namesfalse to look only at the given and candidate names
contexa.bridge.authentication.prefer-security-contexttrueWith false the authentication stamp is made from the user object of the session, request attributes or headers instead of the SecurityContextTo read session or header values first
contexa.bridge.authentication.security-context.mfa-keysmfa, mfaVerified, mfaCompleted, secondFactorVerifiedNames to look for the MFA completion flagWhen your app keeps MFA completion under another name
contexa.bridge.authentication.security-context.amr-keysamrName of the RFC 8176 values used to derive MFA and the login methodWhen tokens carry amr under another claim
contexa.bridge.authentication.session.attributenoneThe session attribute holding the user object (otherwise candidate names, then automatic discovery)To name the session's user object
contexa.bridge.authentication.headers.enabledfalseRead gateway headersWhen a gateway passes the user in headers (with trusted proxies)
contexa.bridge.network.trusted-proxiesnoneProxies whose headers and X-Forwarded-For are trustedAlways with headers
contexa.bridge.network.trusted-proxy-validation-enabledtrueThe trusted proxy check. When off, header reading is always refused and the client IP is taken the legacy way, trusting X-Forwarded-For from anyoneLeave it on (turning it off lets clients forge their IP)
contexa.bridge.step-up.reauthentication-urlnoneUnder HOST_OWNED, where the step-up page sends the user to re-authenticate with your application's own MFA or identity provider (for example an OIDC authorization request with prompt=login or max_age=0). Not offered when empty. A completed MFA in the authentication stamp, newer than the CHALLENGE, then releases itWhen your application can re-authenticate users itself (The step-up under HOST_OWNED)
contexa.bridge.sync.synthetic-email-domainshadow.contexa.localThe email domain given to a mirror user without an emailTo match your company's email rules
contexa.bridge.sync.enabledtrueUser mirror synchronizationTo turn the user mirror sync off

Every contexa.bridge.* setting (311) is in the Settings Index.

Extension points

Extension pointWhen to use it
AuthBridgeTo take the user from the request your own way. Declaring one bean replaces the default session, request attribute and header bridges.
AuthenticationStampResolver · AuthorizationStampResolver · DelegationStampResolverTo add or replace where stamps are made (order with @Order)
ContexaAuthBridgeHandlerTo replace how direct handoff is handled
BridgeUserMirrorSyncServiceTo keep the user mirror differently
AgentClientDirectoryTo tell which clients and accounts are approved agents (Agent security)