Skip to content
fabricators docs
On this page

Integrate browser and Capacitor sessions

Configure login, protected requests, atomic refresh, revocation and native associations.

Status: backend integration supplied in 0.7.0, with the session-policy and login-information corrections below supplied in 0.7.1. Version 0.7.0 still invalidates all sessions on every factor mutation and does not expose these new APIs. The backend lifecycle is tested over HTTP and real databases. Physical devices, Capacitor bridges and frontend acceptance remain product integration work.

One lifecycle, two transports

Version 0.15.0 adds explicit fresh OIDC primary reauthentication and opt-in local factor renewal from an existing session. See the reauthentication contract. These primitives do not replace the browser/native session or revoke other families. The product still supplies live admission and trusted client/session binding; no new OIDC or biometrics frontend is provided by the package.

Profile Login proof Session transport
Browser/PWA WebAuthn at an explicit HTTPS origin, or a verified host primary/MFA flow Opaque access and refresh credentials in Secure/HttpOnly host-only cookies; bound CSRF proof
Capacitor iOS AuthenticationServices passkey bridge and approved app/domain association Opaque bearer access token, rotating refresh token and protected binding in native secure storage
Capacitor Android Credential Manager bridge, approved package/signing certificate and Digital Asset Links Same native transport and server lifecycle

The adapter does not issue JWTs. Every protected request checks authoritative session/family state, both account epochs and the current product directory, roles and policy. There is no stale authorization cache. The older IUserSessionStore/IAccessTokenIssuer ports remain a separate legacy stack; their counter and sessions are not automatically migrated or revoked by this adapter.

Face ID, Touch ID or a device PIN can unlock a passkey. The backend receives verified cryptographic evidence, never biometrics or proof of the selected local unlock method. A local biometric prompt unlocking a stored refresh credential is not a new authentication proof or an MFA upgrade.

Required host composition

Register AddStrongAuthentication, AddNativePasskeys, AddStrongAuthenticationStore, AddInteractiveSessions and AddFoundationSessionHttp. Configure the same authority and application ID in ceremony and session options. Configure explicit browser HTTPS origins and native clients with their approved IDs, signing fingerprints and WebView origins. No identity provider or permissive user directory is supplied by default.

The host must implement IStrongAuthenticationAuthority and ISessionPrincipalSource. Resolve the actor from verified server identity or a protected pending-login context, never from an anonymous user ID or biometric flag. Resolve current enabled status, roles and required methods/assurance on login, refresh and protected requests. Password, OIDC and magic-link verification remain host integrations. CompletePrimaryLoginAsync exchanges a verified, fresh host actor for a one-use completion proof; it cannot bypass required MFA or make an old upstream login fresh again.

Apply all six EF configurations: AuthenticationAccount, AuthenticationChallenge, AuthenticationCredential, AuthenticationAudit, InteractiveSession and InteractiveSessionToken. Their names end in Configuration. Products own their context, schema and migrations. The account mapping adds SessionVersion with a zero default; legacy protected account payloads deserialize it as zero. Sessions and token hashes are new tables. Keep existing rows, keys and encrypted payloads. The acceptance suite generates the populated-schema upgrade through EF's model differ/SQL generator and verifies transactional DDL rollback on SQLite and PostgreSQL. No product migration history is supplied or rewritten by foundation.

Persist and protect the Data Protection key ring across restarts and replicas; use shared authoritative database state and consistent authority, RP, application and client configuration. The adapter has no production in-memory fallback.

The HTTP pipeline must call UseRouting, UseCors, UseAuthentication and UseAuthorization in that order. Select the FoundationSession authentication scheme as the default for product endpoints or name it explicitly in their policy. Call MapFoundationSessions and optionally MapFoundationAppAssociations. Ceremony endpoints remain product-owned and must use the same trusted client binding and browser-write validation as the session endpoints. The HTTP fixtures exercise this composition; they are not a permissive production authority.

HTTP flow

The default session route prefix is /auth/session. All requests require HTTPS. Successful responses and authentication errors use Cache-Control: no-store.

Route Contract
GET /browser/context Sets protected binding cookie; returns csrfToken and requestId
POST /native/{clientId}/context Returns protected binding and requestId for a configured client
POST /browser/login or /native/login Body: userId, proof, requestId; consumes the verified one-use completion proof atomically with session creation
POST /browser/refresh Body: requestId; uses the refresh cookie
POST /native/refresh Body: refreshToken, requestId; uses the protected native binding
POST /browser/logout or /native/logout Revokes the bound family; native body: refreshToken; works after access expiry
POST /browser/revoke-all or /native/revoke-all Requires active access; revokes the subject's families and outstanding completion proofs
POST /browser/revoke-others or /native/revoke-others Requires active access and management policy; retains the authenticated caller's family and credentials, revokes all other families for the same authority/subject and clears outstanding completion proofs
POST /browser/revoke/{sessionId} or /native/revoke/{sessionId} Requires active access; only the owner's session can be revoked
GET /me Requires the FoundationSession scheme; returns bounded session metadata

Browser responses set access/refresh cookies without returning credentials in JSON. Send credentials with browser requests and X-Session-CSRF with the returned csrfToken on writes. A successful login rotates the binding and CSRF proof: use the new value. The CSRF proof is independent of user claims and remains usable for refresh after access expiry. This is a dedicated synchronizer-token protocol, not an ASP.NET IAntiforgery token or the legacy X-XSRF-TOKEN convention. Authenticated unsafe requests using this scheme enforce it automatically; anonymous product write routes must enforce their own admission/CSRF policy. Do not globally disable another security gate to adopt the session adapter.

Native requests send X-Session-Binding and Authorization: Bearer for protected calls. Login/refresh responses return credentials and the protected binding. Store them through a reviewed Keychain/Keystore bridge, not localStorage or Capacitor Preferences. Native requests reject Cookie headers. Origin, when present, must match a configured WebView origin; the native HTTP bridge can omit it. Mixed browser/native credentials are rejected. CORS uses explicit origins, allows credentials only for the browser profile and rejects unrelated origins.

Generate a fresh 43-character random request ID for each login/refresh operation (InteractiveSessionService.NewRequestId). Reuse that ID and the original input when retrying an uncertain network result. Coordinate refreshes within a client: a distinct ID racing the same refresh receives 409 RefreshConflict; a cached result already superseded by another rotation receives 409 RefreshSuperseded. Never blindly loop either conflict with a new ID and an old token.

Transactions, replay and revocation

Proof consumption, family/access/refresh creation and audit commit together. Rotation consumes the old refresh token and inserts its successor/access token in the same transaction. Account-row locking serializes rotation with factor changes and revocation. The default retry window is 30 seconds: the same bound request receives the same result. A short-lived encrypted receipt is the explicit exception to hash-only credential persistence; prune it after the retry window. A replay outside that window revokes only the affected family and commits its audit before returning an error. Other devices remain active.

Defaults: access 5 minutes, refresh idle lifetime 14 days, absolute session cap 30 days, at most 10 active sessions per user/application. Refresh preserves method, assurance, original authentication time, both epochs and the absolute cap. Policy changes can require reauthentication; refresh never launders old MFA. Routine factor changes advance CredentialVersion and clear outstanding completion proofs. Bound challenges carrying an older revision fail, including legacy bound challenges once the revision advances. Existing sessions and their original assurance/time remain valid. Anonymous discoverable-passkey ceremonies still need a current valid credential; a missing factor cannot authenticate after removal. Global logout advances the separate session epoch and invalidates outstanding completion proofs. Trusted security-event invalidation remains available.

Explicit authentication and revocation policy

AuthenticationPolicy.SessionEffect defaults to FactorChangeSessionEffect.Preserve. The host's existing AuthorizeAsync receives EnrollFactor, RemoveFactor or RegenerateRecovery and can select RevokeAll for that operation. RevokeAll advances the security epoch, denying existing access and refresh credentials immediately. Routine maintenance does not require this choice. Regenerating recovery codes still destroys the previous set; removing a factor still prevents its future use.

Factor-management authorization still requires a fresh authenticated actor and the required assurance, through AuthenticationPolicy.MaximumAuthenticationAge and RequiredAssurance. This change does not bypass enrollment/bootstrap policy, mandatory MFA, challenge replay protection or the current directory/policy lookup.

SessionPolicy.Revocation separately configures SessionRevocationPolicy: required assurance, maximum authentication age and AllowIndividual/AllowOthers/AllowAll. Its default is primary assurance, authentication no older than ten minutes and all three management operations allowed. Hosts can require MFA or a shorter freshness window. Missing/stale proof returns Authentication.StepUpRequired; disabled management operations return Authentication.RevocationDenied. No state changes before admission succeeds. Logout of one's own bound family is still available through the refresh credential even after access/freshness expiry.

Use InteractiveSessionService.RevokeOtherSessionsAsync or the revoke-others HTTP route. The server derives the retained family from the validated access token and binding. There is no client-selected exemption ID, and user IDs from JSON cannot select another subject. All other families across applications for that same authority/subject are revoked; other users/authorities remain unaffected. The retained family, refresh token and epochs are unchanged. Pending completion proofs are cleared transactionally so a racing login cannot resurrect an older proof; new authentication admitted after the operation can establish a new session. Refresh and revocation share the account-row lock and commit with audit. Providers implementing IInteractiveSessionStore must implement the new operation; the default interface implementation throws rather than silently skipping revocation.

Optional login information

All capture is disabled by default. SessionHttpOptions independently enables CaptureUserAgent, CaptureIpAddress, CaptureDeviceInformation and CaptureClientLocation. User agent is observed from the request but spoofable. IP defaults to Connection.RemoteIpAddress, never raw forwarded headers. Behind a proxy/BFF, supply ClientIpResolver using the host's configured trusted-forwarding or authenticated-BFF resolver. A peer IP may identify the proxy rather than the end user. IP is descriptive telemetry, never identity or MFA evidence.

LoginInput accepts optional loginInformation with DeviceName, ClientVersion and Location. It does not accept an IP or user agent supplied through JSON. Location is ClientReportedLocation: latitude, longitude, accuracy in meters, CapturedAt and ConsentReported. Coordinate ranges, finite values, accuracy and capture time are bounded. ConsentReported must be true and server capture enabled. This records the client's declaration; it does not verify location or legal consent. Products must actually request permission and explain capture. No GPS collection, IP geolocation provider, external lookup or fingerprinting is performed by foundation.

The non-HTTP API LoginWithInformationAsync accepts a host-created SessionLoginInformation. Device/version labels and GPS are unverified client descriptions. Existing fields already provide application/client/profile, session creation/expiry, original authentication time, method and assurance. No continuous location tracking or per-request last-seen writes are introduced.

Information is saved only in a successful initial-login transaction, encrypted in nullable ProtectedLoginInformation with a session-specific protection purpose. Audit failure rolls it back. Login retries return the original committed snapshot; refresh does not overwrite it or renew the GPS timestamp. The authenticated /me response and login response expose the caller's own snapshot. There is no public user/session directory. Metadata-bearing models redact their ToString output.

Products own purpose, disclosure, access and retention policy. Bounded session pruning deletes metadata with the expired family; schedule it and select suitable session lifetimes/retention before enabling capture. It is not an automatic independent retention service for location data.

Upgrade from 0.7.0

Generate a migration in the consuming context after updating its configurations. The relational change is one nullable string column, ProtectedLoginInformation, on interactive_sessions (maximum length 16384); no session/token rewrite or data backfill is needed. CredentialVersion is inside the protected account JSON and defaults to zero for older payloads. Existing constructors/deconstruction shapes remain unchanged; new optional data uses init properties.

Apply the additive migration before deploying the new mapping. Tests generate the actual EF model difference and SQL on SQLite and PostgreSQL, roll DDL back, then apply it and authenticate/refresh a session created against the 0.7.0 model. Products retain their own migration history; foundation supplies configurations and upgrade acceptance, not an applied product migration chain.

For trusted password-reset, directory-disable or other security events call IInteractiveSessionStore.InvalidateSubjectAsync with a stable event ID. This transaction revokes the subject's families and proofs without needing an active user session. Delivery is idempotent: redelivering that ID does not kill a later new login. Retain the corresponding audit IDs for the event-redelivery window. Do not expose this trusted operation through anonymous input.

Schedule bounded PruneSessionsAsync batches. Clear expired retry receipts and expired rows, but retain consumed unexpired refresh rows as replay evidence. Audit failure rolls back login, rotation and revocation. Current tests establish SQLite and PostgreSQL behavior; accept another relational provider explicitly before production use. In-flight requests admitted before a revocation require normal product transaction/authorization rules; the next authentication rejects revoked state.

Native association and acceptance

MapFoundationAppAssociations serves /.well-known/apple-app-site-association and /.well-known/assetlinks.json on the configured RP host only. Configure Apple TEAMID.bundleid values and Android package IDs with approved colon-separated SHA-256 signing-certificate fingerprints. Serve these over the real identity HTTPS domain; configure OS entitlements/associations and release certificate rotation consistently. Android origins must exactly match the approved android:apk-key-hash: for the bound client. iOS uses the reviewed HTTPS origin. No wildcard or implicit trust of Capacitor local schemes or tenant subdomains is granted. The binding is not device attestation and an app ID alone does not prove binary identity.

Backend tests cover software WebAuthn registration/assertion through HTTP, cookie and bearer protected requests, expiry, refresh, logout, origin rejection, CSRF/CORS, concurrent/replayed rotation, rollback, global/factor revocation and populated-schema upgrades. Run scripts/verify.sh (Windows: scripts\verify.cmd) and its postgres mode. The latter uses FOUNDATION_TEST_POSTGRES when configured or a disposable loopback-only cluster using installed PostgreSQL binaries. CI has a separate PostgreSQL 16 service job. No Python or Node runtime is required.

Real browser/PWA and Capacitor iOS/Android builds must still pass physical passkey, secure-storage, app/domain association and recovery journeys. Software fixtures do not establish Touch ID, Face ID or physical YubiKey acceptance.

References: Apple passkeys, Android passkey origins, Capacitor configuration.

For the public/private-origin topology, follow BFF integration. For native provider SDK tokens, see the 0.19 OIDC exchange.

↑ ↓ to move↵ to openSearching fabricators .NET foundation v0.19.0