Backend-For-Frontend (BFF)
Introduction
The configured ProAuthBff:AuthenticationSettings:Authority must exactly match the provider's discovery issuer, including any trailing slash. The BFF rejects a mismatch before using discovered endpoints or signing keys. Update an authority alias to the provider's published issuer when migrating an existing configuration.
The Backend-For-Frontend (BFF) pattern is a security architecture that places an intermediary server between your Single Page Application (SPA) and your backend APIs. This pattern addresses fundamental security limitations of browser-based applications when handling OAuth 2.0 / OpenID Connect tokens.
Application-owned loading and error pages
ProAuth.Bff provides authentication endpoints and session handling; it does not ship a loading screen, branded error page, or product logo. Each consuming application owns its startup UI and styling. Authentication failure handling can redirect to /Error, so the host should provide an anonymous recovery page at that path. Keep that page independent of the SPA and protected APIs so it can render when initialization fails, and avoid displaying raw exception details.
The ProAuth AdminApp implements its startup screens in React and its standalone /Error page in Razor, with a shared application-owned stylesheet. This branding is not included in the redistributable BFF package.
Why Use a BFF?
Traditional SPAs store access tokens in browser storage (localStorage or sessionStorage), which exposes them to several attack vectors:
| Risk | Description |
|---|---|
| XSS Attacks | Malicious scripts can steal tokens from browser storage |
| Token Exposure | Tokens visible in browser developer tools and network requests |
| Limited Token Lifetime | Short-lived tokens require frequent refresh flows in the browser |
| Refresh Token Security | Storing refresh tokens in the browser is inherently insecure |
The BFF pattern solves these problems by:
- Keeping tokens server-side: Access and refresh tokens never reach the browser
- Using HTTP-only cookies: Session authentication via secure, HTTP-only cookies that JavaScript cannot access
- Server-side token injection: The BFF injects bearer tokens into API requests on behalf of the user
- Centralized token refresh: Automatic token refresh happens transparently on the server
Architecture
Getting Started
Prerequisites
- .NET 9.0 or later
- ASP.NET Core application
- A ProAuth tenant with a configured client application
Package Installation
Add the BFF package and your chosen token store provider:
# Core BFF package
dotnet add package ProAuth.Bff
# Choose ONE token store provider:
dotnet add package ProAuth.Oidc.Client.InMemory # Development/Testing
dotnet add package ProAuth.Oidc.Client.Redis # Production (distributed)
dotnet add package ProAuth.Oidc.Client.Dapr # Dapr-based deployments
dotnet add package ProAuth.Oidc.Client.ReaFx # ReaFx framework integrationClient authentication
With ClientAuthenticationMethod: Auto, a configured client secret selects ClientSecretBasic. The BFF sends those credentials in the HTTP Authorization header when redeeming an authorization code at the discovered token endpoint. This also works with DPoP enabled. Configure the same authentication method on the registered client application.
Basic Setup
Create a new ASP.NET Core application and configure the BFF in Program.cs:
using ProAuth.Bff.Extensions;
using ProAuth.Oidc.Client.InMemory;
var builder = WebApplication.CreateBuilder(args);
// Add health checks
builder.Services.AddHealthChecks();
// Add distributed cache for session support
builder.Services.AddDistributedMemoryCache();
// Add ProAuth BFF services
builder.Services.AddBff(builder.Configuration)
.WithInProcessLocking()
.WithInMemoryTokenStore()
.WithInMemoryTicketStore();
var app = builder.Build();
// Configure middleware pipeline
app.UseForwardedHeaders();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.MapControllers();
app.MapHealthChecks("/health");
// Map BFF reverse proxy routes
app.MapReverseProxy();
// SPA fallback
app.MapFallbackToFile("index.html");
app.Run();Configuration
The BFF is configured through the ProAuthBff section in your application settings.
Configuration Structure
{
"ProAuthBff": {
"SessionTimeoutInMinutes": 60,
"PasswordChangeUrlClaimType": "pwchangeurl",
"ForwardedHeaders": {
"UseForwardedHeaders": true,
"ForwardLimit": 1,
"KnownProxies": "",
"KnownNetworks": ""
},
"Routes": [],
"AuthenticationSettings": {
"Authority": "https://auth.example.com",
"ClientId": "my-spa-client",
"ClientSecret": "client-secret",
"ClientAuthenticationMethod": "Auto",
"ClientAssertion": {
"SigningAlgorithm": "RS256",
"Certificate": "<base64-pfx>",
"CertificatePath": null,
"CertificatePassword": "<pfx-password>",
"KeyId": "my-client-key",
"LifetimeInSeconds": 60
},
"MutualTls": {
"Certificate": "<base64-pfx>",
"CertificatePath": null,
"CertificatePassword": "<pfx-password>"
},
"TenantId": "my-tenant",
"PushedAuthorizationBehavior": "UseIfAvailable",
"RequestObject": {
"Enabled": false,
"SigningAlgorithm": "RS256",
"Certificate": "<base64-pfx>",
"CertificatePassword": "<pfx-password>",
"KeyId": "my-request-object-key"
},
"UserScopes": "openid profile offline_access",
"UserResources": "api://my-api"
},
"TlsCertificateValidation": {
"AcceptAnyServerCertificates": false,
"CustomTrustedRootCaFilePaths": [],
"CustomTrustedTlsCertificatePaths": []
},
"DataProtectionSettings": {
"ApplicationName": "MyBffApp",
"Enabled": false
},
"BackChannelLogout": {
"Enabled": false
},
"FrontChannelLogout": {
"Enabled": true
}
}
}General Settings
| Setting | Type | Default | Description |
|---|---|---|---|
SessionTimeoutInMinutes | int | 60 | Session idle timeout in minutes |
PasswordChangeUrlClaimType | string | "pwchangeurl" | Claim type for the password-change URL. Its scheme, host and port must match the configured authority. |
Forwarded Headers
The BFF package configures ASP.NET Core ForwardedHeadersOptions from ProAuthBff:ForwardedHeaders. Host applications should still call app.UseForwardedHeaders() before authentication, authorization, session, antiforgery, and BFF endpoints.
| Setting | Type | Default | Description |
|---|---|---|---|
ForwardedHeaders:UseForwardedHeaders | bool | true | Configures forwarded header processing options for BFF host applications |
ForwardedHeaders:ForwardLimit | int | 1 | Maximum number of forwarded header entries processed from each header |
ForwardedHeaders:KnownProxies | string | "" | Comma-separated trusted proxy IP addresses |
ForwardedHeaders:KnownNetworks | string | "" | Comma-separated trusted proxy CIDR ranges |
Back-Channel Logout
The BFF can receive OpenID Connect Back-Channel Logout notifications on POST /bff/backchannel-logout. This is optional and disabled by default.
{
"ProAuthBff": {
"BackChannelLogout": {
"Enabled": true
}
}
}When enabled, configure the client application in ProAuth with backchannel_logout_uri set to the public BFF endpoint, for example https://app.example.com/bff/backchannel-logout, and set backchannel_logout_session_required to true for interactive browser clients.
The endpoint expects the standard form POST shape logout_token=<jwt>, validates the token against the ProAuth issuer metadata and signing keys, rejects tokens with a nonce, rejects replayed jti values until token expiry, and removes matching local BFF authentication sessions by sid when present or by sub for subject-only logout tokens. Use a shared ticket store and distributed cache provider for multi-instance deployments so every instance can find and remove sessions created by another instance and enforce replay protection across pods.
Front-Channel Logout
The BFF can also receive OpenID Connect Front-Channel Logout notifications on GET /bff/frontchannel-logout. This endpoint is enabled by default and can be disabled with:
{
"ProAuthBff": {
"FrontChannelLogout": {
"Enabled": false
}
}
}Configure the client with frontchannel_logout_session_required enabled. The BFF requires both iss and sid and signs out only the browser session whose cookie matches the notification. If the browser blocks third-party cookies, use signed back-channel logout to terminate server-side sessions.
Authentication Settings
| Setting | Type | Required | Description |
|---|---|---|---|
Authority | string | Yes | ProAuth server URL (e.g., https://auth.example.com) |
ClientId | string | Yes | OAuth 2.0 client identifier |
ClientSecret | string | For secret-based methods | OAuth 2.0 client secret |
ClientAuthenticationMethod | string | No | Auto, None, ClientSecretPost, ClientSecretBasic, ClientSecretJwt, PrivateKeyJwt, TlsClientAuth, or SelfSignedTlsClientAuth. Auto uses ClientSecretBasic when a secret is configured and None otherwise. |
ClientAssertion.SigningAlgorithm | string | No | Signing algorithm for PrivateKeyJwt; defaults to RS256. |
ClientAssertion.Certificate | string | For PrivateKeyJwt unless CertificatePath is set | Base64 encoded PFX containing the assertion signing private key. |
ClientAssertion.CertificatePath | string | For PrivateKeyJwt unless Certificate is set | File path to a PFX containing the assertion signing private key. |
ClientAssertion.CertificatePassword | string | No | Password for the assertion signing PFX. |
ClientAssertion.KeyId | string | No | JWT header kid; should match a key in the client's ClientAssertionSigning key set. |
ClientAssertion.LifetimeInSeconds | int | No | JWT client assertion lifetime; defaults to 60 seconds. |
MutualTls.Certificate | string | For mTLS unless CertificatePath is set | Base64 encoded PFX presented to ProAuth for TlsClientAuth or SelfSignedTlsClientAuth. |
MutualTls.CertificatePath | string | For mTLS unless Certificate is set | File path to a PFX presented to ProAuth for mTLS. |
MutualTls.CertificatePassword | string | No | Password for the mTLS client certificate PFX. |
SecurityProfile | string | No | Set to Fapi2SecurityProfile to require the BFF-side FAPI 2.0 baseline. |
SenderConstrainedTokenMode | string | No | None, Dpop, or MutualTls. |
Dpop.JsonWebKey | string | No | Private JWK used for DPoP signing. When omitted, the BFF can generate an ephemeral process-local key. |
TenantId | string | No | ProAuth tenant identifier |
ProAuthIdp | string | No | Comma-separated provider IDs for explicit selection/filtering. |
ProAuthHiddenIdp | string | No | Comma-separated hidden provider IDs to include alongside visible providers. |
ProAuthInvitation | string | No | Invitation identifier; does not replace invitation validation. |
AdditionalAcrValues | string | No | Genuine authentication-context preferences. No legacy tenant hint is added automatically. Use dedicated settings for routing; see parameter migration. |
PushedAuthorizationBehavior | string | No | PAR behavior: UseIfAvailable, Disable, or Require. Defaults to UseIfAvailable. |
RequestObject.Enabled | bool | No | Enables JWT-secured authorization requests (JAR) for browser authorization flows. |
RequestObject.SigningAlgorithm | string | No | Asymmetric request-object signing algorithm. Defaults to RS256. |
RequestObject.Certificate | string | When JAR is enabled | Base64 encoded PFX containing the request-object signing private key. |
RequestObject.CertificateInput.CertificatePath | string | When JAR is enabled unless Certificate is set | File path to the request-object signing PFX. |
RequestObject.CertificatePassword | string | No | Password for the PFX certificate. |
RequestObject.KeyId | string | No | JWT header kid; should match the key registered on the ProAuth client app. |
AuthorizationRequestClaims | string | No | Raw OIDC claims request parameter JSON added to authorization requests. |
UserScopes | string | No | Space-separated scopes for user authentication (default: openid profile offline_access) |
UserResources | string | No | Space-separated resource identifiers |
ServiceScopes | string | No | Scopes for service-to-service authentication |
ServiceResources | string | No | Resources for service-to-service authentication |
Route Configuration
Routes define how the BFF proxies requests to your backend APIs:
{
"ProAuthBff": {
"Routes": [
{
"RouteId": "api-route",
"Path": "/api/{**catch-all}",
"Destination": "https://api.example.com",
"InjectToken": true,
"AccessTokenForwardingMode": "Automatic",
"TransparentProxy": false,
"RemoveRequestPrefix": true,
"AuthorizationPolicy": "default"
},
{
"RouteId": "public-route",
"Path": "/public/{**catch-all}",
"Destination": "https://api.example.com/public",
"AllowAnonymous": true,
"InjectToken": false
}
]
}
}InjectToken=true remains a compatibility shortcut for bearer forwarding when SenderConstrainedTokenMode is None. It is rejected for DPoP- or mTLS-bound tokens because presenting a sender-constrained token as an ordinary bearer token is unsafe. New routes should use AccessTokenForwardingMode: "Automatic":
| Mode | Behavior |
|---|---|
None | No access token is sent downstream. |
Bearer | Sends Authorization: Bearer <access_token>. |
Dpop | Sends Authorization: DPoP <access_token> and adds a DPoP proof for the proxied request. |
MutualTls | Sends Authorization: Bearer <access_token> through the configured mutually authenticated TLS connection. |
Automatic | Resolves to Bearer, Dpop, or MutualTls from SenderConstrainedTokenMode. |
For Fapi2SecurityProfile with PrivateKeyJwt, set AuthenticationSettings.Authority to the exact authorization-server issuer, including its path and trailing slash. The BFF uses that value as the scalar client assertion aud for PAR, authorization-code redemption, and automatic refresh. Requests still go to the discovered endpoints. A missing or blank authority fails explicitly. If an existing BFF session cannot renew tokens with invalid_client, verify the issuer value and upgrade the BFF/OIDC client packages together; keep the registered signing key and DPoP or mTLS configuration in place.
SenderConstrainedTokenMode is the only setting that activates DPoP. When SecurityProfile is Fapi2SecurityProfile, the BFF requires PAR, PKCE, secure client authentication, and either DPoP or mTLS sender-constrained tokens. Use AccessTokenForwardingMode: "Automatic" for routes that forward the access token obtained by the BFF so token acquisition and presentation cannot diverge.
The BFF validates route forwarding against the effective sender-constrained mode during startup. Explicit Bearer, Dpop, or MutualTls forwarding must match SenderConstrainedTokenMode; mismatches stop startup with a configuration error.
By default, BFF routes use API-client semantics. The downstream HTTP Host is derived from Destination, and the BFF removes inherited Forwarded, X-Forwarded-For, X-Forwarded-Host, X-Forwarded-Proto, and X-Forwarded-Prefix headers. This prevents browser-facing origin metadata from making a forwarded-header-aware API reconstruct a URI different from the actual API destination. ResponsePrefixMode: "XForwardedHeader" remains an explicit exception that sends the configured X-Forwarded-Prefix only.
Set TransparentProxy: true only when the destination intentionally treats the BFF URL as its public origin and needs YARP's standard forwarded-host, scheme, prefix, and client-address behavior. Transparent proxy mode is rejected for DPoP routes because the proof is bound to the configured Destination URI rather than the browser-facing BFF URI.
Route Options
| Setting | Type | Default | Description |
|---|---|---|---|
RouteId | string | Required | Unique identifier for the route |
Path | string | Required | URL pattern to match (supports {**catch-all} for wildcards) |
Destination | string | Required | Backend API base URL |
InjectToken | bool | false | Whether to inject the access token as a Bearer token |
AccessTokenForwardingMode | enum | None | How an injected access token is presented to the downstream API. Prefer Automatic for the token obtained by this BFF. |
TransparentProxy | bool | false | Forward browser-facing origin and client metadata using YARP's default forwarded headers. Enable only for an intentional transparent reverse-proxy route; it is incompatible with DPoP forwarding. |
AllowAnonymous | bool | false | Allow unauthenticated requests |
AuthorizationPolicy | string | null | ASP.NET Core authorization policy name |
RemoveRequestPrefix | bool | false | Remove the matched path prefix when forwarding |
PreventRedirectToLogin | bool | false | Return 401 instead of redirecting to login |
CustomHeaders | dict | {} | Custom headers to add to proxied requests |
ResponsePrefixMode | enum | None | How to handle response URL prefixes |
ResponseRewriteLinkHeaders | bool | false | Rewrite Link headers in responses |
ResponseRewriteXPaginationHeader | bool | false | Rewrite X-Pagination headers |
RewriteManifestWithCredentials | bool | false | Rewrite manifest files with credentials |
TLS Certificate Validation
For development or private CA scenarios:
{
"ProAuthBff": {
"TlsCertificateValidation": {
"AcceptAnyServerCertificates": false,
"CustomTrustedRootCaFilePaths": [
"/etc/ssl/certs/custom-ca.crt"
],
"CustomTrustedTlsCertificatePaths": [
"/etc/ssl/certs/custom-cert.crt"
],
"EnableFileSystemWatcher": true
}
}
}WARNING
Never set AcceptAnyServerCertificates to true in production environments.
Data Protection Settings
For multi-instance deployments, configure data protection to share authentication cookies:
{
"ProAuthBff": {
"DataProtectionSettings": {
"ApplicationName": "MyBffApp",
"Enabled": true,
"EncryptionKeys": {
"Mode": "X509",
"Certificate": "BASE64_ENCODED_CERTIFICATE",
"CertificatePassword": "certificate-password",
"KeyRotationDecryptionCertificates": [
{
"Certificate": "BASE64_ENCODED_OLD_CERTIFICATE",
"CertificatePassword": "old-password"
}
]
}
}
}
}Token Store Providers
The BFF requires a token store to persist user tokens between requests. Choose the appropriate provider based on your deployment scenario.
In-Memory Token Store
Package: ProAuth.Oidc.Client.InMemory
Best for development, testing, and single-instance deployments.
builder.Services.AddBff(builder.Configuration)
.WithInProcessLocking()
.WithInMemoryTokenStore()
.WithInMemoryTicketStore();WARNING
In-memory storage does not survive application restarts and cannot be shared across multiple instances. Use only for development or single-instance scenarios.
Protected Redis authentication tickets
Package: ProAuth.Oidc.Client.Redis
WithRedisTicketStore() encrypts and authenticates the complete authentication ticket with ASP.NET Core Data Protection, including saved access and refresh tokens. Protection is mandatory and bound to the application identity and the full Redis storage key. Copying a value to another session key does not authenticate that session. Invalid, modified, foreign-application and unprotected values are treated as missing sessions.
For BFF tokens scoped to each browser session, combine the protected ticket store with WithAuthSessionTokenStore() and Redis distributed locking:
using Microsoft.AspNetCore.DataProtection;
using ProAuth.Bff.Extensions;
using ProAuth.Oidc.Client.AspNetCore;
using ProAuth.Oidc.Client.Redis;
// Share session/logout indexes and replay state across replicas too.
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration.GetConnectionString("BffRedis");
options.InstanceName = "orders-production:cache:";
});
var bff = builder.Services.AddBff(builder.Configuration);
bff.WithRedisDistributedLocking()
.WithAuthSessionTokenStore()
.WithRedisTicketStore();
// Uses Microsoft's Redis key-ring implementation. Configure a persistent Redis
// instance and protect the key ring with an application-controlled certificate.
bff.DataProtectionBuilder
.PersistKeysToRedisCache(options =>
{
options.ConnectionString = builder.Configuration.GetConnectionString("DataProtectionRedis");
options.KeyPrefix = "orders-production:data-protection";
})
.ProtectKeysWithCertificate(keyEncryptionCertificate);keyEncryptionCertificate is an X509Certificate2 loaded from your deployment's certificate store or secret provider. Every replica needs its private key. The certificate must be available before building the application. A persistent shared filesystem or another supported ASP.NET Core key repository can be used instead of Redis.
Configure connection strings through your deployment's secret provider. The following illustrates the configuration shape:
{
"ConnectionStrings": {
"DataProtectionRedis": "redis-keys:6379,ssl=true,password=<secret>",
"BffRedis": "redis:6379,ssl=true,password=<secret>"
},
"ProAuthBff": {
"DataProtectionSettings": {
"ApplicationName": "orders-production"
},
"Redis": {
"DistributedLock": {
"ConnectionString": "redis:6379,ssl=true,password=<secret>",
"KeyPrefix": "orders-production:locks:"
},
"TicketStore": {
"ConnectionString": "redis:6379,ssl=true,password=<secret>",
"ApplicationName": "orders-production",
"KeyPrefix": "orders-production:tickets:"
}
}
}
}Redis:TicketStore:ApplicationName is required and has no shared default. Use a stable, unique value for each application and environment, shared by all of its replicas. DataProtectionSettings:ApplicationName sets the Data Protection application discriminator; configure it consistently too. The ticket options can also be supplied through WithRedisTicketStore(options => { ... }). Direct construction of RedisTicketStore now requires an IDataProtectionProvider in addition to its options; dependency injection supplies it automatically.
Replicas must share the ticket database, both application names, key prefix, Data Protection key ring, key-encryption certificate/private key, shared distributed cache, and distributed lock configuration. Use compatible ASP.NET Core Data Protection versions. Retain old Data Protection keys and the certificates needed to decrypt them for as long as their tickets can remain valid. Normal key rotation keeps existing sessions readable; deleting or revoking their keys, losing the key ring, or changing either application name invalidates them. Application names isolate payloads within the configured trust boundary; applications that are not mutually trusted should have separate key repositories and credentials.
Protect the key ring at rest, especially when it is persisted in Redis alongside tickets. An attacker with both unencrypted Data Protection keys and ticket values can decrypt tickets. Use Redis authentication, TLS, access controls and durable key-ring storage. The older PersistDataProtectionKeysToRedis() helper uses a different repository format; do not point the Microsoft-backed PersistKeysToRedisCache() helper at its existing key. Moving repositories without preserving key material invalidates existing protected cookies and tickets. See Microsoft's Data Protection configuration guidance for key persistence, isolation and encryption options.
Ticket expiry remains stored in Redis as an absolute TTL and is checked again inside the protected ticket. Renewal protects the updated ticket and updates its TTL. Removal, session-token updates and back-channel logout continue through the existing ticket-store integration. Cancellation prevents commands from being submitted when already cancelled and interrupts waits for Redis; a command already submitted may still complete.
Migration from unprotected Redis tickets
The first release containing protected Redis tickets intentionally invalidates tickets written by ProAuth 3.3.0 and earlier unprotected implementations. There is no plaintext migration option and no fallback to raw ticket deserialization after protection fails. Users must sign in again. This policy also applies to custom ticket formats unless they implement this package's protected format; do not assume reference/custom ticket stores are interchangeable.
Before upgrading, configure the required ticket application name and durable Data Protection key ring. Drain old replicas and deploy the new package to all replicas together; old and new writers must not share a live ticket namespace during a rolling deployment. Prefer a fresh application-specific ticket prefix and remove the old ticket namespace after the old deployment is drained, including legacy tickets with no TTL. Remove only that application's old ticket keys, not the shared Redis database or key ring. A rollback cannot read the new protected tickets and requires another sign-in cutover. Existing cookies, including those pointing at old ticket keys, will fail authentication and users must sign in again.
Separate Redis token storage
WithRedisTokenStore() remains available for applications that need a separate token store. Its Redis:TokenStore:DataProtectionEnabled setting is independent of ticket protection and should remain enabled. DataProtectionSettings:Enabled and Redis:TokenStore:DataProtectionEnabled do not disable protected tickets. To keep BFF user tokens inside the protected, session-bound ticket, use WithAuthSessionTokenStore() as shown above.
Dapr Token Store
Package: ProAuth.Oidc.Client.Dapr
For applications using Dapr for state management.
builder.Services.AddBff(builder.Configuration)
.WithDaprLocking()
.WithDaprTokenStore()
.WithDaprTicketStore();Requires Dapr state store component configuration.
ReaFx Token Store
Package: ProAuth.Oidc.Client.ReaFx
For applications built with the ReaFx framework.
builder.Services.AddBff(builder.Configuration)
.WithReaFxLocking()
.WithReaFxTokenStore()
.WithReaFxTicketStore();INFO
ReaFx integration is available separately for licensed ReaFx customers. Contact your account representative for more information.
Auth Session Token Store
Package: ProAuth.Oidc.Client.AspNetCore
Stores tokens in the server-side authentication ticket, with only a protected session reference in the browser cookie. A ticket store is required; cookie-only configuration is rejected when the cookie authentication options are initialized.
builder.Services.AddBff(builder.Configuration)
.WithInProcessLocking()
.WithAuthSessionTokenStore()
.WithInMemoryTicketStore();For multiple instances, use a shared Redis, Dapr, or ReaFx ticket store and its matching distributed lock provider on every instance. In-process locking and in-memory tickets are suitable only for a single instance.
Initial and refreshed tokens use the same 30-second refresh margin, while the ticket’s expires_at retains the actual access-token expiry. The token store reloads the authoritative session ticket after acquiring the refresh lock instead of relying on ASP.NET Core's request-cached authentication result. Token writes, sliding cookie renewal, and logout coordinate through the configured lock provider. A late response preserves newer tokens, and a refresh finishing after logout cannot recreate the removed session. A new sign-in establishes a new session generation so requests from the previous sign-in cannot overwrite its tokens or renew its old ticket. Separate sessions for the same user retain separate tokens.
Access-token expiry and the refresh schedule do not end a browser session. While the ticket remains valid, its refresh grant can obtain another access token, subject to the provider's grant policy. Ticket expiration or logout withdraws the session's credentials even if a refresh is in flight; a late result cannot renew an expired or removed session. Sliding session renewal follows the cookie policy and is separate from token refresh.
Choose this store for tokens owned by a browser login. External BFF stores also use login-specific keys, but their physical retention policies differ from the ticket lifetime. Direct standalone subject-keyed stores require application-owned isolation and removal coordination. See refresh timing, retention and store selection. For step-up, keep replacement tokens and assurance tied to the intended login; sharing a subject key across browser sessions is not session isolation.
When upgrading a cookie-only WithAuthSessionTokenStore() configuration, add a ticket store as shown above. The in-memory ticket store now returns independent ticket snapshots, matching distributed stores; mutate a retrieved ticket and call RenewAsync to persist a change.
Authentication Endpoints
The BFF package automatically registers authentication controllers:
| Endpoint | Method | Description |
|---|---|---|
/bff/account/login | GET / POST | Starts an OIDC login through an antiforgery-protected POST |
/bff/account/logout | GET | Displays the sign-out choices |
/bff/account/logout | POST | Performs the selected logout mode after antiforgery validation |
/signout-callback-oidc | GET | OIDC sign-out callback |
/bff/user | GET | Returns current user information, including isAuthenticated. Responses use Cache-Control: no-store. |
Frontend Integration
Your SPA can check authentication status and user info:
const response = await fetch('/bff/user', { credentials: 'same-origin' });
if (response.ok) {
const userInfo = await response.json();
if (userInfo.isAuthenticated) {
console.log('User:', userInfo);
} else {
// Render a Sign in link to /bff/account/login.
console.log('Signed out');
}
}Advanced Configuration
HTTP handler customization
AddBff supplies back-channel transports with automatic redirects and cookie handling disabled (AllowAutoRedirect = false, UseCookies = false). This covers the middleware's discovery/signing-key retrieval, PAR, authorization-code redemption and userinfo, plus the named OAuth/discovery clients used for renewal and other protocol calls. No transport casts or handler-chain traversal are required. Certificate validation, configured client certificates, client authentication, DPoP proofs and nonce retries remain in place.
Use direct protocol endpoint URLs: a redirect response is unsuccessful and is not followed, even within the same origin. Back-channel Set-Cookie headers are not retained or replayed. Browser sign-in/sign-out redirects and the BFF's session, correlation, nonce and antiforgery cookies keep their existing behavior. When upgrading from 3.3.0, remove patches that changed internal handler flags and remove any reliance on redirected endpoints or upstream cookie sessions. See the transport customization contract and compatibility details.
Attach DI-resolved handlers to the BFF's renewal and OAuth client after registering the BFF:
using Microsoft.Extensions.DependencyInjection;
using ProAuth.Bff.Extensions;
services.AddBff(configuration);
services.AddTransient<MyObserver>();
services.AddHttpClient("OidcClient")
.AddHttpMessageHandler<MyObserver>();This covers OAuth calls made by IOidcClient, including token refresh and renewal requested through ITokenHandler. Register handlers in the desired request order; responses pass through them in reverse order. See client names, discovery coverage, transport customization and handler lifetimes.
The ASP.NET Core OpenID Connect back channel remains a separate integration point. The registration above does not observe the middleware's interactive login discovery, authorization-code redemption, PAR or userinfo calls. To observe those too, configure the named OpenIdConnectOptions for OpenIdConnectDefaults.AuthenticationScheme after AddBff, wrapping the existing BackchannelHttpHandler before the middleware creates its Backchannel. Preserve the existing inner chain: it carries TLS/client-certificate settings, client authentication and DPoP/nonce processing. Do not replace it with the "OidcClient" pipeline. The BFF reverse proxy and resource-server JWT bearer metadata retrieval also have separate transports.
Custom Token Processing
You can add custom processing when tokens are validated:
builder.Services.AddBff(builder.Configuration,
configureAuthenticationOptions: options =>
{
options.CustomTokenProcessing = async (context, logger) =>
{
// Add custom claims or perform additional validation
var identity = (ClaimsIdentity)context.Principal.Identity;
identity.AddClaim(new Claim("custom_claim", "custom_value"));
logger.LogInformation("Token validated for user {User}",
context.Principal.Identity.Name);
};
});Programmatic Configuration
All configuration can also be done programmatically:
builder.Services.AddBff(
builder.Configuration,
configureBffOptions: options =>
{
options.SessionTimeoutInMinutes = 120;
options.Routes.Add(new BffRouteOptions
{
RouteId = "api",
Path = "/api/{**catch-all}",
Destination = "https://api.example.com",
InjectToken = true,
TransparentProxy = false
});
},
configureAuthenticationOptions: options =>
{
options.Authority = "https://auth.example.com";
options.ClientId = "my-client";
options.ClientSecret = "secret";
});Optional HTTP/2 request buffering
The BFF streams proxy requests by default. Applications forwarding small, finite request bodies can opt into bounded buffering to support the HTTP client's automatic recovery when an HTTP/2 peer explicitly reports a request as unprocessed during connection retirement.
Register this after AddBff and after any custom YARP HTTP client factory configuration:
builder.Services.AddBff(builder.Configuration);
builder.Services.AddBffHttp2RequestBuffering(maxBufferedRequestBodySize: 64 * 1024);This retains the existing TLS configuration, connection pooling, and HTTP version policy. It does not introduce endpoint-specific rules or a retry policy for HTTP errors. Requests with an ambiguous processing outcome remain failed; a lost response must not trigger an automatic repeat of a write. Custom HTTP handlers must also respect this restriction.
Buffering applies only to requests configured for HTTP/2 whose positive Content-Length fits the limit. Unknown-length, larger, chunked, gRPC, CONNECT, upgrade, trailer-bearing, and Expect: 100-continue requests retain streaming behavior and are not covered by this recovery mechanism. No response buffering is added.
The complete eligible body is read before contacting the destination. The limit is per request, not a process-wide memory limit; account for concurrent requests and buffer overhead when choosing it. Keep the limit small. A declared length mismatch or input failure is rejected rather than forwarding a partial buffered body. Omit the registration to retain default behavior.
Security Considerations
Cookie Security
The BFF uses secure, HTTP-only cookies with the following defaults:
HttpOnly: Prevents JavaScript accessSecure: Only sent over HTTPSSameSite=None: Required for cross-origin scenarios (OIDC flows)
CSRF Protection
MapProAuthBff() requires X-ProAuth-BFF: 1 on every proxied request except GET, HEAD, and OPTIONS. If an Origin header is present, it must match the BFF request's scheme and host. A missing intent header or a foreign origin returns HTTP 403 before token injection or forwarding. This protects cookie-authenticated proxy writes, including bodyless commands, from HTML form submissions and cross-origin scripts. Keep the BFF and SPA on the same origin and configure trusted forwarded headers before routing when TLS terminates at a reverse proxy.
fetch('/api/data', {
method: 'POST',
headers: { 'X-ProAuth-BFF': '1', 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify(data)
});The React AdminApp supplies the header through its shared authenticatedFetch adapter. Other BFF consumers must add it to their API write transport. The header is an explicit browser intent marker, not an authentication token. Server authorization remains mandatory. OIDC callbacks and local MVC endpoints use their existing protocol/MVC protections; the proxy rule does not replace those protections.
Preventing Open Redirects
The BFF validates redirect URLs to prevent open redirect attacks. Only relative URLs and URLs to the configured authority are allowed.
Troubleshooting
Common Issues
401 Unauthorized on API calls
- Verify the route has
InjectToken: true - Check that the user is authenticated
- Verify the access token hasn't expired
Cookie too large errors
- Use a ticket store to reduce cookie size
- See Auth Session Token Store recommendations
CORS errors
- The BFF should be served from the same origin as your SPA
- Verify your reverse proxy or hosting configuration
Token refresh failures
- Ensure
offline_accessscope is requested - Verify refresh tokens are enabled for your client in ProAuth
See Also
- OIDC Client Library - Core OIDC operations
- Client Applications - Configure clients in ProAuth
Browser sign-out confirmation
GET /bff/account/logout displays a confirmation form and leaves the session active. The form submits to POST /bff/account/logout, which requires a valid ASP.NET Core antiforgery token and accepts returnUrl as a form field. The optional logoutMode form field selects the behavior.
| Form value | What happens |
|---|---|
app | Ends this browser’s local BFF session and requests revocation of its access and refresh tokens at the OAuth revocation endpoint. The browser can use its existing SSO session to sign in again. |
sso or omitted | Clears the local session and sends the browser to the identity provider’s OpenID Connect end-session endpoint. The provider handles confirmation and any configured logout notifications. |
Submit the form after the user chooses an action. The BFF handles logoutMode locally. Use a public landing page for returnUrl if the user should see a signed-out state. A protected page can immediately start a fresh sign-in through the existing SSO session.
If another tab signs in to a different ProAuth tenant, the browser’s current IdP session can differ from the session identified by the application’s ID token. Choosing SSO logout still ends the local BFF session. ProAuth keeps the current browser session and leaves the requesting application’s IdP session and tokens subject to their existing lifetimes. The sign-out page offers a link to the application’s origin when the request contains a validated HTTPS logout callback. Otherwise, reopen the application from its usual address.
New BFF logins have separate token-store entries, including when the same user signs in from two browsers. Upgrade all BFF instances serving an application together if they share an external token store. Older versions look up tokens by subject.
App-only sign-out closes the local session before contacting the provider. When a refresh overlaps sign-out and its lock lease expires, the BFF returns HTTP 503 and attempts to revoke any credentials the refresh subsequently receives. HTTP 503 means the provider may still accept a token. The BFF also returns 503 if the provider is unavailable, the current token-store entry is missing, or another login has replaced a shared entry created before the upgrade.
Customize the confirmation page
Applications can supply an MVC Razor view to use their own branding, layout and translated text. Configure its name through ProAuthBff:LogoutConfirmationViewName or the existing AddBff callback:
builder.Services.AddBff(builder.Configuration, configureBffOptions: options =>
{
options.LogoutConfirmationViewName = "~/Views/Account/Logout.cshtml";
});Add the view to the host application's ASP.NET Core web project. AddBff already registers MVC view support. This is a controller view, so do not add an @page directive:
@model ProAuth.Bff.Models.LogoutConfirmationViewModel
@{ Layout = "_Layout"; }
<h1>Sign out</h1>
<p>Choose whether to also end your single sign-on session.</p>
<form method="post" action="@Model.LogoutAction" asp-antiforgery="false">
<input type="hidden" name="returnUrl" value="@Model.ReturnUrl" />
<input type="hidden" name="@Model.AntiforgeryFieldName" value="@Model.AntiforgeryToken" />
<button type="submit" name="logoutMode" value="app">Sign out of this app</button>
<button type="submit" name="logoutMode" value="sso">SSO logout</button>
<a href="@Model.ReturnUrl">Cancel</a>
</form>Use your application's layout or set Layout = null and supply a complete HTML document. The BFF provides a path-base-aware LogoutAction, a validated local ReturnUrl, and the antiforgery field name and token. Use normal Razor expressions so values remain HTML-encoded. The example disables automatic form-tag-helper token generation because the model already supplies the token.
The custom view is rendered at the existing authenticated GET endpoint. It must require an explicit user action to POST; cancelling must only navigate. The BFF continues to validate antiforgery tokens and return URLs on POST, and sends Cache-Control: no-store and X-Frame-Options: DENY for the confirmation response.
Custom views use the host application's content security policy, including policies configured through AddBffSecurity. Permit the assets your layout needs, restrict form submission to trusted destinations, and disallow framing. The built-in page retains its restrictive policy. Leaving the view name unset or blank keeps the built-in page; a configured view that cannot be found produces an MVC view-resolution error.
ProAuth Administration uses this setting to share the branding and light/dark styling of its server error page without loading the SPA.
API authentication assurance
See API authentication assurance and step-up for opt-in client policies, verified token evidence, RFC 9470 challenges and bounded BFF reauthentication.