Backend for Frontend (BFF) Pattern with ASP.NET Core
On this page
Learning Objective
Explain why a browser-only OIDC client is the weakest place to hold tokens, design a backend-for-frontend that performs the OIDC flow and keeps tokens server-side, proxy API calls with YARP while attaching the access token, and expose a minimal session API to the React app.
Concept Explanation
When a React application performs the OIDC flow by itself, it becomes a public client. It cannot keep a secret, so it relies on PKCE alone, and it ends up holding an access token, and often a refresh token, in JavaScript memory or storage. Everything from Day 43 then applies: any script that runs in the page can reach those tokens. The refresh token is the most dangerous piece, because it lets an attacker mint new access tokens long after the user has left. The IETF's current guidance for browser-based OAuth applications names the backend-for-frontend, or BFF, as the most secure architecture, precisely because it removes tokens from the browser entirely.
A BFF is a small server-side application that sits between the browser and your APIs and acts as the confidential OIDC client. The browser talks only to the BFF. When the user signs in, the BFF runs the authorization code flow with its client secret, receives the tokens, and stores them in server-side state or in the encrypted session ticket. It gives the browser nothing but an HttpOnly, Secure, SameSite session cookie. When React calls an API endpoint, the request goes to the BFF at the same origin, which validates the cookie, attaches the user's access token as a bearer token, forwards the request to the real API, and streams the response back. Tokens are refreshed by the BFF when they near expiry, without the browser ever knowing.
This topology has several advantages beyond hiding tokens. Because the SPA, the BFF, and the proxied API paths share one origin, there is no cross-origin traffic, so CORS configuration disappears and cookies are first-party. The API can require bearer tokens and stay stateless and machine-friendly, while the BFF absorbs browser-specific concerns such as cookies, CSRF, and session lifetime. It also gives you one place to apply rate limiting, request logging, and header hygiene for browser traffic. The cost is one more component to deploy and secure, and the BFF must be treated as security-critical code.
In .NET the ingredients are ASP.NET Core cookie and OIDC authentication from Day 45, plus YARP, Yet Another Reverse Proxy, Microsoft's open source proxy library, to forward API calls with request transforms. Commercial libraries such as Duende BFF package the same pattern with extras. Whatever you use, implement a few endpoints for the SPA: one to start login, one to return the current user's claims, and one to sign out. Then guard the details. Validate the return URL to prevent open redirects. Require a custom header on API calls so a cross-site form cannot drive the proxy. Strip the browser's cookie before forwarding the request to the backend. And never send the access token to any destination other than the intended API.
| Concern | Token in the SPA | Backend-for-frontend |
|---|---|---|
| Where tokens live | JavaScript memory or storage | Server side only |
| Refresh token exposure | Reachable by XSS | Never leaves the server |
| Browser credential | Bearer token in headers | HttpOnly session cookie |
| CORS | Needed if API is cross-origin | Not needed, one origin |
| CSRF | Not applicable to headers | Must be handled, SameSite plus header check |
| Extra component | None | The BFF service to operate and secure |
Worked Example: A BFF with Session Endpoints and a Token-Attaching Proxy
The server below hosts the React static files, performs OIDC as a confidential client, exposes login, user, and logout endpoints, and proxies /api calls with YARP, attaching the access token and removing the browser's cookie.
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.Lax;
o.Events.OnRedirectToLogin = c => { c.Response.StatusCode = 401; return Task.CompletedTask; };
})
.AddOpenIdConnect(o => { /* as on Day 45: Authority, ClientId, ClientSecret from Key Vault, code + PKCE, SaveTokens = true */ });
builder.Services.AddAuthorization();
builder.Services.AddHttpContextAccessor();
// YARP forwards /api/* to the real API and adds the user's access token.
builder.Services.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
.AddTransforms(ctx =>
{
ctx.AddRequestTransform(async t =>
{
t.ProxyRequest.Headers.Remove("Cookie"); // the browser's session cookie stays here
var token = await t.HttpContext.GetTokenAsync("access_token"); // stored during sign-in
if (token is not null) t.ProxyRequest.Headers.Authorization = new("Bearer", token);
});
});
var app = builder.Build();
app.UseHttpsRedirection();
app.UseDefaultFiles();
app.UseStaticFiles(); // the built React app
app.UseAuthentication();
app.UseAuthorization();
// Session API used by React.
app.MapGet("/bff/login", (string? returnUrl) =>
{
var safe = !string.IsNullOrEmpty(returnUrl) && returnUrl.StartsWith('/') && !returnUrl.StartsWith("//") ? returnUrl : "/";
return Results.Challenge(new AuthenticationProperties { RedirectUri = safe }); // no open redirect
}).AllowAnonymous();
app.MapGet("/bff/user", (ClaimsPrincipal user) =>
user.Identity?.IsAuthenticated == true
? Results.Ok(new { name = user.FindFirstValue("name"), email = user.FindFirstValue("email") })
: Results.Unauthorized()).AllowAnonymous();
app.MapPost("/bff/logout", async (HttpContext ctx) =>
{
await ctx.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await ctx.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme); // also ends the provider session
return Results.NoContent();
}).RequireAuthorization();
// Only same-site JavaScript can add this header; a cross-site form or image tag cannot.
app.Use(async (ctx, next) =>
{
var isApi = ctx.Request.Path.StartsWithSegments("/api") || ctx.Request.Path.StartsWithSegments("/bff/logout");
var unsafeMethod = !HttpMethods.IsGet(ctx.Request.Method) && !HttpMethods.IsHead(ctx.Request.Method);
if (isApi && unsafeMethod && ctx.Request.Headers["X-CSRF"] != "1")
{
ctx.Response.StatusCode = StatusCodes.Status400BadRequest;
return;
}
await next();
});
app.MapReverseProxy().RequireAuthorization();
app.MapFallbackToFile("index.html"); // SPA routes
app.Run();{
"ReverseProxy": {
"Routes": { "api": { "ClusterId": "notes", "Match": { "Path": "/api/{**catch-all}" } } },
"Clusters": { "notes": { "Destinations": { "d1": { "Address": "https://notes-api.internal/" } } } }
}
}// React: it only ever learns who the user is, never holds a token.
export function useUser() {
return useQuery({
queryKey: ['user'],
queryFn: async () => {
const res = await fetch('/bff/user', { credentials: 'include' });
return res.ok ? await res.json() : null; // null means signed out
},
});
}
export const signIn = () => { window.location.href = `/bff/login?returnUrl=${encodeURIComponent(location.pathname)}`; };
export const signOut = () => fetch('/bff/logout', { method: 'POST', headers: { 'X-CSRF': '1' } }).then(() => location.assign('/'));The API behind the proxy is unchanged from Day 44: it validates bearer tokens and knows nothing about cookies. That separation is what lets the same API also serve mobile apps and machine clients.
Real-World Examples
- The IETF OAuth working group's draft on OAuth 2.0 for Browser-Based Applications describes several architectures and identifies the backend-for-frontend as the recommended pattern for applications that need the highest security, because tokens are not exposed to JavaScript. It reflects years of incidents and research on tokens stolen from browser storage.
- YARP is a reverse proxy toolkit built by Microsoft and released as open source, designed to be embedded in ASP.NET Core applications and customized in code, and Microsoft has described it as the foundation for reverse proxies inside several of its own services. Its request transforms are the mechanism this lesson uses to attach tokens and strip cookies, and the same library provides load balancing, health checks, and session affinity.
Review Questions & Answers
It removes tokens, especially the long-lived refresh token, from the browser environment. An XSS attack in an SPA can read tokens from memory or storage and use them from anywhere. With a BFF the browser holds only an HttpOnly cookie, so the attacker cannot exfiltrate a reusable credential and is limited to acting through the victim's open page.
The cookie is a credential meant only for the BFF. Forwarding it would send the session credential to another service, which does not need it and might log it or misuse it. The API authenticates with the bearer token the BFF attaches, so removing the cookie keeps each credential confined to the component that owns it.
Browsers do not let a cross-site form, image tag, or simple request add arbitrary custom headers, and adding one from another origin triggers a CORS preflight that the BFF never approves. Requiring the header on state-changing requests therefore proves the call came from JavaScript running on your own origin, defeating cross-site request forgery even though the session cookie is sent automatically.
If it redirects to whatever URL the caller supplies after sign-in, an attacker can craft a login link that ends at a malicious site while appearing to be your domain, which supports phishing and token or code theft in some flows. Accepting only local paths beginning with a single slash keeps the redirect within the application.