A hand-rolled BFF in .NET 10: cookie + OpenID Connect authentication with SaveTokens, server-side token refresh, YARP forwarding with a bearer-token transform, custom-header CSRF protection, and login, logout and user endpoints for a React SPA.
The BFF is an ASP.NET Core app on the SPA's origin. It uses cookie authentication as the default scheme and OpenID Connect as the challenge scheme, acting as a confidential client with the code flow and PKCE. SaveTokens = true keeps the access and refresh tokens inside the encrypted auth ticket (or a server-side ticket store), and a cookie event refreshes the access token before it expires.
YARP forwards /api/** to the downstream API: the route requires an authenticated user, and a request transform adds Authorization: Bearer <token> and strips the browser's cookie. CSRF is handled by a SameSite cookie plus a required custom header that cross-site requests cannot send.
The SPA gets three endpoints: /bff/login, /bff/logout and /bff/user. The trade-off is owning auth plumbing (refresh, logout, key management) in exchange for no tokens in the browser.
"The BFF has one job: be the OAuth client so the browser doesn't have to. I host it on the same origin as the React app. Authentication is two schemes: cookies by default and OpenID Connect for the challenge. OIDC runs the authorisation code flow with PKCE using a client secret or certificate, so the BFF is a confidential client. With
SaveTokenson, the access token and refresh token are stored in the authentication ticket, which ASP.NET Core encrypts with Data Protection into the HttpOnly cookie. If the ticket gets too big, or I want server-side revocation, I plug in anITicketStorebacked by Redis so the cookie only carries a session id.For API calls the SPA calls
/api/...on its own origin. YARP matches that route, requires an authenticated user, and a request transform reads the access token withGetTokenAsyncand sets theAuthorizationheader, while removing theCookieheader so the downstream API never sees our session. Tokens expire, so in the cookie'sOnValidatePrincipalevent I checkexpires_at; within a minute of expiry I call the token endpoint with the refresh token, update the stored tokens and setShouldRenewso a fresh cookie is issued. If refresh fails, I reject the principal and the SPA gets a 401. For example, at [company] we built this for [a React portal] and [an independent pen test found no token exposure]; the tricky part was concurrent refreshes from parallel requests, which we solved with [a per-session lock / rotation grace period].CSRF matters because cookies go automatically. I use a
__Host-cookie withSameSite=Strictand require anX-CSRFheader on every/apiand BFF call; a cross-site form can't add it, and a cross-origin fetch with it needs a preflight we never approve. The mistake I see is letting the OIDC handler answer an expired API call with a 302 to the identity provider:fetchfollows it and fails with a CORS error. API calls must get a clean 401 and the SPA redirects the whole page to/bff/login."
| Piece | Responsibility |
|---|---|
| Cookie scheme | Session for the browser; HttpOnly, Secure, SameSite, __Host- |
| OIDC scheme | Code flow + PKCE, confidential client, SaveTokens |
| Token refresh | OnValidatePrincipal refreshes before expiry |
| YARP | /api/** to the downstream API with bearer token, cookie stripped |
| CSRF guard | Requires X-CSRF header on /api and /bff |
/bff/login |
Challenge with a validated local returnUrl |
/bff/logout |
Sign out of cookie and OIDC (end session at the IdP) |
/bff/user |
Returns selected claims, never tokens |
| Option | When it fits | Cost |
|---|---|---|
| Hand-rolled (this code) | Team with OIDC experience, simple needs | Refresh races, logout, testing are yours |
| Duende BFF (v4) | Want back-channel logout, server-side sessions, tested refresh | Commercial annual licence above community thresholds |
For a React portal with [about 8,000 daily users] behind Azure Front Door, the BFF added about 3 to 5 ms per proxied call, the cookie stayed under 1 KB with a Redis ticket store, and moving tokens server-side closed the pen test's token-theft finding.
Checks whether a senior candidate can implement a BFF correctly and knows the production pitfalls, not just the diagram.
Green flags
SaveTokens and code flow as a confidential client__Host- cookiesRed flags
Login:
SPA ─► GET /bff/login?returnUrl=/orders ─► 302 to IdP /authorize (code + PKCE)
IdP ─► 302 /signin-oidc?code=... ─► BFF swaps code for tokens (with client secret)
BFF ─► Set-Cookie: __Host-bff=<encrypted ticket or session id> ─► 302 /orders
API call:
SPA ─► GET /api/orders (Cookie + X-CSRF: 1)
BFF ─► validate cookie ─► maybe refresh ─► YARP ─► GET https://orders-api/orders
Authorization: Bearer eyJ...
With SaveTokens, the OIDC handler writes access_token, refresh_token, id_token and expires_at into AuthenticationProperties. The cookie handler serialises the ticket, encrypts and signs it with Data Protection, and may split it into chunks if large. Two consequences: the cookie can reach 3 to 4 KB with big tokens, and every instance must share the Data Protection key ring (blob storage + Key Vault) or cookies from one instance fail on another. An ITicketStore (for example Redis) stores the ticket server-side and puts only a key in the cookie, which also allows server-side revocation.
The SPA often fires several requests at once. If each sees an expiring token and refreshes, a refresh-token rotation policy may treat the second use as reuse and revoke the whole family. Mitigations: refresh slightly early, serialise refresh per session (a lock keyed by session id in the ticket store), or rely on the identity provider's rotation grace period.
Cookies are ambient credentials. Defences, in layers:
SameSite=Strict (or Lax) stops cookies on most cross-site requests.fetch with custom headers triggers a CORS preflight that the BFF does not allow.The __Host- prefix forces Secure, Path=/ and no Domain, so a sibling subdomain cannot overwrite the cookie.
By default an unauthenticated request to a protected endpoint triggers the challenge scheme. For OIDC that is a 302 to the IdP, which fetch follows cross-origin and fails confusingly. Override OnRedirectToLogin on the cookie scheme or set a ForwardChallenge policy so /api gets 401 and /bff/login is the only place that challenges.
Sign out of the cookie scheme (clears the session) and the OIDC scheme (redirects to the IdP's end-session endpoint with id_token_hint). For a full solution, support back-channel logout so the IdP can end the BFF session when the user signs out elsewhere, and revoke the refresh token.
One extra hop per API call (typically low single-digit milliseconds in the same region), a stateful concern (keys or ticket store), and auth code your team owns. In return, no token is ever exposed to JavaScript.
Cookie header removal transform and log headers on the downstream API to see the session leak./api/orders from a page on another origin with credentials: 'include' and confirm the preflight or the CSRF check blocks it.A minimal hand-rolled BFF in .NET 10 with cookie + OIDC, server-side refresh, YARP forwarding and a CSRF guard.
// Program.cs (.NET 10) — packages: Microsoft.AspNetCore.Authentication.OpenIdConnect, Yarp.ReverseProxy
using System.Globalization;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Yarp.ReverseProxy.Transforms;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(o =>
{
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(o =>
{
o.Cookie.Name = "__Host-bff";
o.Cookie.HttpOnly = true;
o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
o.Cookie.SameSite = SameSiteMode.Strict;
o.ExpireTimeSpan = TimeSpan.FromHours(8);
o.Events.OnRedirectToLogin = ctx => { ctx.Response.StatusCode = 401; return Task.CompletedTask; }; // no 302 for fetch
o.Events.OnValidatePrincipal = TokenRefresher.RefreshIfExpiringAsync;
})
.AddOpenIdConnect(o =>
{
builder.Configuration.Bind("Oidc", o); // Authority, ClientId; secret from Key Vault / user-secrets
o.ResponseType = OpenIdConnectResponseType.Code; // code flow; PKCE is on by default
o.SaveTokens = true; // tokens stay in the encrypted server-issued ticket
o.Scope.Add("offline_access"); // refresh token
o.Scope.Add(builder.Configuration["Oidc:ApiScope"]!);
o.MapInboundClaims = false;
});
builder.Services.AddAuthorization();
builder.Services.AddHttpClient();
// Shared keys so any instance can read the cookie (blob + Key Vault in production).
builder.Services.AddDataProtection().SetApplicationName("orders-bff");
builder.Services.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
.AddTransforms(t =>
{
t.AddRequestHeaderRemove("Cookie"); // never forward the browser session downstream
t.AddRequestTransform(async ctx =>
{
var token = await ctx.HttpContext.GetTokenAsync("access_token");
if (token is not null)
ctx.ProxyRequest.Headers.Authorization = new("Bearer", token);
});
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
// CSRF guard: SPA calls must carry X-CSRF; cross-site forms cannot set it.
app.Use(async (ctx, next) =>
{
var guarded = ctx.Request.Path.StartsWithSegments("/api") || ctx.Request.Path.StartsWithSegments("/bff/user");
if (guarded && !ctx.Request.Headers.ContainsKey("X-CSRF")) { ctx.Response.StatusCode = 401; return; }
await next(ctx);
});
var bff = app.MapGroup("/bff");
bff.MapGet("/login", (string? returnUrl, HttpContext ctx) =>
TypedResults.Challenge(new AuthenticationProperties
{
RedirectUri = returnUrl is not null && Uri.IsWellFormedUriString(returnUrl, UriKind.Relative) && returnUrl.StartsWith('/') && !returnUrl.StartsWith("//")
? returnUrl : "/", // local URLs only: no open redirect
}));
bff.MapPost("/logout", () => TypedResults.SignOut(new AuthenticationProperties { RedirectUri = "/" },
[CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme]))
.RequireAuthorization();
bff.MapGet("/user", (ClaimsPrincipal user) =>
TypedResults.Ok(new BffUser(user.FindFirstValue("name"), user.FindFirstValue("email")))) // claims only, never tokens
.RequireAuthorization();
app.MapReverseProxy().RequireAuthorization();
app.MapFallbackToFile("index.html");
app.Run();
public sealed record BffUser(string? Name, string? Email);
public static class TokenRefresher
{
public static async Task RefreshIfExpiringAsync(CookieValidatePrincipalContext ctx)
{
var expiresAt = ctx.Properties.GetTokenValue("expires_at");
if (expiresAt is null || DateTimeOffset.Parse(expiresAt, CultureInfo.InvariantCulture) > DateTimeOffset.UtcNow.AddMinutes(1))
return;
var oidc = ctx.HttpContext.RequestServices
.GetRequiredService<Microsoft.Extensions.Options.IOptionsMonitor<OpenIdConnectOptions>>()
.Get(OpenIdConnectDefaults.AuthenticationScheme);
var config = await oidc.ConfigurationManager!.GetConfigurationAsync(ctx.HttpContext.RequestAborted);
var http = ctx.HttpContext.RequestServices.GetRequiredService<IHttpClientFactory>().CreateClient();
using var response = await http.PostAsync(config.TokenEndpoint, new FormUrlEncodedContent(new Dictionary<string, string>
{
["grant_type"] = "refresh_token",
["refresh_token"] = ctx.Properties.GetTokenValue("refresh_token") ?? "",
["client_id"] = oidc.ClientId!,
["client_secret"] = oidc.ClientSecret!,
}), ctx.HttpContext.RequestAborted);
if (!response.IsSuccessStatusCode)
{
ctx.RejectPrincipal(); // SPA gets 401 and sends the user to /bff/login
await ctx.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return;
}
var payload = new OpenIdConnectMessage(await response.Content.ReadAsStringAsync(ctx.HttpContext.RequestAborted));
ctx.Properties.UpdateTokenValue("access_token", payload.AccessToken);
if (!string.IsNullOrEmpty(payload.RefreshToken))
ctx.Properties.UpdateTokenValue("refresh_token", payload.RefreshToken); // rotation
ctx.Properties.UpdateTokenValue("expires_at",
DateTimeOffset.UtcNow.AddSeconds(int.Parse(payload.ExpiresIn, CultureInfo.InvariantCulture)).ToString("o", CultureInfo.InvariantCulture));
ctx.ShouldRenew = true; // re-issue the cookie with the new tokens
}
}
// appsettings.json (no secrets here)
{
"Oidc": { "Authority": "https://login.example.com.au/", "ClientId": "orders-bff", "ApiScope": "api://orders/orders.read" },
"ReverseProxy": {
"Routes": { "api": { "ClusterId": "orders", "Match": { "Path": "/api/{**rest}" }, "Transforms": [{ "PathRemovePrefix": "/api" }] } },
"Clusters": { "orders": { "Destinations": { "d1": { "Address": "https://orders-api.internal/" } } } }
}
}
// React side: the only auth code the SPA needs.
export async function getUser() {
const res = await fetch("/bff/user", { headers: { "X-CSRF": "1" } });
return res.ok ? ((await res.json()) as { name?: string; email?: string }) : null; // 401 = signed out
}
export const login = () => (window.location.href = `/bff/login?returnUrl=${encodeURIComponent(location.pathname)}`);
/api calls trigger the OIDC challenge. Why it is wrong: The challenge is a 302 to the identity provider; fetch follows it cross-origin and fails with a CORS error instead of a usable status. Instead: Make every API and BFF data endpoint return 401 (override OnRedirectToLogin and the forbidden redirect), and let the SPA navigate the whole page to /bff/login, the only endpoint that challenges.returnUrl back to the same screen.Cookie header downstream. Why it is wrong: It leaks the session to other services and logs. Instead: Strip it in a YARP transform and send only the bearer token./bff/user 'for convenience'. Why it is wrong: It undoes the whole pattern. Instead: Return only the claims the UI needs.returnUrl on login. Why it is wrong: It creates an open redirect. Instead: Allow only local paths.Writing this is not hard; operating it is. The parts that bite in production are refresh races, cookie size, key ring sharing across instances and slots, logout that actually ends the IdP session, and correct 401 behaviour for fetch. I write integration tests for each with WebApplicationFactory and a fake token endpoint before calling it done.
I would choose hand-rolled for a single SPA with a simple identity provider setup and a team that understands OIDC; I would buy Duende BFF (v4 as of November 2026, licensed annually, with a free community edition for qualifying small organisations) when I need server-side sessions, back-channel logout and multiple frontends, because those features are exactly where hand-rolled versions go wrong. Measure: added latency per proxied call (should be single-digit ms), cookie size, refresh failures per hour, and 401 rate after deploys.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Hand-rolled cookie + OIDC + YARP | One SPA, experienced team | Ownership of edge cases | Many frontends, back-channel logout needed |
| Duende BFF | Supported implementation, more features | Licence, vendor dependency | Tight budget for a small internal app (unless community edition applies) |
| Tokens in SPA + PKCE | Truly no server possible | Exposure to XSS theft | Personal or financial data |
| Session storage | When it fits | Cost |
|---|---|---|
| Encrypted cookie ticket | Small tokens, few claims | 2 to 4 KB cookies, no server-side revocation |
ITicketStore (Redis) |
Large tokens, revocation, back-channel logout | Redis dependency and availability |
For a strangler-fig migration, I put a new ASP.NET Core 10 app in front of the legacy ASP.NET Framework 4.8 app. Routes the new app implements are served locally; everything else is forwarded to the legacy app with YARP's MapForwarder as a lowest-priority catch-all. I migrate one vertical slice at a time, using System.Web adapters to share session and authentication, until the legacy app has no traffic and is switched off. Rollback is a route change.
For a backend-for-frontend, the SPA authenticates with an HttpOnly, SameSite cookie to the BFF; the BFF holds the OAuth tokens and attaches access tokens server-side when YARP forwards calls to the APIs, so no token ever reaches browser JavaScript.
The risks are extra latency, shared state coupling the two apps, CSRF on cookie-based calls, and the "temporary" proxy becoming permanent, so I set exit criteria up front.
Put a single identity provider in the middle (Entra External ID, Auth0 or a self-hosted OIDC server) that federates Google and Apple; every app speaks only OIDC to it, so adding a login provider never touches your code.
HttpOnly, SameSite cookie; it proxies API calls with an access token.The trade-off: a BFF adds a hop and state, in exchange for no tokens in the browser.
ASP.NET Core's Data Protection system encrypts auth cookies and antiforgery tokens with a key ring. By default each instance creates its own key ring on local disk, so a cookie protected by replica A cannot be decrypted by replica B, and every redeploy creates new keys. Fix it by persisting keys to a shared store (PersistKeysToAzureBlobStorage), protecting them at rest with Key Vault (ProtectKeysWithAzureKeyVault) and setting the same SetApplicationName on every instance. If the app uses session, back it with IDistributedCache (Redis) so any replica can read it. Sticky sessions only hide the problem: they break on scale-in, deploys and pod rescheduling, so treat them as a stopgap, not the fix.
How to tell it (STAR)
**S:** On [project], our BFF for [about 8,000] daily users started logging people out at random during [a campaign], right after autoscaling kicked in. **T:** As the owner of the auth layer I had to stop the logouts and make scale-out safe. **A:** Application Insights tied the 401s to new replicas, and the logs showed Data Protection unprotect failures: every replica had its own keys. I pinned to one replica as a stop-gap, then moved keys to Blob Storage with Key Vault protection, introduced a Redis ticket store that cut the cookie from about 3.8 KB to under 200 bytes, and added a cross-instance cookie test. **R:** Unexpected logouts went to [zero] at [4] replicas, and the header-size errors at Front Door disappeared.
Last updated 23 Nov 2026.