A browser app that calls an API with OAuth needs an access token, and for years the standard advice was to get it in the browser: authorization code flow with PKCE, the token in memory, a refresh token somewhere. It works, but it puts the most valuable thing the app has where any script in the page can reach it. Our articles on access and refresh tokens, refresh token rotation and DPoP all ended with the same suggestion: if you can, keep the tokens out of the browser entirely, with a backend for frontend.
That suggestion is now a standard. RFC 10017 (OAuth 2.0 for Browser-Based Applications, published in August 2026 as BCP 212) describes three ways to run OAuth for a browser app, ranks them, and puts the BFF first. This article explains the pattern, builds one in ASP.NET Core with an Angular app, tests it against the attacks it's meant to stop, and shows the one it can't. All the code is from a sample repo you can run, with an attack lab built in.
The short answer#
Why tokens in the browser are a problem#
The danger is the same one every browser-token design fights: script that isn't yours running in your page, through XSS, a compromised npm package, a browser extension, or a third-party widget. RFC 10017 spells out what such script can do with tokens in reach, in rising order of harm:
- Single-execution token theft (section 5.1.1): read the current access token from memory, storage or a request, and send it home. It works until it expires.
- Persistent token theft (5.1.2): steal the refresh token too, or keep stealing new tokens, so access lasts long after the page is closed.
- Acquiring new tokens (5.1.3): run its own silent sign-in in a hidden iframe and get a fresh set of tokens that the app never sees. RFC 10017 says there's no practical way for a browser-only app to prevent this one.
- Proxying requests via the user's browser (5.1.4): skip the tokens and call the API through the app while it's open.
Short-lived tokens, rotation and DPoP each blunt part of that list. Keeping tokens in memory instead of localStorage helps less than people hope: injected script can wrap fetch and read the Authorization header on the next call. The only way to remove the first three entirely is to make sure the browser never has a token, and that's the BFF.
Three patterns, ranked#
RFC 10017 section 6 describes three architectures, "presented in decreasing order of security":
| Pattern | Who holds the tokens | Stolen access token | Stolen refresh token | New tokens via silent sign-in | RFC 10017 says |
|---|---|---|---|---|---|
| Backend for frontend (6.1) | The BFF; the browser has a cookie | Nothing to steal | Nothing to steal | Stopped: the code needs the client secret | "strongly recommended for business applications, sensitive applications, and applications that handle personal data" |
| Token-mediating backend (6.2) | The backend gets them, hands the access token to the browser | Possible | Nothing to steal | Stopped | Lighter, but consider a full BFF first |
| Browser-based OAuth client (6.3) | The browser | Possible | Possible | Not stopped | "not recommended for business applications, sensitive applications, and applications that handle personal data" |
The fourth attack, proxying requests through the browser, applies to all three. We'll come back to it.
How a BFF works#
The sample has four parts: an Angular app, the BFF, an orders API, and a small OpenID Connect provider so it runs without an account anywhere. In development, the Angular dev server proxies /bff, /api and the sign-in callbacks to the BFF, so the browser sees one origin; in production you'd serve the app from the BFF or from the same site. Here's who holds what once you're signed in:
- one cookie: __Host-Http-bff
- HttpOnly: script can't read it
- no access token
- no refresh token
- no ID token
- the client secret
- a session per browser
- access, refresh and ID tokens
- the route allowlist
- the refresh lock
- the issuer's public key (JWKS)
- a Bearer access token per call
- never the cookie
- no idea a browser exists
Signing in is a page navigation. The app sends the browser to /bff/login, the BFF redirects to the identity provider, the user signs in there, and the provider redirects back to the BFF's callback with a code. The BFF exchanges the code for tokens, stores them, sets the cookie and sends the browser back to the app. From then on, an API call looks like this from the browser's side:
GET /api/orders HTTP/1.1
Host: app.example.com
Cookie: __Host-Http-bff=CfDJ8N3x...
X-CSRF: 1
HTTP/1.1 200 OK
Content-Type: application/json
[{"id":"ORD-1001","item":"Mechanical keyboard","quantity":1,"status":"Shipped"}]And like this from the API's side, after the BFF has done its part:
GET /api/orders HTTP/1.1
Host: api.internal
Authorization: Bearer eyJhbGciOiJFUzI1NiIsInR5cCI6ImF0K2p3dCJ9...
X-Forwarded-For: 203.0.113.7The browser's only "auth" code is a service that asks the BFF who's signed in and navigates to its login and logout URLs. There's no token storage, no refresh timer and no OAuth library:
@Injectable({ providedIn: 'root' })
export class SessionService {
private readonly http = inject(HttpClient);
readonly user = signal<BffUser | null>(null);
/** Asks the BFF whether there's a session ("check session" in RFC 10017, figure 1). */
async load(): Promise<BffUser | null> {
try {
this.user.set(await firstValueFrom(this.http.get<BffUser>('/bff/user')));
} catch (err) {
if (!(err instanceof HttpErrorResponse && err.status === 401)) throw err;
this.user.set(null);
}
return this.user();
}
/** A full-page navigation, so the BFF can redirect to the identity provider. fetch() can't follow that. */
login(returnUrl = '/'): void {
window.location.assign(`/bff/login?returnUrl=${encodeURIComponent(returnUrl)}`);
}
/** The logout URL carries a key from /bff/user, so another site can't sign you out with a link. */
logout(): void {
const user = this.user();
window.location.assign(user ? user.logoutUrl : '/');
}
}Sign-in: the BFF as a confidential client#
The BFF is a normal server-side web app as far as the identity provider is concerned, so ASP.NET Core's built-in OpenID Connect handler does the work. RFC 10017 (section 6.1.3.1) makes two requirements: the BFF MUST be a confidential client, with credentials registered at the authorization server, and MUST use the authorization code grant. We add PKCE too, as RFC 9700 recommends for every client:
.AddOpenIdConnect(BffDefaults.OidcScheme, o =>
{
o.Authority = bff.Authority;
o.RequireHttpsMetadata = bff.Authority.StartsWith("https:", StringComparison.OrdinalIgnoreCase);
o.ClientId = bff.ClientId;
o.ClientSecret = bff.ClientSecret; // confidential client (RFC 10017, section 6.1.3.1)
o.ResponseType = "code"; // authorization code flow...
o.UsePkce = true; // ...with PKCE
o.ResponseMode = "query"; // so the sign-in cookies can be SameSite=Lax instead of None
o.Scope.Clear();
foreach (var scope in bff.Scopes.Split(' ', StringSplitOptions.RemoveEmptyEntries)) o.Scope.Add(scope);
o.SaveTokens = false; // tokens go in the server-side session, not the cookie
// ...
o.Events.OnRedirectToIdentityProvider = ctx =>
{
ctx.ProtocolMessage.RedirectUri = bff.PublicOrigin + o.CallbackPath;
return Task.CompletedTask;
};
// ...
o.Events.OnTokenValidated = async ctx =>
{
// Signed in. Keep the tokens on the server and put only the session ID (and who it is) in the cookie.
var tokens = ctx.TokenEndpointResponse!;
var time = ctx.HttpContext.RequestServices.GetRequiredService<TimeProvider>();
var now = time.GetUtcNow();
var p = ctx.Principal!;
var session = new BffSession
{
Id = Base64UrlEncoder.Encode(RandomNumberGenerator.GetBytes(32)),
Subject = p.FindFirstValue("sub")!,
IdpSid = p.FindFirstValue("sid") ?? "",
IdToken = tokens.IdToken,
AccessToken = tokens.AccessToken,
RefreshToken = tokens.RefreshToken,
AccessTokenExpiresAt = now.AddSeconds(int.TryParse(tokens.ExpiresIn, out var s) ? s : 60),
CreatedAt = now,
ExpiresAt = now.AddHours(bff.SessionHours),
LogoutKey = Base64UrlEncoder.Encode(RandomNumberGenerator.GetBytes(16)),
};
await ctx.HttpContext.RequestServices.GetRequiredService<ISessionStore>().SetAsync(session);
ctx.Principal = new ClaimsPrincipal(new ClaimsIdentity(
[
new Claim("sub", session.Subject),
new Claim("name", p.FindFirstValue("name") ?? session.Subject),
new Claim("email", p.FindFirstValue("email") ?? ""),
new Claim(BffDefaults.SessionClaim, session.Id),
], "bff", "name", null));
};Three choices in there matter more than they look:
SaveTokens = false. By default, the handler can save the tokens in the authentication cookie, encrypted. That's a valid BFF design (RFC 10017 calls it a client-side session, and says to encrypt it), but the cookie then carries all three tokens and changes on every refresh. We store them on the server, under a random session ID, and the cookie holds only that ID and the user's name: 582 characters, about the size of one access token.- The redirect URI comes from configuration. Behind the Angular dev server, or any proxy, the request the BFF sees isn't the one the browser sent. Building
redirect_urifrom theHostheader is the same trap as DPoP'shtubehind a proxy; we use a configuredPublicOrigininstead. ResponseMode = "query". ASP.NET Core defaults toform_post, which means the identity provider POSTs the code back cross-site, and the handler's correlation and nonce cookies must beSameSite=Noneto survive it. With the code in the query string, a top-level redirect, they can beLax.
Because the BFF holds the secret, an authorization code is useless to anyone else. That's what closes the third attack: injected script can start a silent sign-in and even catch the code, but it can't exchange it.
The session cookie#
RFC 10017 section 6.1.3.2 lists the cookie settings, and they map directly onto ASP.NET Core's options:
.AddCookie(o =>
{
// RFC 10017, section 6.1.3.2. __Host- means Secure, Path=/ and no Domain, so no subdomain can set or read it;
// the newer __Host-Http- also tells browsers that know it to refuse it from JavaScript.
o.Cookie.Name = "__Host-Http-bff";
o.Cookie.HttpOnly = true;
o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
o.Cookie.SameSite = SameSiteMode.Strict;
o.Cookie.Path = "/";
o.ExpireTimeSpan = TimeSpan.FromHours(bff.SessionHours);
o.SlidingExpiration = false;
o.Events.OnRedirectToLogin = ctx => { ctx.Response.StatusCode = StatusCodes.Status401Unauthorized; return Task.CompletedTask; };
// ...
// The cookie is only a pointer: if the server-side session is gone (logout, back-channel logout, failed
// refresh, expiry), the cookie stops working too.
o.Events.OnValidatePrincipal = async ctx =>
{
var id = ctx.Principal?.FindFirstValue(BffDefaults.SessionClaim);
var store = ctx.HttpContext.RequestServices.GetRequiredService<ISessionStore>();
if (id is null || await store.GetAsync(id, ctx.HttpContext.RequestAborted) is null)
{
ctx.RejectPrincipal();
await ctx.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
};
})SecureandHttpOnlyare MUSTs.HttpOnlyis the whole point: page script can't read the cookie, so it can't send it anywhere. (Browsers treathttp://localhostas secure, which is why the sample's cookie works in development without HTTPS.)SameSite=Strictmeans the browser doesn't send it on requests started by another site, not even top-level navigations. That's fine for a BFF: after the sign-in redirect, the app loads and calls/bff/userwith fetch, a same-site request, and the cookie goes along.- The
__Host-prefix makes the browser refuse the cookie unless it'sSecure, hasPath=/and noDomain, so a sibling subdomain can't set or overwrite it. The RFC suggests the newer__Host-Http-, which also tells the browser the cookie must never be set from script; Chrome 140 and Firefox 143 support it, and older browsers still see the__Host-rules. OnValidatePrincipalchecks the server-side session on every request. The cookie is only a pointer, so logout, back-channel logout, an expired session or a failed refresh all end it immediately, even for a copy of the cookie.
CSRF: a header the browser won't forge#
A cookie-authenticated API is a CSRF target by definition: the browser attaches the cookie to requests other sites trigger. SameSite=Strict stops most of that, but not all. Sites are compared by registrable domain, so a.example.com and b.example.com are the same site, and a hijacked sibling subdomain can still send the cookie (RFC 10017, section 6.1.3.3.1). The RFC's answer is a custom header on every request:
// CSRF defense (RFC 10017, section 6.1.3.3.2): every API call and session check must carry a custom header. A
// cross-site form, link or image can't add one, and a cross-origin fetch that tries needs a CORS preflight, which
// this server never approves.
app.Use(async (ctx, next) =>
{
var path = ctx.Request.Path;
var guarded = path.StartsWithSegments("/api") || path.Equals("/bff/user");
if (guarded && ctx.Request.Headers[bff.CsrfHeader] != "1")
{
ctx.Response.StatusCode = StatusCodes.Status403Forbidden;
await ctx.Response.WriteAsJsonAsync(new { error = "csrf", message = $"Requests to the BFF need the {bff.CsrfHeader}: 1 header." });
return;
}
await next();
});/**
* Adds "X-CSRF: 1" to every call to the BFF. That's the whole client side of the CSRF defense (RFC 10017,
* section 6.1.3.3.2): a form, link or image on another site can't add a custom header, and a cross-origin fetch
* that tries needs a CORS preflight, which the BFF never approves. There's no token here, and nothing to store.
*/
export const csrfInterceptor: HttpInterceptorFn = (req, next) =>
isBffRequest(req.url) && !req.context.get(SKIP_CSRF_HEADER) ? next(req.clone({ setHeaders: { 'X-CSRF': '1' } })) : next(req);This works because of what the browser won't let another site do. A form, a link or an image can't add a header. A cross-origin fetch can, but a custom header makes it a "non-simple" request, so the browser first sends a CORS preflight, and the BFF, which never sends CORS headers, never approves it. RFC 10017 says the BFF MUST check the header on every incoming request, not only on state-changing ones, and we do: GETs to /api and the session check need it too.
The proxy: an allowlist, not a pipe#
The BFF forwards API calls with YARP, Microsoft's reverse proxy library. It's tempting to forward /api/{**rest} to the API and be done, but the BFF attaches a powerful token to whatever it forwards. RFC 10017 section 6.1.3.6 says it MUST only forward to explicitly allowed hosts and paths, so ours lists three routes, each with its method:
// The proxy, with an explicit allowlist of routes and methods (RFC 10017, section 6.1.3.6): the browser can reach
// these three API endpoints through the BFF, and nothing else, not even other paths on the same API.
builder.Services.AddReverseProxy()
.LoadFromMemory(
[
Route("profile", "/api/profile", "GET"),
Route("orders-list", "/api/orders", "GET"),
Route("orders-create", "/api/orders", "POST"),
],
[new ClusterConfig { ClusterId = "api", Destinations = new Dictionary<string, DestinationConfig> { ["api"] = new() { Address = bff.ApiUrl } } }])
.AddTransforms(t =>
{
t.AddRequestHeaderRemove("Cookie"); // the session cookie stays at the BFF
t.AddRequestHeaderRemove(bff.CsrfHeader);
t.AddResponseHeaderRemove("Set-Cookie"); // and the API can't set cookies on the app's origin
t.AddRequestTransform(ctx =>
{
if (ctx.HttpContext.Items[BffDefaults.AccessTokenItem] is string token)
ctx.ProxyRequest.Headers.Authorization = new("Bearer", token);
return ValueTask.CompletedTask;
});
});
// ...
// Every allowed API route: swap the cookie for the session's access token, refreshing it first if needed.
app.MapReverseProxy(proxy => proxy.Use(async (ctx, next) =>
{
var id = ctx.User.FindFirstValue(BffDefaults.SessionClaim);
var token = id is null ? null : await ctx.RequestServices.GetRequiredService<TokenManager>().GetAccessTokenAsync(id, ctx.RequestAborted);
if (token is null)
{
await ctx.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
await ctx.Response.WriteAsJsonAsync(new { error = "session_ended", message = "The session has ended. Sign in again." });
return;
}
ctx.Items[BffDefaults.AccessTokenItem] = token;
await next();
}));The transforms do the BFF's main job. The Cookie header is removed, so the session cookie never leaves the BFF; the access token goes in as Authorization: Bearer; and any Set-Cookie from the API is dropped, so the API can't plant cookies on the app's origin. In the sample, the API has a fourth endpoint, /api/internal/stats, that would accept the BFF's token; through the BFF, it's a 404, and DELETE /api/orders is a 405.
Refreshing once, on the server#
Access tokens are short-lived (two minutes in the sample, so you can watch it happen). When one is about to expire, the BFF refreshes it before forwarding the call. RFC 10017 (section 6.1.2.2) describes exactly that, and adds that if the refresh token stops working, the session should end.
The catch is concurrency. A page that loads with three tabs open can send ten API calls at once, all with an expiring token. With rotating refresh tokens, the first refresh spends the refresh token; a second refresh with the same token looks like theft to the identity provider, which revokes the whole family. So the refresh has to happen once, and everyone else has to wait for it:
/// <summary>The access token to forward, or null if the session is gone or can't be refreshed.</summary>
public async Task<string?> GetAccessTokenAsync(string sessionId, CancellationToken ct)
{
var seen = await store.GetAsync(sessionId, ct);
if (seen is null) return null;
if (!NeedsRefresh(seen)) return seen.AccessToken;
var gate = _locks.GetOrAdd(sessionId, _ => new SemaphoreSlim(1, 1));
await gate.WaitAsync(ct);
try
{
var current = await store.GetAsync(sessionId, ct);
if (current is null) return null;
// Another request refreshed while this one waited: use its token rather than refreshing again.
if (current.AccessToken != seen.AccessToken) return current.AccessToken;
var refreshed = await RefreshAsync(current, ct);
if (refreshed is null)
{
// The refresh token is spent, expired or revoked: the session is over (RFC 10017, section 6.1.2.2).
await RemoveAsync(sessionId, ct);
return null;
}
await store.SetAsync(refreshed, ct);
return refreshed.AccessToken;
}
finally
{
gate.Release();
}
}We checked that this matters. The test sends ten API calls at once while the token endpoint is slowed down, so they really overlap. With the lock, all ten succeed, the identity provider sees one refresh, and all ten requests reach the API with the same new token. With the lock removed, all ten refreshed with the same refresh token at once; the identity provider took the second use as theft and revoked the family, nine of the ten calls came back 401, and the session was over. With the lock but without the second check inside it, every waiting request refreshed again in turn: all ten succeeded, but with ten refreshes instead of one. The lock is per process; with several BFF instances, the thread-safe RTR article covers sharing it.
This is also where the BFF quietly fixes a browser problem. A browser-only app has to coordinate refreshes across tabs, which is notoriously fiddly. A BFF refreshes per session, on the server, so tabs don't need to know about each other at all.
Logout, both ways#
Signing out of the app has to end three things: the BFF's session, the cookie, and the user's session at the identity provider, or the next sign-in will skip the password. The app navigates to the logout URL from /bff/user:
// Ends the session here and at the identity provider. The key from /bff/user stops another site from signing the
// user out with a plain link (logout CSRF).
app.MapGet("/bff/logout", async (HttpContext http, ISessionStore store, TokenManager tokens, string? key) =>
{
var auth = await http.AuthenticateAsync();
var id = auth.Principal?.FindFirstValue(BffDefaults.SessionClaim);
var session = id is null ? null : await store.GetAsync(id);
if (session is null) return Results.Redirect("/");
if (key is null || !CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(key), Encoding.UTF8.GetBytes(session.LogoutKey)))
return Results.BadRequest(new { error = "logout_key", message = "Sign out with the logoutUrl from /bff/user." });
await tokens.RemoveAsync(session.Id);
var props = new AuthenticationProperties { RedirectUri = "/" };
props.Items["id_token_hint"] = session.IdToken;
return Results.SignOut(props, [CookieAuthenticationDefaults.AuthenticationScheme, BffDefaults.OidcScheme]);
});The key parameter is there because a plain GET /bff/logout would let any site sign your users out with an image tag (logout CSRF). The key is random per session and only the app can read it, from /bff/user, which needs the CSRF header. The ID token goes along as id_token_hint, so the identity provider knows which session to end and can trust the post_logout_redirect_uri.
The other direction matters just as much. If the user signs out at the identity provider, or an admin ends their session there, the BFF's session would otherwise live on for hours. OpenID Connect Back-Channel Logout fixes that: the identity provider POSTs a signed logout token to each app that used the session, server to server. The endpoint is public and takes no cookie, so the token's checks are all that protect it:
var o = oidc.Get(BffDefaults.OidcScheme);
var config = await o.ConfigurationManager!.GetConfigurationAsync(ct);
var result = await _handler.ValidateTokenAsync(logoutToken, new TokenValidationParameters
{
ValidIssuer = config.Issuer, // from our provider
ValidAudience = o.ClientId, // for us
IssuerSigningKeys = config.SigningKeys, // signed with its key, from the JWKS
ValidTypes = ["logout+jwt"], // not an ID token or access token replayed here
ValidAlgorithms = [SecurityAlgorithms.EcdsaSha256, SecurityAlgorithms.RsaSha256, SecurityAlgorithms.RsaSsaPssSha256],
ClockSkew = TimeSpan.FromSeconds(30),
});
if (!result.IsValid) return (null, $"invalid logout token: {result.Exception?.Message}");
var token = (JsonWebToken)result.SecurityToken;
if (!token.TryGetPayloadValue<Dictionary<string, object>>("events", out var events) || !events.ContainsKey(Event))
return (null, "the token has no back-channel logout event");
if (token.TryGetPayloadValue<string>("nonce", out _))
return (null, "a logout token must not have a nonce"); // so an ID token can't pass as one
if (!token.TryGetPayloadValue<string>("sid", out var sid) || string.IsNullOrEmpty(sid))
return (null, "the token has no sid"); // this BFF ends sessions by sid; the spec also allows sub alone
return (sid, null);We tried six forgeries: a token signed with another key, one for another client, one typed as a plain JWT, one without the logout event, one with a nonce, and the user's real ID token. All six were refused and the session survived; the genuine logout token ended it.
What we tested#
The sample's 15 integration tests run all three .NET apps in memory, each at its own HTTPS origin, and drive them like a browser: a cookie jar, real redirects and real HTML forms. Every snippet in this article is an unchanged excerpt of that repo, and our test script checks each one against it before running the tests.
| Test | Result |
|---|---|
| Sign in, then look for tokens in everything the browser received | None; the cookie is Secure, HttpOnly, SameSite=Strict, Path=/, no Domain |
| Call the API through the BFF | 200; the API saw the access token and no Cookie header |
The same calls without X-CSRF (GET, POST, session check) | 403 each; nothing created |
| A path and a method that aren't on the allowlist | 404 and 405; the API itself would have answered 200 |
| Call the API directly, with no token or with the ID token | 401 both times (the API requires typ: at+jwt) |
| Ten concurrent calls with an expiring token | One refresh; all ten used the same new token |
| Use a copied refresh token without the client secret | 401 invalid_client |
| Reuse a spent refresh token, with the secret | Family revoked; the BFF's next refresh failed and it ended the session (401) |
| Log out without the key, or with a guessed one | 400; still signed in |
| Log out properly, then replay the old cookie | 401; the identity provider asked for the password again |
| Sign out at the identity provider | Back-channel logout ended the BFF's session |
| Six forged logout tokens | All refused |
/bff/login?returnUrl=//evil.test; an unregistered redirect_uri; no PKCE | Stayed on the site; refused at the provider; invalid_request |
| Copy the session cookie to another client | 200: it works |
We also broke the BFF on purpose to check the tests notice: removing the Cookie strip, the CSRF check, the refresh lock, or the second check inside it each made a test fail.
What a BFF doesn't stop#
That last row is the first limit. A session cookie is a bearer credential too: whoever has it has the session. HttpOnly keeps it from page script, and SameSite and the CSRF header keep other sites from using it, but malware that reads the browser's cookie store can copy it and use it from elsewhere, until the session ends. RFC 10017 notes the same about encrypted cookies: encryption hides the tokens inside, not the cookie's power. Keep sessions as short as the refresh token's lifetime, end them on logout, and use back-channel logout so the identity provider can end them too.
The second limit is the one the RFC calls client hijacking. Script running in the page doesn't need a token: it can call /api/orders with the X-CSRF header, exactly like the app, and the BFF can't tell the difference. The sample's attack lab has a button for it, and it works: it places an order. RFC 10017 is blunt that "nothing will be able to prevent such attacks apart from stopping the execution of malicious code in the first place."
What the BFF changes is what the attacker leaves with. With tokens in the browser, the script steals them and keeps working after the tab is closed, from anywhere. With a BFF, there's nothing to take, so the attack lasts only while the page is open, and it runs through a server you control, where rate limits and anomaly detection can see it. The defenses against the script itself are the usual ones: a strict Content Security Policy, output encoding, and care with third-party code.
What it costs#
- A server in the path. Every API call makes an extra hop. For a BFF next to the app and the API, that's a little latency per call; for a static site on a CDN that called APIs directly, it's a new component to run, scale and keep up.
- State. Server-side sessions need a shared store and a shared Data Protection key ring once you have two instances, plus a lock or compare-and-set around refresh.
- All traffic passes through it. RFC 10017 points out the privacy side (the BFF sees every request and response, which matters if a third party runs it) and an operational one: to the API, every user now comes from the BFF's address, so IP-based rate limits need rethinking.
- Cross-origin APIs need the BFF too. If the app calls several APIs, each needs a route on the BFF and a token for its audience.
In return, the frontend gets simpler. The Angular app in the sample has no OAuth library and no token code at all, and the security-critical parts live in one server-side component that's easy to test.
BFF or DPoP?#
DPoP answers a different question: what if the token has to be in the browser? It binds the token to a key the browser can't export, so a stolen copy is useless elsewhere. In our DPoP tests, injected script could still sign proofs ahead of time unless the server used nonces; a BFF has no such gap, because there's nothing to sign or steal.
| Backend for frontend | DPoP in the browser | |
|---|---|---|
| Tokens in the browser | None | Yes, bound to a non-extractable key |
| Injected script can take something away | No | Proofs signed ahead, unless the server uses nonces |
| Injected script can use the session while the page is open | Yes | Yes |
| Needs a server you run | Yes | No |
| APIs called directly from the browser | No, all through the BFF | Yes |
| Client-side complexity | Almost none | Key storage, proofs, nonce retries |
They also combine. RFC 10017 section 6.1.3.7 notes that a BFF, being a server, can more easily adopt advanced practices such as key-based client authentication and sender-constrained tokens, so its own tokens can be DPoP-bound too. For a business app with a server anyway, start with the BFF; reach for DPoP in the browser when you can't run one.
FAQ#
Isn't a BFF just going back to cookies and sessions?
For the browser, yes, and that's the point: cookies have HttpOnly, which no JavaScript-visible storage can match. The difference from an old session-based app is behind the BFF: the APIs still use OAuth access tokens, short-lived and scoped, so they can be shared with other clients and services.
Can the BFF and the API be the same app?
Yes. RFC 10017 (section 6.1.2.5) mentions it: if the API lives in the same service, the BFF handles those requests directly instead of forwarding them. You still need the cookie settings and the CSRF header; you just skip the proxy for those routes.
Do I need YARP, or a library like Duende BFF?
Neither is required. The sample uses ASP.NET Core's own cookie and OpenID Connect handlers plus YARP, in about 500 lines with comments, to show every moving part. Packaged BFF libraries, such as Duende.BFF, do the same with less of your own code, and add server-side sessions and back-channel logout out of the box; check their license terms for commercial use.
What about mobile apps?
A BFF is a browser pattern, built around cookies. Native apps are public clients that can keep tokens in the platform keychain, which is far harder to read than a web page's memory; they use the authorization code flow with PKCE directly, as RFC 8252 describes.
How do I see what the identity provider's tokens contain?
The sample's BFF never shows them to the browser, but its tests and logs can. Paste one into our JWT decoder: an access token has typ: at+jwt and the API as its aud; a logout token has typ: logout+jwt, a sid and the back-channel logout event.
Get the code
- bff-sample on GitHub: the ASP.NET Core BFF, a small OpenID Connect provider and an orders API, an Angular app that never holds a token, 15 integration tests, and an attack lab with the four attacks a BFF stops and the one it can't.
Try it in your browser
- JWT Decoder, Encoder & Editor: decode the access, ID and logout tokens the sample's identity provider issues, to see their typ, aud, sid and events claims.