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.
- Request
- ApplicationSpring Security puts the logged-in user in the
SecurityContextThe application's own authentication - ContexaThe authentication bridge makes three stampsAuthentication, authorization and delegation stamps + a coverage report, kept in the request attributes
ctxa.bridge.* - Facts of the decision promptLogin method, MFA, authorities, delegated scope, and where each came from
What the application must do
- 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. - Put the logged-in user in the
SecurityContextas an authenticatedAuthentication. The bridge makes stamps only when an authenticated (non-anonymous)Authenticationis present. Otherwise it makes nothing, and protected methods (@Protectable) are refused in theSHADOWandENFORCEmodes (ENFORCEis the default); underDISABLEDandOBSERVEthey are not refused. - Tell it about MFA and the login method. Put a value such as
mfaVerifiedon theAuthentication's details or principal; with OAuth2 or OIDC the token'samrclaim is enough (Telling it about MFA). - 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).
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
@Protectablemethods 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 (afterSecurityContextHolderFilterfor session flows, afterBearerTokenAuthenticationFilterfor 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
| Stamp | Where it reads (order) | When several places answer |
|---|---|---|
| Authentication stamp (who, and how they logged in) | SecurityContext → session → request attributes → headers | The first result with a user ID is used. |
| Authorization stamp (what they may do) | All of SecurityContext, session, request attributes and headers | All 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 account | The 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.
- The name you give. With
contexa.bridge.authentication.session.attribute(for request attributescontexa.bridge.authentication.request-attributes.attribute) that attribute is looked at first and used at once when it holds a user ID. - Candidate names. For the session
currentUser,authenticatedUser,sessionUser,userSession,principal,user,securityUser,authenticatedPrincipal; for request attributescurrentUser,authenticatedUser,requestUser,principal,user,authenticatedPrincipal,authUser. - 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 has | Score |
|---|---|
| A user ID | 10 (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);
| Stamp | Request attribute names |
|---|---|
| Authentication | ctxa.auth.principalId (required), displayName, authenticated, authorities, tenantId, organizationId, orgId, type, assurance, mfaCompleted, time |
| Authorization | ctxa.authz.effect, privileged, policyId, policyVersion, scopeTags, roles, authorities |
| Delegation | ctxa.delegation.enabled, agentId, objectiveId, objectiveFamily, objectiveSummary, allowedOperations, allowedResources, approvalRequired, privilegedExportAllowed, containmentOnly, expiresAt |
- When
ctxa.auth.authenticatedis 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.
- A value the application gives comes first. MFA completion is read from
mfa·mfaVerified·mfaCompleted·secondFactorVerified, the login method fromauthenticationType·authMethod·loginMethodand others. - Otherwise it is derived from the
amrclaim (RFC 8176), with the source markedDERIVED_FROM_AMR.
amr value | Login method |
|---|---|
pwd | PASSWORD |
otp, sms, tel | ONE_TIME_CODE |
pop, hwk, swk | PASSKEY |
face, fpt, iris, retina, vbm | BIOMETRIC |
- MFA rule: MFA is complete when
amrholdsmfaor two or more different methods. Example:["pwd","otp"]→ MFA complete, methodPASSWORD+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·acrhas a value (it is not derived fromamr). - From the session, request attributes and headers
amris 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 theSecurityContext. Only when Contexa owns login (CONTEXA_OWNED) does it fill theSecurityContextand save it to the session. - Without
@EnableAISecurityit throwsIllegalStateException; 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.
| Level | Score | Meaning |
|---|---|---|
NONE | 0 | No authenticated user found |
AUTHENTICATION_ONLY | 40 | Only who the user is |
AUTHORIZATION_CONTEXT | 75 (minus for each missing part) | Authorities and the authorization result too |
DELEGATION_CONTEXT | 90 | Delegation 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
| Setting | Default | Meaning | When to change |
|---|---|---|---|
contexa.bridge.enabled | true | Turns the bridge filter on (when off, only direct handoff works) | To turn the bridge off (fewer decision facts) |
contexa.bridge.ownership | HOST_OWNED (CONTEXA_OWNED with mode=FULL) | Who owns login. When set, it wins over the annotation | CONTEXA_OWNED when Contexa should own sign-in |
contexa.bridge.populate-security-context | true | Under 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-name | None | The 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-discover | true | Scan session attributes beyond the candidate names | false to look only at the given and candidate names |
contexa.bridge.authentication.prefer-security-context | true | With false the authentication stamp is made from the user object of the session, request attributes or headers instead of the SecurityContext | To read session or header values first |
contexa.bridge.authentication.security-context.mfa-keys | mfa, mfaVerified, mfaCompleted, secondFactorVerified | Names to look for the MFA completion flag | When your app keeps MFA completion under another name |
contexa.bridge.authentication.security-context.amr-keys | amr | Name of the RFC 8176 values used to derive MFA and the login method | When tokens carry amr under another claim |
contexa.bridge.authentication.session.attribute | none | The session attribute holding the user object (otherwise candidate names, then automatic discovery) | To name the session's user object |
contexa.bridge.authentication.headers.enabled | false | Read gateway headers | When a gateway passes the user in headers (with trusted proxies) |
contexa.bridge.network.trusted-proxies | none | Proxies whose headers and X-Forwarded-For are trusted | Always with headers |
contexa.bridge.network.trusted-proxy-validation-enabled | true | The trusted proxy check. When off, header reading is always refused and the client IP is taken the legacy way, trusting X-Forwarded-For from anyone | Leave it on (turning it off lets clients forge their IP) |
contexa.bridge.step-up.reauthentication-url | none | Under 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 it | When your application can re-authenticate users itself (The step-up under HOST_OWNED) |
contexa.bridge.sync.synthetic-email-domain | shadow.contexa.local | The email domain given to a mirror user without an email | To match your company's email rules |
contexa.bridge.sync.enabled | true | User mirror synchronization | To turn the user mirror sync off |
Every contexa.bridge.* setting (311) is in the Settings Index.
Extension points
| Extension point | When to use it |
|---|---|
AuthBridge | To take the user from the request your own way. Declaring one bean replaces the default session, request attribute and header bridges. |
AuthenticationStampResolver · AuthorizationStampResolver · DelegationStampResolver | To add or replace where stamps are made (order with @Order) |
ContexaAuthBridgeHandler | To replace how direct handoff is handled |
BridgeUserMirrorSyncService | To keep the user mirror differently |
AgentClientDirectory | To tell which clients and accounts are approved agents (Agent security) |