# Validate external login before product admission

Configure Google, Apple and explicit Microsoft directory profiles with durable intent and product completion ports.

Status: supplied in Foundation 0.9.0. The older 0.8.0 packages do not contain this
adapter. No real provider applications or callbacks are configured.

## Ownership

`Fabricators.Authentication.OpenIdConnect` uses the official
Microsoft.AspNetCore.Authentication.OpenIdConnect handler for discovery, code
exchange, signature, issuer/audience/lifetime, correlation and nonce validation.
The provider-neutral contracts live in Application, without HTTP/EF dependencies.

The adapter supplies neither a user database nor an application session cookie.
A validated external identity reaches a mandatory product completion port only
after the entire protocol succeeds and a durable browser-bound intent is consumed.
No access token, refresh token, unsigned Apple profile or amr/acr assurance crosses
that port. Email equality never grants account linking or tenant access.

Products own signup, stable UserIds, username/email normalization, external-key
uniqueness, linking/unlinking, MFA, user admission, audit, recovery and migrations.
An external key includes the configured provider/client namespace, validated issuer
and stable subject. Keep that namespace stable across deployments and client-ID
changes, or perform an explicitly reviewed identity migration.

## Register the bridge

```csharp
services.AddFoundationOidc(new OidcProvider(
    "google",
    OidcProviderProfile.Google,
    configuredClientId,
    new Uri("https://login.example.test")));
```

Register scoped implementations of IOidcLoginIntentStore, IOidcLoginCompletion and
IOidcClientSecretSource. No permissive or process-local production fallback exists.
Configure persistent shared Data Protection keys with the correct application
discriminator. Call `UseAuthentication()` before product endpoints. Configure
trusted proxy forwarding before authentication; callback scheme/host must match
PublicOrigin exactly. The released default has no path base; the 0.19.0
BFF transport below adds an explicit public prefix.

From a CSRF-protected product POST, call OidcLoginBridge.BeginAsync with the fixed
registered provider and an OidcLoginContext created by the trusted product host.
ContextId references server-owned pending user/client state; never bind it to an
anonymous UserId. Begin additionally requires HTTPS, same-origin Origin and JSON.
Translate invalid-input exceptions to bounded no-store errors in the product API.
The adapter does not publish a start endpoint or grant linking authority by itself.

Linking requires recent authenticated consent before Begin and a current authority
recheck in completion. A login intent must not become a link intent because an
email matches. Disablement and changed method policies must still deny completion.

ReturnPath is a bounded local path without a query, fragment, encoded separators
or backslashes. Store any return context server-side; do not carry credentials or
native handoff tokens in URLs. The browser binding is a per-intent Secure, HttpOnly,
host-only cookie with SameSite=None for Apple's cross-site form POST. Provider
correlation and nonce cookies remain managed by the official handler.

Products must enforce request/body limits, rate budgets and bounded pending-intent
counts at the start/callback routes and reverse proxy. Keep callback traffic out
of credential-bearing query/body logs, traces and third-party page assets. Leave
IdentityModel PII/security-artifact logging disabled. The built-in backchannel
uses HTTPS, bounded responses/timeouts and no cookies or HTTP redirect following.

## Durable consumption and local completion

CreateAsync persists a fresh intent with its provider, browser-binding hash,
trusted product context and a five-minute lifetime. TryConsumeAsync atomically
checks all of those fields, creation/expiry and unused state across instances.
Mismatches must not consume another intent. Prune expired data using host policy.
The bridge independently checks the returned intent before product completion.

Consumption happens before product effects. CompleteAsync rechecks current product
authority and records linking/login, audit and the next local handoff/MFA step in
its own transaction, idempotent by intent ID. A failed completion consumes this
attempt; restart login with a new intent. Never fall through to signing the provider
principal into a product cookie. No application session scheme is installed here.

VerifiedAt is the local validation time. ProviderAuthenticatedAt is the signed
auth_time when supplied; its absence does not prove recent reauthentication.
An upstream amr/acr claim does not satisfy local MFA. Product mapping to Foundation
primary-login proofs must preserve these distinctions and enforce the chosen policy.
The adapter does not solve cross-store ERP credential/session transactions.

Browser/PWA clients can use the local completion flow directly. Capacitor clients
need a system-browser launch and a product-owned, single-use native handoff bound
to the original registered app/client. Do not return provider tokens through a
custom URL scheme or treat an embedded WebView as a trusted authentication origin.
Native handoff/client UX and physical-device acceptance remain product work.

## Provider profiles

- Google uses its fixed authority and code/PKCE S256 flow, with openid/email only.
- Apple uses its fixed authority, code flow and form_post callback. PKCE is explicitly
  disabled for this profile, rather than inferred from another provider. Only signed
  identity claims are returned; Apple's unsigned first-login profile is ignored.
  IOidcClientSecretSource supplies a runtime signed client-secret JWT. The
  AppleClientSecret.Create helper signs ES256 with a server-owned P-256 key, explicit
  team/client/key IDs and a lifetime of one minute to one day; the caller owns key
  loading, protection and rotation. No key is serialized into login state.
- Microsoft requires a specific canonical directory GUID. Register approved
  directories separately; use OidcProvider.MicrosoftConsumerTenant for personal
  accounts. Each configuration has its own provider/client namespace. The generic
  common/organizations aliases and arbitrary tenant discovery are intentionally
  unsupported until a separate maintained multitenant issuer policy is implemented.

All redirect profiles require confidential-client credentials at runtime, fixed HTTPS
PublicOrigin and derived callback paths `/auth/oidc/callback/{providerId}`. Token
validation accepts RS256 ID tokens; Apple's ES256 client secret is a different
credential. Native and web client audiences must be configured explicitly.
Microsoft sign-in requests no Graph grant: mailbox OAuth consent remains separate.

## Evidence and limits

Version **0.15.0** adds a separate Reauthenticate purpose; it is
not in published 0.14.0. See [dedicated reauthentication](/foundation/0.19.0/guides/action-confirmation/#oidc-only-users-dedicated-reauthentication)
for issuer capability opt-in, expected linked identity, live session/operation
admission, signed auth_time and one-use primary StepUp integration. Ordinary
Login and Link retain their existing semantics. No provider is opted in by
default and controlled issuer tests do not certify any live provider profile.

Controlled HTTPS issuer fixtures exercise real discovery/JWKS retrieval, signed
token exchange, PKCE, Apple's form POST, invalid signatures/issuer/audience/nonce,
state/correlation/browser binding, expiry, concurrent consumption and product
rejection. Independent package consumers compile the public registration API.
Product stores must separately prove PostgreSQL uniqueness, rollback, current
admission, atomic intent consumption and credential/session races. These fixtures
do not establish live Google, Apple or Microsoft interoperability.

Local verification: 22 OIDC/Apple signing tests; full family acceptance passes
399 SDK-only and 11 PostgreSQL tests, zero-warning Release build, formatting,
info-level analyzers/unused imports/layout, 28 package archives and independent
consumer/tool/documentation checks. CI verifies the published source/tag separately;
consumer adoption and product integration remain explicit operations.

References: [official OIDC integration](https://learn.microsoft.com/en-us/aspnet/core/security/authentication/configure-oidc-web-authentication?view=aspnetcore-10.0),
[Apple authentication](https://developer.apple.com/documentation/signinwithapple/authenticating-users-with-sign-in-with-apple),
[Microsoft OIDC protocol](https://learn.microsoft.com/en-us/entra/identity-platform/v2-protocols-oidc).

## Native token exchange and authenticated BFFs (0.19.0)

Status: **supplied in 0.19.0**, not included in 0.18.0. No frontend, provider-console
configuration or physical-device acceptance is implied by these APIs.

Native SDK tokens use a separate entry point. The existing web callback still
rejects incoming ID/access tokens and accepts only its correlated code flow.
Capacitor can also use a system browser, PKCE and verified universal/app links;
SDK token exchange is an additional supported topology, not a reason to embed
Google's login page in a WebView.

Configure native audiences and authorized parties on trusted provider profiles:

```csharp
var apple = new OidcProvider("apple", OidcProviderProfile.Apple,
    "com.example.app.web", new Uri("https://app.example.test"))
{
    PublicPathBase = "/api",
    NativeClients =
    [
        new("ios", ["com.example.app"])
        {
            NonceMode = OidcNonceMode.Sha256Hex,
        },
    ],
};
var google = new OidcProvider("google", OidcProviderProfile.Google,
    webClientId, new Uri("https://app.example.test"))
{
    NativeClients =
    [
        new("ios", [webClientId, iosClientId])
        {
            ValidAuthorizedParties = [iosClientId, webClientId],
            NonceMode = OidcNonceMode.Raw,
        },
    ],
};
services.AddFoundationOidc(apple, google);
```

`NativeClients` defaults to empty. Each profile's `ValidAudiences` is a nonempty,
case-sensitive allowlist. Every audience in the token must be approved; multiple
audiences require `azp`. An `azp`, when present, must occur in the explicit
`ValidAuthorizedParties` list (or the audience list when that list is empty).
Use exact client IDs issued to your product, never audiences read from a request
or unvalidated token. The web code-flow audience remains its original `ClientId`.
Microsoft retains its explicitly configured directory issuer. Do not accept
arbitrary tenants or use email equality to join identities across providers.

From a product-owned HTTPS JSON POST after CSRF/native-client admission:

1. Create a trusted `OidcLoginContext` and recover a random per-client pending-login
   binding from the BFF's durable state. `clientBinding` must have at least 256 bits
   of entropy (43 base64url characters), remain bound to the same browser/app login,
   and never be an anonymous UserId or a freely submitted JSON field.
2. Call `BeginNativeAsync(http, provider, "ios", context, clientBinding)`.
   Return the resulting `OidcNativeChallenge` (ID, raw nonce, UTC expiry) through a
   no-store response. Foundation persists a five-minute intent using the existing
   `IOidcLoginIntentStore`; no new production schema or memory fallback is supplied.
3. Give the SDK the nonce in the configured convention. `Raw` compares the nonce
   directly; `Sha256Hex` compares lowercase hexadecimal SHA-256 of the UTF-8 raw
   nonce. Some SDKs hash automatically: configure the convention actually signed
   into the ID token and avoid double hashing. There is no raw/hash fallback.
4. POST `OidcNativeTokenExchange(ChallengeId, Nonce, IdToken)` through the BFF.
   Recover the same server-owned binding, select the same configured native profile
   and call `CompleteNativeAsync`. Never put the token/nonce in a URL or logs.

The bridge validates HTTPS discovery/JWKS, RS256 signatures, exact issuer, approved
clients/authorized party, lifetime, integer time claims and nonce before atomically
consuming the bound intent. Key rollover uses IdentityModel's cached configuration
and refresh machinery; a refresh-in-progress can require retrying the exchange.
An invalid token or mismatched binding does not consume another attempt. Profile,
audience policy, nonce convention, nonce and client binding are committed into the
intent binding; configuration changes require a new attempt. Concurrent valid
exchanges have one winner. Failed product completion consumes that attempt and
requires a new login, as for web callbacks. Apply bounded start/exchange budgets
and prune expired intents in the product store.

`CompleteNativeAsync` calls the same `IOidcLoginCompletion` and dedicated
reauthentication authority as the web flow. It sets no cookie and performs no
redirect. The product/BFF owns the returned local session or single-use handoff,
with current user/linking admission, MFA, audit and account uniqueness unchanged.
For reauthentication, the provider capability must be explicitly enabled and the
SDK must obtain a fresh signed `auth_time` for the same linked identity. An old
cached SDK token or upstream `amr: mfa` is not local reauthentication/MFA evidence.
Cancellation propagates; other exchange failures are redacted without provider
exceptions or tokens. Product route handlers still map errors to bounded HTTP
responses and enforce stream/body limits (including chunked requests).

### Private API origin, public BFF cookies and callbacks

Two supported arrangements are explicit:

- A conventional trusted reverse proxy can use ASP.NET forwarded-header middleware
  with fixed known proxies/networks before authentication, restoring the public
  HTTPS host and path base. Never trust arbitrary forwarded headers globally.
- A BFF-only pipeline can install `UseFoundationOidcBff` before authentication:

```csharp
app.UseFoundationOidcBff(
    new OidcBffOptions(new Uri("https://app.example.test"), "/api"),
    authenticateProxy: (http, cancellationToken) =>
        proxyCredentials.VerifyAsync(http, cancellationToken));
app.UseAuthentication();
```

The mandatory delegate verifies server-to-server provenance, for example mTLS or
an authenticated BFF service credential. Origin/Host/X-Forwarded-* or a browser
cookie do not authenticate a proxy. The middleware denies all downstream requests
on that pipeline until the check succeeds, then applies only its fixed configured
public origin/prefix. It ignores caller-provided forwarded-host values. Protect
this transport on a private network/TLS connection; browser callers never receive
the proxy credential. If only selected routes use the BFF, install this middleware
on their branch, including start, exchange and callback paths.

The BFF strips `/api` before forwarding and relays the original Origin header,
query/form body and individual Set-Cookie headers. The provider's `PublicPathBase`
must match the BFF options. Its public callback becomes
`https://app.example.test/api/auth/oidc/callback/apple`, while the API handler still
matches `/auth/oidc/callback/apple`. Configure that exact public callback with the
provider. Correlation/nonce and intent cookies are Secure/HttpOnly, root-path,
host-only cookies; through the BFF they belong to `app.example.test`, not the API
origin. Do not follow provider redirects server-side or flatten Set-Cookie headers.
Do not change Apple's cross-site form-post SameSite behavior. A missing or mismatched
correlation cookie still fails before product completion.

The product's completion port records a client-bound local result; the BFF can
redeem that result using its original pending ContextId and set its own session
cookies. Do not expose raw provider tokens/principals through a redirect or treat
an unbound ContextId as a completion credential. Shared Data Protection keys and
atomic durable intents remain necessary across API instances.

Protocol references: [native OAuth topology](https://www.rfc-editor.org/rfc/rfc8252),
[Google backend ID-token validation](https://developers.google.com/identity/sign-in/web/backend-auth),
[Apple server authentication](https://developer.apple.com/documentation/signinwithapple/authenticating-users-with-sign-in-with-apple).
