Back to all posts
·8 min read

Keeping tokens out of the browser: the BFF pattern for SPA authentication

Authentication in single-page applications (SPAs) often starts like this: the user signs in, an access token arrives from the identity provider, the token is written to localStorage and attached to every API call as an Authorization header. It works, it is quick to set up, and nobody touches it for a long time.

The problem is that this setup makes security depend entirely on the JavaScript inside the page staying clean. In this post I look at the Backend for Frontend (BFF) pattern, which removes tokens from the browser altogether, how to build it with ASP.NET Core, and the trade-offs it brings. The examples apply equally to React and Angular; very little changes on the frontend side.

Where should the token live in the browser

localStorage and sessionStorage can be read by every script running on the page. An XSS vulnerability, a malicious third-party package or a compromised analytics script can read the token and send it somewhere else. Once the token is out, it is a valid identity in the attacker's hands until it expires.

Keeping the token only in memory reduces this risk but does not remove it; code running on the page can still observe fetch calls or use the token to send requests. On top of that, the session is lost when the page reloads. Solving that means keeping the refresh token in the browser too, which puts a much longer-lived secret in the same risky environment.

The conclusion is simple: the browser is not a good place to store long-lived secrets. We need a storage location that does not require trusting the code inside the page.

The BFF pattern: keeping tokens on the server

In the BFF pattern, a small server component dedicated to that frontend sits between the SPA and the APIs. This server runs the OpenID Connect flow with the identity provider and receives and stores the tokens itself. The browser only gets a session cookie; since that cookie is HttpOnly, JavaScript cannot read it.

When the SPA makes an API call, it sends the request to its own origin, that is, to the BFF. The BFF resolves the session from the cookie, finds the matching access token and forwards the request to the backend API with an Authorization header. The backend APIs do not change; they are still ordinary APIs that expect a bearer token.

In this setup XSS does not become completely harmless: malicious code on the page can still send requests on the user's behalf while the user is on the page. But it cannot steal the token and use it from another machine, independently of the user and for a long time. The attack surface shrinks from "permanently taking over the identity" to "sending requests while the page is open".

Cookies and OpenID Connect in ASP.NET Core

In ASP.NET Core, the pieces needed for a BFF ship with the framework: cookie authentication and the OpenID Connect handler.

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
    options.Cookie.Name = "__Host-app";
    options.Cookie.HttpOnly = true;
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    options.Cookie.SameSite = SameSiteMode.Lax;
    options.ExpireTimeSpan = TimeSpan.FromHours(8);
    options.SlidingExpiration = true;

    // For an SPA, returning 401 is clearer than a redirect
    options.Events.OnRedirectToLogin = ctx =>
    {
        ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
        return Task.CompletedTask;
    };
})
.AddOpenIdConnect(options =>
{
    options.Authority = builder.Configuration["Oidc:Authority"];
    options.ClientId = builder.Configuration["Oidc:ClientId"];
    options.ClientSecret = builder.Configuration["Oidc:ClientSecret"];
    options.ResponseType = "code";
    options.SaveTokens = true;
    options.Scope.Add("offline_access");
});

A few details matter. A cookie name starting with the __Host- prefix tells the browser that the cookie may only be set over HTTPS, without a domain attribute and for the root path; this makes it harder for subdomains to overwrite the cookie. SaveTokens = true stores the received tokens inside the authentication session. Since the BFF is now a confidential client, it can use a client secret; that secret should also come through configuration, as described in the previous post.

For API requests, the default behaviour when there is no session is to redirect to the identity provider. That makes no sense for a fetch call; it is cleaner for the SPA to receive a 401 and start the sign-in flow itself.

Routing API calls through the BFF

The second job of the BFF is to forward requests from the SPA to the backend, adding the token. You can do this with hand-written HttpClient calls, but a reverse proxy library makes it much easier. An example with YARP:

builder.Services.AddReverseProxy()
    .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
    .AddTransforms(context =>
    {
        // Browser cookies should not reach the backend API
        context.AddRequestHeaderRemove("Cookie");

        context.AddRequestTransform(async transform =>
        {
            var token = await transform.HttpContext.GetTokenAsync("access_token");
            if (token is not null)
            {
                transform.ProxyRequest.Headers.Authorization =
                    new AuthenticationHeaderValue("Bearer", token);
            }
        });
    });

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapReverseProxy().RequireAuthorization();

In the route configuration, mapping paths such as /api/orders/{**rest} to the relevant services is enough. Not forwarding the session cookie to the backend is a small but important detail: the APIs work with tokens, not cookies, and the session cookie should not be visible anywhere outside the BFF.

A new responsibility that comes with cookies: CSRF

An SPA that carries the token in a header is naturally resistant to CSRF; the browser does not add the header on its own. That changes the moment we switch to cookies. The browser sends the cookie automatically, so requests triggered from another site can also appear authenticated.

SameSite=Lax prevents the cookie from being sent on POST requests coming from other sites, but it should not be left as the only defence. A simple and effective additional measure is to require a custom header on every API call:

app.Use(async (context, next) =>
{
    if (context.Request.Path.StartsWithSegments("/api") &&
        !context.Request.Headers.ContainsKey("X-CSRF"))
    {
        context.Response.StatusCode = StatusCodes.Status400BadRequest;
        return;
    }
    await next();
});

Cross-origin requests that include a custom header require the browser to perform a CORS preflight first. As long as the BFF does not grant CORS access to other origins, an attacker's page cannot send a request with this header. On the frontend, collecting this in a single helper function is enough:

export async function api<T>(path: string, init: RequestInit = {}): Promise<T> {
  const res = await fetch(`/api${path}`, {
    ...init,
    credentials: 'same-origin',
    headers: { 'Content-Type': 'application/json', 'X-CSRF': '1', ...init.headers },
  });

  if (res.status === 401) {
    const returnUrl = encodeURIComponent(location.pathname + location.search);
    window.location.href = `/bff/login?returnUrl=${returnUrl}`;
    throw new Error('Sign-in required');
  }
  if (!res.ok) throw new Error(`Request failed: ${res.status}`);
  return res.json() as Promise<T>;
}

The session lifecycle: sign-in, sign-out and refresh

A BFF usually exposes three small endpoints. /bff/login starts the OpenID Connect flow and, when it finishes, sends the user back to returnUrl. This parameter must be validated; if it is not restricted to the application's own paths, you get an open redirect vulnerability. /bff/user returns the user information the SPA needs to render the interface: name, roles, perhaps a few claims. The tokens themselves never appear in this response. /bff/logout should both delete the local cookie and end the session at the identity provider; otherwise, when the user clicks "Sign in", they are let back in without being asked for a password. Since sign-out is also a state-changing operation, it should be called with POST rather than GET, and with the CSRF header.

The access token's lifetime is usually shorter than the session. Before using the token, the BFF should check its expiry time and, if necessary, obtain a new one with the refresh token and update the session. Storing tokens inside the cookie makes the cookie larger; ASP.NET Core splits large cookies into chunks, but the data carried on every request still grows. As the number of users and the token size increase, keeping the session on the server (for example in a distributed cache) and putting only a key in the cookie is a healthier approach. In that case, when the BFF runs as multiple instances, you also need to make sure the data protection keys are shared.

The cost, and when you do not need it

A BFF is not free. Every API call goes through an extra network hop, a new service appears that has to be operated, and the SPA and the BFF need to be served under the same site. In an architecture where the SPA is served from a CDN and the API from an entirely different domain, cookie-based sessions require additional arrangements.

Nor is it necessary for every application. Mobile apps call for a different assessment because the platform provides secure storage. For internal tools that do not handle sensitive data and work with short-lived tokens, a simpler setup can be reasonable. But in an SPA that involves user data, payments or administrative privileges, removing tokens from the browser reduces more risk than many measures added later.

When designing authentication, the question to ask should not be "where is the safest place to store the token" but "does the token need to reach the browser at all". The BFF makes the answer "no": the browser carries a cookie, the server keeps the secrets and the SPA only talks to its own origin. The frontend code gets simpler, and security decisions are gathered in a single place, on the server.