Authio.AspNetCore.Bff
0.9.0
dotnet add package Authio.AspNetCore.Bff --version 0.9.0
NuGet\Install-Package Authio.AspNetCore.Bff -Version 0.9.0
<PackageReference Include="Authio.AspNetCore.Bff" Version="0.9.0" />
<PackageVersion Include="Authio.AspNetCore.Bff" Version="0.9.0" />
<PackageReference Include="Authio.AspNetCore.Bff" />
paket add Authio.AspNetCore.Bff --version 0.9.0
#r "nuget: Authio.AspNetCore.Bff, 0.9.0"
#:package Authio.AspNetCore.Bff@0.9.0
#addin nuget:?package=Authio.AspNetCore.Bff&version=0.9.0
#tool nuget:?package=Authio.AspNetCore.Bff&version=0.9.0
Authio.AspNetCore.Bff
A Backend-for-Frontend for Authio on ASP.NET Core (.NET 8 and .NET 10). It lets a browser SPA (React, Angular, Vue, plain JavaScript...) sign in with Authio without ever holding a token, following the BFF pattern of the IETF draft OAuth 2.0 for Browser-Based Applications.
dotnet add package Authio.AspNetCore.Bff
Why a BFF
Tokens kept in the browser (local storage, session storage, memory) can be stolen by any script that runs on the page. Refresh tokens in the browser are worse: they outlive the page. With a BFF:
- the SPA and the BFF share an origin; the browser only holds an
HttpOnly,Secure,SameSite=Lax, host-only cookie (__Host-authio) that scripts cannot read; - the BFF is a confidential client: it runs the authorization code flow (with PKCE), keeps the access, refresh and ID tokens server-side (the cookie only carries a random session key), refreshes them, and attaches the access token when it calls APIs on the user's behalf;
- every API call from the SPA must carry a custom header (
X-CSRF: 1), which a cross-site page cannot add without a CORS preflight, so the cookie cannot be abused by CSRF.
What it does
| Area | Behavior |
|---|---|
| Sign-in | Cookie + OpenID Connect schemes configured like the client in Authio: code flow, the checks of Authio:Checks (PKCE with S256 or plain, nonce), Authio:ResponseMode, the configured scopes, the ID token algorithm of Authio:IdTokenSignedResponseAlg, iss of the authorization response validated (RFC 9207), code redeemed through the Authio client with Authio:TokenEndpointAuthMethod, MapInboundClaims = false, no telemetry parameters, no PAR. |
| Authorize parameters | organization, resource (RFC 8707), prompt, login_hint, ui_locales, max_age, per login request or as defaults, plus any extra parameter. |
| Session | Server-side ticket store on IDistributedCache (in-memory by default, Redis for several instances), tickets encrypted with Data Protection. Sliding expiration (8 h by default). |
| Tokens | IAuthioBffTokenService refreshes the access token before it expires (Authio:TokenRefreshSkew), single-flight per session, validates the ID token a refresh hands back (signature, issuer, audience, expiry, at_hash, the session's sub) before keeping anything, persists the rotated refresh token, and ends the session on invalid_grant or a refused ID token. Per-resource tokens via token exchange, cached per session. |
| Liveness | Back-channel logout: POST /bff/backchannel-logout validates the logout token Authio posts when a session ends and refuses every BFF session of that Authio session (sid), or of the user (sub) when the token names no session, from its next request on (BackChannelLogout, default on). Front-channel logout (FrontChannelLogout, default off): GET /bff/frontchannel-logout, the page Authio loads in an iframe, ends the sessions of the Authio session named by sid (its iss checked) the same way, or the session whose cookie reached it. With SessionValidation = Introspection (default) the BFF also introspects the session's refresh token every 5 minutes and signs the user out when Authio says it ended (revocation, suspension). |
| Endpoints | /bff/login, /bff/logout, /bff/user, /bff/silent-login, /bff/backchannel-logout, /bff/frontchannel-logout. |
| Local APIs | .AsAuthioBffApiEndpoint() / [AuthioBffApi]: anti-forgery header required, 401/403 JSON instead of redirects (the 401 even while Authio cannot be reached). IHttpClientBuilder.AddAuthioBffUserToken() calls downstream APIs with the user's token. |
| Remote APIs | MapAuthioRemoteApi("/api/orders", "https://orders.example.com") forwards with YARP, attaching the user's token (or a machine token), stripping cookies and the anti-forgery header. |
Register the client at Authio
In the Authio console, create a client for the BFF:
- Type: confidential. Set
Authio:TokenEndpointAuthMethodto the method the client is registered for:Basic(what a secret implies when it is left out) orPost. Without a secret, chooseprivate_key_jwt, register the public key (JWK Set orjwks_uri), and setAuthio:TokenEndpointAuthMethodtoPrivateKeyJwtwithAuthio:ClientPrivateKeyPath(orAuthio:ClientPrivateKey) andAuthio:ClientKeyIdinstead ofAuthio:ClientSecret: the code redemption, every refresh, the session check (introspection), the token exchange and the logout revocation then carry a fresh signed assertion and the OpenID Connect handler is given no secret. SeeAuthio.Client. - PKCE: a new client requires it with
S256. SetAuthio:CheckstoPkce(addNoncefor the ID token'snonce), andAuthio:CodeChallengeMethodtoPlainonly for a client that allowsplain. - Signing algorithms: when the client signs its ID tokens with something else than an asymmetric algorithm of the
realm's keys, set
Authio:IdTokenSignedResponseAlgto it, andAuthio:AccessTokenSignedResponseAlgto the access token's (HS256,HS384andHS512are verified with the client secret, which then needs at least 32, 48 or 64 bytes). The session's roles and organization are copied from the access token only once it verifies. - Redirect URI:
https://<your-app>/signin-oidc(Authio:Bff:CallbackPath). - Post-logout redirect URI:
https://<your-app>/signout-callback-oidc(Authio:Bff:SignedOutCallbackPath). - Back-channel logout URI:
https://<your-app>/bff/backchannel-logout, with the session (sid) required, so a logout anywhere else (another application, the console, a revoked session) ends the BFF session at once. - Front-channel logout URI (optional, with
Authio:Bff:FrontChannelLogout = true):https://<your-app>/bff/frontchannel-logout, with the session required, so the page can end the session bysid(theSameSite=Laxcookie does not reach a cross-site iframe). - Scopes:
openid profile email offline_access(offline_accessgives the refresh token), plusrolesif you setRequestRoles, plus your API scopes. The BFF sendsAuthio:Bff:Scopesas they are;openidis required there (the sign-in fails at start-up without it). - Resources (optional): the API resource identifiers you will ask for with
resourceor use with remote APIs. - Allow the token exchange grant if a remote API needs a token for a specific resource or a narrower scope set.
Setup
{
"Authio": {
"Authority": "https://auth.example.com",
"Realm": "acme",
"ClientId": "acme-web",
"ClientSecret": "<secret>",
"TokenEndpointAuthMethod": "Basic",
"Checks": "Pkce, State, Nonce",
"Bff": {
"RequestRoles": true,
"SessionValidation": "Introspection",
"SessionValidationInterval": "00:05:00",
"SessionLifetime": "08:00:00"
}
}
}
using Authio.AspNetCore.Bff.Extensions;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthioBff(builder.Configuration.GetSection("Authio"));
var app = builder.Build();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthioBff();
app.UseAuthorization();
app.MapAuthioBffEndpoints();
app.MapGet("/api/me", (HttpContext context) => new { name = context.User.FindFirst("name")?.Value })
.RequireAuthorization()
.AsAuthioBffApiEndpoint();
app.MapAuthioRemoteApi("/api/orders", "https://orders.example.com");
app.Run();
Every setting that mirrors the client is read from Authio (see
Authio.Client); an option left out is off. Three
things are fixed by ASP.NET Core or by Authio itself: the OpenID Connect handler always sends and checks a state (it
carries the protected sign-in properties), whatever Checks says; Authio:ResponseMode = WebMessage fails at start-up
(its answer never reaches the callback); and pushed authorization (PAR) stays off, as Authio has no PAR endpoint.
AddAuthioBff(Action<AuthioBffOptions>) is also available when the client is configured with
services.AddAuthioClient(...). A bound Authio:Bff:Scopes replaces the default scopes (list openid there, or the
application fails at start-up); in code, options.Scopes starts with the defaults, so add to it or assign a new list.
For more than one instance, register a shared IDistributedCache (e.g. AddStackExchangeRedisCache) and persist the
Data Protection keys (e.g. AddDataProtection().PersistKeysToStackExchangeRedis(...)) before AddAuthioBff.
Token refreshes are single-flight per process; keep a user on one instance (sticky sessions) or rely on Authio's short
refresh-token reuse leeway.
A client that holds its own encryption key
When the client's encryption key source in Authio is its own (Security → Encryption key → Client's own key), the ID
token arrives encrypted to the client's key pair. Give the BFF the private key Authio showed when it generated the pair
(the JWK) or a PEM private key, as Authio:ClientEncryptionKey (the name every Authio library uses; or
Authio:ClientEncryptionKeyPath for a file):
{
"Authio": {
"ClientEncryptionKey": "{\"kty\":\"RSA\",\"use\":\"enc\",\"kid\":\"…\",\"n\":\"…\",\"e\":\"AQAB\",\"d\":\"…\",…}"
}
}
RSA-OAEP and RSA-OAEP-256 are accepted (narrow them with Authio:EncryptionAlgorithms and
Authio:EncryptionMethods); RSA1_5 only with Authio:AllowLegacyEncryptionAlgorithms = true.
The access token the session's roles and organization are read from is opened with the same key, then verified
(signature with Authio:AccessTokenSignedResponseAlg, by default the asymmetric algorithms discovery announces,
iss, exp); a token that does not verify is logged and contributes nothing. Authio always signs tokens encrypted to
the client's key. A client whose tokens are encrypted to the platform's key needs no key: its ID token is issued signed
only, but its access token cannot be read, so the session has no *_resource_access or organization claims.
Keep it out of appsettings.json in production (user secrets, a key vault, an environment variable). A signed UserInfo
response is read as usual; an encrypted one is not (ASP.NET Core's handler does not decrypt UserInfo), so leave
UserInfo unencrypted for this client or keep GetClaimsFromUserInfoEndpoint off.
The SPA side
const api = (url, init = {}) =>
fetch(url, { ...init, credentials: "same-origin", headers: { ...init.headers, "X-CSRF": "1" } });
const response = await api("/bff/user");
if (response.status === 401) {
window.location.href = "/bff/login?returnUrl=" + encodeURIComponent(location.pathname);
} else {
const claims = await response.json();
const logoutUrl = claims.find(c => c.type === "bff:logout_url").value;
}
- Log in: navigate to
/bff/login?returnUrl=/somewhere(local URLs only). Optionalorganization,prompt(none,login,select_account,consent),login_hint,ui_locales,max_ageandresource(must be inAllowedResources). A failure comes back asreturnUrl?error=<code>(e.g.access_denied). - User:
GET /bff/userwithX-CSRF: 1returns[{ "type": "...", "value": ... }]: the session's claims, oneroleper Authio role and onepermission(resource:method) per grant (from the*_resource_accessclaims, which need therolesscope),bff:session_expires_in(seconds) andbff:logout_url. Anonymous:401, never a redirect. - Log out: navigate to the
bff:logout_urlvalue (/bff/logout?sid=...), optionally with&returnUrl=/. The BFF revokes the refresh token, deletes the session and sends the browser to Authio's end-session endpoint withid_token_hint,post_logout_redirect_uriandstate. Without the rightsid(or theX-CSRFheader), a signed-in user cannot be logged out by another site. - Silent login (optional): load
/bff/silent-loginin a hidden iframe; the page posts{ source: "authio-bff-silent-login", isLoggedIn, error }to the parent (same origin only). - APIs: always send
X-CSRF: 1. A401means the session is gone: send the user to log in again.
Calling APIs
app.MapGet("/api/report", async (HttpContext context, IAuthioBffTokenService tokens) =>
{
var token = await tokens.GetUserAccessTokenAsync(context);
return token is null ? Results.Unauthorized() : Results.Ok();
})
.RequireAuthorization()
.AsAuthioBffApiEndpoint();
builder.Services.AddHttpClient("billing", client => client.BaseAddress = new Uri("https://billing.example.com"))
.AddAuthioBffUserToken(options => options.Resource = "https://billing.example.com");
app.MapAuthioRemoteApi("/api/inventory", "https://inventory.example.com", options =>
{
options.TokenMode = AuthioBffRemoteApiTokenMode.ClientCredentials;
options.Scopes.Add("inventory:read");
});
Remote API token modes: User (default; anonymous calls get 401), UserOrNone, ClientCredentials,
UserOrClientCredentials, None. With Resource or Scopes a user token is obtained by token exchange (the result
carries act). When a remote API answers 401 to a user call, the BFF introspects the session and signs the user out
if it ended. Upstream Set-Cookie headers are dropped.
Tokens for an API protected by Authio
An API protected with Authio.AspNetCore accepts only tokens addressed to it: their aud must be the resource
identifier it lists in Authio:Audiences. The session's token is addressed to the resource the sign-in asked for,
so request a token for the API:
Authio:Bff:Resource(or/bff/login?resource=…, allowed byAllowedResources) makes the session's token the API's:Usermode andAddAuthioBffUserToken()without aResourceforward it as is;Resourceon a remote API or a typed client exchanges the session's token for one addressed to that API.
Without either, the session's token is addressed to the BFF's own client and the API answers 401 with
error_description="The token is not addressed to this API: …". The BFF itself does not introspect the access token
it requested for a resource: Authio tells only the API's introspection client about that token (RFC 7662 §2.2) and
answers the BFF active: false. Keep offline_access in the scopes (the default) when you set Resource: the
session check (SessionValidation = Introspection) then introspects the refresh token, which stays addressed to the
BFF.
See docs/bff-api.md for the full
public API.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Authio.Client (>= 0.9.0)
- Microsoft.AspNetCore.Authentication.OpenIdConnect (>= 10.0.10)
- Yarp.ReverseProxy (>= 2.3.0)
-
net8.0
- Authio.Client (>= 0.9.0)
- Microsoft.AspNetCore.Authentication.OpenIdConnect (>= 8.0.31)
- Yarp.ReverseProxy (>= 2.3.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.