Elarion

Proxy identity

Authenticate an app that sits behind an authenticating reverse proxy (Cloudflare Access, Google IAP, oauth2-proxy, an OIDC gateway) — validate the forwarded token, refuse to start unauthenticated, and develop locally with a stand-in identity.

Many small apps never run a sign-in flow of their own. An authenticating reverse proxy in front of them — Cloudflare Access, Google Cloud IAP, oauth2-proxy, an OpenID Connect gateway — signs the person in and forwards a short-lived signed token with every request, in a vendor header or a cookie. The app's job is to validate that token, never to trust an unsigned "user" header, and every app ends up rebuilding the same adapter around JwtBearer. The optional Elarion.AspNetCore.ProxyIdentity package is that adapter:

  • reads the token only from the configured header and/or cookie (a Bearer prefix is stripped);
  • validates issuer, audience, lifetime and signature, with audience required unless you opt out explicitly;
  • gets the signing keys from a JWKS URL or OpenID Connect discovery through IdentityModel's ConfigurationManager — no hand-rolled key cache;
  • keeps the token's claim names (MapInboundClaims = false) and maps ICurrentUser to them;
  • refuses to start outside Development when it is disabled or half-configured, unless you explicitly sign everyone in as one fixed identity;
  • gives Development a stand-in identity with user, roles and groups switches, so the app runs locally without the proxy;
  • exposes an ExternalIdentity record (issuer, subject, e-mail with a trust decision, name, groups, roles) and an optional session-snapshot section.

Authentication stays a host concern: handlers still declare [RequirePermission]/[RequireRole] and read ICurrentUser; only the host wiring changes (authorization).

Wiring

using Elarion.AspNetCore.Identity;        // UseElarionCurrentUser
using Elarion.AspNetCore.ProxyIdentity;   // AddElarionProxyIdentity

builder.Services.AddElarionProxyIdentity(builder.Configuration, builder.Environment);  // section "ProxyIdentity"
builder.Services.AddElarionAuthorization();

var app = builder.Build();
app.UseElarionCrossOriginProtection();   // the proxy's session cookie is an ambient credential (see below)
app.UseAuthentication();
app.UseElarionCurrentUser();   // after authentication, before endpoints
app.UseAuthorization();

AddElarionProxyIdentity binds the ProxyIdentity section, applies the optional configure callback, validates the result and throws an InvalidOperationException naming the offending setting when it cannot run. It registers the proxy scheme (ProxyIdentityDefaults.AuthenticationScheme) as the default and returns the AuthenticationBuilder, so further named schemes can be added. It also registers ICurrentUser mapped to the configured subject, e-mail and role claims — registration is first-wins, so call it before any other AddElarionCurrentUser; an application that signs in a principal of its own builds it under these names (replacing the principal).

At startup it logs once what the instance accepts (issuer, key source, header, cookie, e-mail trust) and warns when audience validation is off or the Development stand-in is active.

Configuration

{
  "ProxyIdentity": {
    "Enabled": true,
    "Issuer": "https://myteam.cloudflareaccess.com",
    "JwksUrl": "https://myteam.cloudflareaccess.com/cdn-cgi/access/certs",
    "Audiences": [ "4714c1358e65fe4b408ad6d432a5f878f08194bdb4752441fd56faefa9b2b6f2" ],
    "TokenHeader": "Cf-Access-Jwt-Assertion",
    "TokenCookie": "CF_Authorization",
    "EmailTrust": "Trusted",
    "LogoutUrl": "/cdn-cgi/access/logout"
  }
}
SettingDefaultMeaning
EnabledfalseValidate proxy tokens. false selects the Development stand-in and is refused outside Development, unless Fixed:Enabled is set.
Issuer—The exact iss of the proxy's tokens. Required when enabled.
JwksUrl—A bare JSON Web Key Set. Mutually exclusive with MetadataAddress.
MetadataAddress—An OpenID Connect discovery document. With neither set, {Issuer}/.well-known/openid-configuration is used.
RequireHttpsMetadatatrueKey and discovery URLs must be https; turn off only for a local test issuer.
Audiences—Accepted aud values; each entry may be a comma-separated list. Required unless AllowAnyAudience.
AllowAnyAudiencefalseAccept any audience of the issuer. Logged as a warning; cannot be combined with Audiences.
TokenHeader—The header carrying the token. At least one of TokenHeader/TokenCookie is required.
TokenCookie—The cookie read when the header is absent.
Claims:SubjectsubThe stable subject; becomes ICurrentUser.UserId.
Claims:EmailemailBecomes ICurrentUser.Email.
Claims:EmailVerifiedemail_verifiedRead under EmailTrust = Claim.
Claims:NamenameThe display name (also the principal's name claim).
Claims:GroupsgroupsIdentity-provider groups, exposed on ExternalIdentity.Groups only.
Claims:RolesrolesApplication roles (RFC 9068 §2.2.3.1); the role claim of the principal, so ICurrentUser.Roles and [RequireRole] use it.
EmailTrustClaimClaim (verified when email_verified is true), Trusted (the proxy vouches for every address), None.
LogoutUrl—Where the browser signs out of the proxy; surfaced in the session section.
ClockSkew00:01:00Tolerance for exp/nbf. Proxy tokens are short-lived, so it is tighter than JwtBearer's five minutes.
AutomaticRefreshInterval01:00:00How long fetched keys are used before a background refresh (library minimum: 5 minutes).
RefreshInterval00:01:00Minimum time between refreshes triggered by an unknown key id (library minimum: 1 second).
LastKnownGoodLifetime00:00:00 (off)IdentityModel's last-known-good grace for a configuration a refresh replaced (see below).
Development:*see belowThe stand-in identity.
Fixed:*offOne identity every request is signed in as, in any environment (below).

Set any value from code with the configure callback, which runs after binding and before validation:

builder.Services.AddElarionProxyIdentity(builder.Configuration, builder.Environment,
    options => options.Audiences.Add(builder.Configuration["PUBLIC_HOSTNAME"]!));

Proxy recipes

Each recipe is the ProxyIdentity section; everything not shown keeps its default.

Cloudflare Access

{
  "Enabled": true,
  "Issuer": "https://<team>.cloudflareaccess.com",
  "JwksUrl": "https://<team>.cloudflareaccess.com/cdn-cgi/access/certs",
  "Audiences": [ "<Application Audience (AUD) tag>" ],
  "TokenHeader": "Cf-Access-Jwt-Assertion",
  "TokenCookie": "CF_Authorization",
  "EmailTrust": "Trusted",
  "LogoutUrl": "/cdn-cgi/access/logout"
}

Access forwards the header on proxied requests; the cookie covers requests where the header is absent. The application token carries sub and email but no email_verified, so decide EmailTrust from your login methods (Trusted for one-time PIN or a directory you trust).

Google Cloud IAP

{
  "Enabled": true,
  "Issuer": "https://cloud.google.com/iap",
  "JwksUrl": "https://www.gstatic.com/iap/verify/public_key-jwk",
  "Audiences": [ "/projects/<project-number>/global/backendServices/<service-id>" ],
  "TokenHeader": "x-goog-iap-jwt-assertion",
  "EmailTrust": "Trusted",
  "Claims": { "Name": null }
}

IAP signs with ES256 keys, which the JWKS handles like any other. For App Engine the audience is /projects/<project-number>/apps/<project-id>. The token has no display name.

oauth2-proxy

With --pass-authorization-header (or --set-authorization-header behind an auth_request proxy) oauth2-proxy forwards the identity provider's ID token as Authorization: Bearer …:

{
  "Enabled": true,
  "Issuer": "<the --oidc-issuer-url>",
  "Audiences": [ "<the --client-id>" ],
  "TokenHeader": "Authorization"
}

The keys come from the issuer's discovery document. Note the TokenHeader: the standard Authorization header is read only when it is configured, because the package never falls back to a location the proxy does not control.

Any OpenID Connect gateway

A gateway that forwards tokens of a standard OIDC provider needs the issuer, the audience and the header; the keys come from discovery. When the discovery document lives somewhere other than {Issuer}/.well-known/openid-configuration, set MetadataAddress:

{
  "Enabled": true,
  "Issuer": "https://login.example.com/tenant/v2.0",
  "MetadataAddress": "https://login.example.com/tenant/v2.0/.well-known/openid-configuration",
  "Audiences": [ "api://my-app" ],
  "TokenHeader": "X-Forwarded-Id-Token",
  "Claims": { "Subject": "oid" }
}

A discovery document must name exactly the configured issuer (OpenID Connect Discovery §4.3); one that names another issuer is refused, so it can never widen the accepted issuers. Proxies that publish keys in another format than a JWKS (for example per-key PEM endpoints) are not covered.

Expired sessions in the browser

The proxy's session expires on its own schedule, and the app only learns of it from the next request. A page load is fine: the proxy renews the session on the way, through redirects to its own and the identity provider's origins, usually without the person seeing a sign-in. An API call is not, and a single-page app or an installed one makes little else:

ProxyAPI call after expiryWithout a marker header
Cloudflare Access401 with X-Requested-With: XMLHttpRequestRedirect to the team domain: a CORS failure
Google Cloud IAP401; send X-Requested-With: XMLHttpRequest where it redirects insteadRedirect: a CORS failure
oauth2-proxy401 with Accept: application/jsonRedirect to the provider: a CORS failure

A browser's EventSource sends neither header, so a live-update stream fails without a reason. Elarion's browser side handles both: createSessionRenewal() from @swimmesberger/elarion-pwa marks the JSON-RPC calls, probes a failing event stream, and answers an expired session with one reload that lets the proxy renew it — see Renewing an expired proxy session.

How often that reload ends at a sign-in page is the proxy's and the identity provider's configuration, not the app's. On Cloudflare Access the application token expires after the application's session duration (24 hours unless set), and Access renews it silently while the global session is still valid; raise both for an app people keep open for weeks, and keep the identity provider's own session persistent (an IdP that forces a password on every re-authentication, or a session cookie that dies with the browser process, defeats the silent renewal).

Signing keys

The package builds one IdentityModel ConfigurationManager<OpenIdConnectConfiguration> per scheme; a JWKS URL is read through a small retriever into the same configuration shape, so both modes behave identically. The configuration is accepted only when it names the configured issuer and holds at least one signing key. What follows is the library's behaviour, pinned by the package's tests:

SituationBehaviour
First requests after startupOne fetch; every concurrent request waits for it, none is validated against an empty key list.
Key endpoint down at startupRequests are refused (401, fail-closed); the next request after the endpoint recovers fetches again and succeeds.
Routine refreshIn the background every AutomaticRefreshInterval; requests keep using the current keys.
Token with an unknown key idThat request is refused and a background refresh is requested (at most once per RefreshInterval); the new key is accepted as soon as it lands.
Refresh fails, or returns no keys / a foreign issuerThe current keys keep serving.
A key the issuer withdrewStops validating once the refresh lands, unless LastKnownGoodLifetime grants a grace.

Most proxies publish a new key well before they sign with it, so the routine refresh normally picks it up before the first token arrives; lower AutomaticRefreshInterval if yours rotates faster. LastKnownGoodLifetime is off by default although IdentityModel's own default is one hour: that grace keeps accepting tokens signed with a key the issuer withdrew, which is the wrong default when a key is withdrawn because it leaked. An outage never needs it.

The keys are fetched with the named HttpClient ProxyIdentityDefaults.HttpClientName (10-second timeout); configure it with services.AddHttpClient(ProxyIdentityDefaults.HttpClientName) to add an outbound proxy or a handler.

Startup refusal

Outside the Development environment, Enabled: false throws at startup — a deployment that lost its proxy configuration must not come up as "everybody is the development user". The only way past it is the explicit fixed identity. An enabled configuration is refused when the issuer, the audience (without AllowAnyAudience), the token location or the subject claim is missing, when both JwksUrl and MetadataAddress are set, when a key URL is not https (unless RequireHttpsMetadata is off), or when a refresh interval is below the library minimum.

The token only says who the proxy signed in. Make sure the app is reachable only through the proxy, and keep the audience scoped to this app: without it any other application behind the same issuer could present its tokens here. The proxy signs the browser in with its own session cookie and forwards the token on every request it lets through, including one that a page on another site makes the browser send. The token is therefore an ambient credential whether the app reads it from a header or a cookie: install UseElarionCrossOriginProtection (see CSRF and cookie authentication).

Development stand-in

With Enabled: false in Development, every request is signed in as the configured developer, with the same claim shape a proxy token carries (under your Claims names) and the issuer ProxyIdentityDefaults.DevelopmentIssuer. The X-Elarion-Dev-User header or the elarion-dev-user cookie (URL-encoded) switches the user: to one of Development:Users when its e-mail address or subject matches, otherwise to an ad-hoc user with that address, a subject of dev:{address} and no groups or roles (the roles and groups switches give it some).

{
  "ProxyIdentity": {
    "Enabled": false,
    "Development": {
      "Subject": "developer",
      "Email": "developer@example.com",
      "Roles": [ "admin" ],
      "Users": [
        { "Subject": "reader-1", "Email": "reader@example.com", "Name": "A Reader", "Roles": [ "reader" ] }
      ]
    }
  }
}

Set Development:UserHeader/UserCookie to empty to turn the switch off. With Enabled: true the real proxy scheme runs in Development too, for testing against a staging proxy.

User switch valueSigns in
absent or emptythe configured developer (Development:Subject/Email)
the e-mail address or subject of a Development:Users entrythat user
any other valuean ad-hoc user with that address, subject dev:{address}, no groups or roles
- (ProxyIdentityDefaults.DevelopmentSignedOutUser)nobody: the request is anonymous (signed-out state)

Seeing the signed-out state in development

The stand-in signs someone in on every request, but the application also has a signed-out face — a landing page, a sign-in prompt, the 401 an [Authorize] endpoint returns. Set the user switch to the reserved value - to see it:

GET /api/settings
X-Elarion-Dev-User: -

or set the elarion-dev-user cookie to -. For that request the stand-in signs nobody in — the same outcome as a proxy that forwarded no token: HttpContext.User and ICurrentUser are anonymous, an endpoint that requires authorization is challenged with 401, no IExternalIdentityFeature is captured, and the roles and groups switches are ignored, since there is nobody to give them to. The session section carries no identity but still names the switch cookies, so a development switcher can sign back in; removing the switch returns to the configured developer.

A client-side development menu does not need to hard-code the value: the section's developmentSignedOutUser member carries it whenever the user switch cookie is named, so the menu sets developmentUserCookie to that value instead of a literal -.

Like every switch value it is trimmed, and it is reserved: AddElarionProxyIdentity refuses a stand-in user — the configured developer or a Development:Users entry — whose subject or e-mail address is -. It belongs to the stand-in alone; validated proxy tokens never read the switch.

Switching roles and groups

An identity provider grants roles and groups that configuration cannot predict for an ad-hoc user — an owner or admin role, a team group. The roles switch sets them per request, for any user the stand-in signs in:

GET /api/settings
X-Elarion-Dev-User: new.person@example.com
X-Elarion-Dev-Roles: owner,admin

The X-Elarion-Dev-Roles header, or the elarion-dev-roles cookie (URL-encoded) when the header is absent, carries a comma-separated list. When present it replaces the resolved user's roles — the configured developer, a Development:Users entry or an ad-hoc user alike; absent, the configured roles stay. Values are trimmed and de-duplicated, and are emitted under the configured Claims:Roles name, so ICurrentUser.Roles, [RequireRole] and ExternalIdentity.Roles see them exactly as they would see a proxy token's roles. An empty header means no roles; ASP.NET Core ignores a cookie with an empty value, so a cookie clears the roles with , (a list of no entries), and removing the cookie restores the configured ones. A value longer than 256 characters is ignored.

The groups switch — X-Elarion-Dev-Groups header, elarion-dev-groups cookie — works the same way for ExternalIdentity.Groups, so an application that maps identity-provider groups to its own permissions can be tested too. Set Development:RolesHeader/RolesCookie or GroupsHeader/GroupsCookie to empty to turn a switch off.

Like the user switch, these exist only where the stand-in does: with Enabled: false and no fixed identity, which is refused outside Development. When proxy tokens are validated or the fixed identity is on, no switch is read, in any environment.

Fixed identity without a proxy

Some deployments have no authenticating proxy on purpose: an instance reachable only on a home or office network, or behind a VPN, where everyone who can reach it is trusted. Fixed signs every request in as one configured user, in any environment:

{
  "ProxyIdentity": {
    "Fixed": {
      "Enabled": true,
      "Subject": "household",
      "Name": "Household",
      "Roles": ["admin"]
    }
  }
}

Requests carry the same claim shape as a proxy token, under the issuer urn:elarion:proxy-identity:fixed (ProxyIdentityDefaults.FixedIssuer, ExternalIdentity.IsFixedIdentity), so the application reads ICurrentUser and ExternalIdentity exactly as it does behind a proxy, and enabling a proxy later is a configuration change. Subject is required; it is the key the application stores that user's data under, so keep it stable. Email, Name, Groups and Roles are optional.

Unlike the Development stand-in, the fixed identity has no switches: no header or cookie changes the user, its roles or its groups, so a visitor cannot give themselves admin. Nobody can sign out either. A proxy token on the request is ignored. Fixed:Enabled together with Enabled: true is refused at startup, and the app logs a warning on every start that it runs unauthenticated.

Anybody who can reach the instance acts as the fixed user, with its roles. Use it only where the network itself is the access control, and give the user only the roles everyone may have. Keep UseElarionCrossOriginProtection installed: an always-signed-in user is an ambient credential too.

Reading the identity

Handlers read ICurrentUser as always. When the application needs more — linking the person to a local account, mapping identity-provider groups to permissions, trusting the address for an invitation — read the ExternalIdentity record:

// In a handler: transport-neutral, from ICurrentUser.
var identity = ExternalIdentity.TryRead(currentUser, proxyOptions.Value);   // IOptions<ProxyIdentityOptions>
if (identity is { EmailVerified: true }) { /* link by e-mail */ }

// In host code: from the request. Keeps working after the application replaced the principal.
var fromRequest = ExternalIdentity.TryRead(httpContext, proxyOptions.Value);

The request reader returns the identity captured when the token (or the stand-in) was accepted, kept in HttpContext.Features as IExternalIdentityFeature, and falls back to httpContext.User. The ICurrentUser and ClaimsPrincipal readers see only the principal in place (replacing the principal).

MemberMeaning
Issuer, SubjectTogether the stable key of the person.
Email, EmailVerifiedThe address and the EmailTrust decision (always false without an address or under None).
NameThe display name, or null.
Groups, RolesTrimmed, de-duplicated values; a JSON array and a single string read the same.
IsDevelopmentIdentityTrue for the stand-in.

It grants nothing by itself; account linking and group-to-permission mapping stay application policy.

Replacing the principal

Some applications replace the proxy's principal after authentication, in a middleware between UseAuthentication and UseElarionCurrentUser: they link the person to a local account and sign in that account's principal (built with ASP.NET Core Identity's IUserClaimsPrincipalFactory<TUser>), or build a principal by hand, for example one carrying permissions mapped from identity-provider groups. ICurrentUser reads whatever principal is in place through one claim mapping, ClaimsCurrentUserOptions, so the replacement must carry its claims under that mapping's names.

The mapping in effect is the first one registered. AddElarionCurrentUser adds it with TryAdd, and so do the packages that call it — AddElarionProxyIdentity (the proxy's names: sub, email, roles by default) and AddElarionIdentity (Identity's ClaimTypes.NameIdentifier/Email/Role). A later registration is ignored without an error. So with the proxy identity registered first, a principal built under Identity's default claim types has no user id ICurrentUser can find.

Don't fix that with a second mapping: which one wins would depend on registration order, and the proxy's own principal (the stand-in included) would no longer be read. Keep the one mapping and build the replacement under its names, read from DI. With ASP.NET Core Identity, point IdentityOptions.ClaimsIdentity at the mapping, so the claims-principal factory emits those names:

using Elarion.Identity;            // ClaimsCurrentUserOptions
using Microsoft.AspNetCore.Identity;

builder.Services.AddElarionProxyIdentity(builder.Configuration, builder.Environment);  // registers the mapping
builder.Services.AddElarionIdentity<AppUser, AppRole, AppDbContext>();                 // its mapping is ignored

// The factory names claims after IdentityOptions.ClaimsIdentity: use the mapping in effect, whichever call supplied it.
builder.Services.AddOptions<IdentityOptions>()
    .Configure<ClaimsCurrentUserOptions>((identity, currentUser) => {
        identity.ClaimsIdentity.UserIdClaimType = currentUser.UserIdClaimType;
        identity.ClaimsIdentity.EmailClaimType = currentUser.EmailClaimType;
        identity.ClaimsIdentity.RoleClaimType = currentUser.RoleClaimType;
    });

Identity's own readers, such as UserManager.GetUserId(principal), use the same IdentityOptions and follow along. A hand-built principal takes the claim types from an injected ClaimsCurrentUserOptions and passes RoleClaimType as the ClaimsIdentity role type, so ClaimsPrincipal.IsInRole agrees with ICurrentUser.Roles. Code that hard-codes ClaimTypes.* to read the user should read ICurrentUser instead.

The replacement does not carry the proxy's issuer, so ExternalIdentity.TryRead(ICurrentUser, …) and TryRead(ClaimsPrincipal, …) return null after the swap — ASP.NET Core also drops its own authentication result once HttpContext.User is assigned. The proxy scheme and the stand-in therefore capture the identity when they accept the token, as IExternalIdentityFeature in HttpContext.Features. Read it with ExternalIdentity.TryRead(httpContext, options): it returns who the proxy signed in whether the application put a local account's principal in place or, for a person it has no account for, an anonymous one. The session section reads it the same way. The capture runs in the scheme's JwtBearerEvents (OnTokenValidated); a host that customizes those events for this scheme wraps the existing handlers rather than replacing the events instance.

Session section

To render an account menu without a second round trip, add the proxyIdentity section to the client-capability snapshot:

builder.Services.AddElarionSession(builder.Configuration.GetClientCapabilityManifest());
builder.Services.AddElarionProxyIdentitySessionSection();

It carries email, name, logoutUrl, isDevelopmentIdentity and isFixedIdentity for whoever the proxy signed in, read from the request, so they survive an application replacing the principal. logoutUrl is omitted for the Development stand-in and the fixed identity, which have no proxy session to end. While the stand-in is configured (Enabled: false, no fixed identity) it also names the cookies a development switcher sets — developmentUserCookie, developmentRolesCookie and developmentGroupsCookie, each omitted when that switch is turned off. Alongside the user switch cookie it carries developmentSignedOutUser, the reserved value (-) that signs nobody in, so a switcher reads it instead of hard-coding it; it is omitted exactly where developmentUserCookie is. Those names are static configuration, so they are present whoever is signed in, including a person the application treats as anonymous because no local account matches, and also while nobody is, with the user switch signed out (-). The section is omitted when the proxy signed nobody in and the stand-in is not configured; like every section, it is a read-only UX projection.

The snapshot endpoint is anonymous-friendly (MapElarionSession() adds no authorization), which is what lets a switcher reach a person without an account. A host that puts .RequireAuthorization() on it hides the section from exactly that person; the names are also available outside the snapshot from IOptions<ProxyIdentityOptions> (Development.UserCookie, RolesCookie and GroupsCookie, meaningful while Enabled is false).

On this page