In ASP.NET Core 10, how do you put a single-page app behind a BFF that signs in with AddOpenIdConnect so the browser never holds an access token?
answer
- the server is the confidential client
- SaveTokens = true, read with GetTokenAsync
- login and logout endpoints challenge or sign out
- API calls need 401, not a 302 to the provider
- no built-in token refresh
basics
~20 sThe ASP.NET Core host is the OpenID Connect client: it signs in with AddOpenIdConnect, keeps the tokens in its encrypted cookie via SaveTokens and attaches the access token to downstream calls itself. The SPA only ever sends that cookie to same-origin endpoints.
solid answer
~40 sThe host runs `AddCookie` plus `AddOpenIdConnect` with `ResponseType = "code"`, `SaveTokens = true` and, if it will refresh, the `offline_access` scope. It exposes `/bff/login` (`Results.Challenge` on the OIDC scheme with a local `RedirectUri`), a POST `/bff/logout` that signs out of both schemes, and `/bff/user` returning the claims the UI needs. The SPA calls same-origin `/api/...` endpoints with the cookie; the host reads `await HttpContext.GetTokenAsync("access_token")` and forwards the call with that bearer token. Two traps: an expired session on a `fetch` must get **401**, not a 302 to the provider, so protect API endpoints with the cookie scheme (in ASP.NET Core 10 its challenge answers 401 for API endpoints) or end `OnRedirectToIdentityProvider` with `HandleResponse()`; and nothing refreshes the saved token for you, so you add that in `OnValidatePrincipal`.
code
csharp · 24 lines.AddOpenIdConnect(options =>
{
// Authority, ClientId, ClientSecret from configuration
options.ResponseType = OpenIdConnectResponseType.Code;
options.SaveTokens = true;
options.Scope.Add("offline_access");
options.Events.OnRedirectToIdentityProvider = context =>
{
if (context.Request.Path.StartsWithSegments("/api"))
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
context.HandleResponse();
}
return Task.CompletedTask;
};
});
app.MapGet("/api/timesheets", async (HttpContext http, IHttpClientFactory factory) =>
{
var token = await http.GetTokenAsync("access_token");
var client = factory.CreateClient("timesheets");
client.DefaultRequestHeaders.Authorization = new("Bearer", token);
return Results.Stream(await client.GetStreamAsync("timesheets"), "application/json");
}).RequireAuthorization();go deeper
Recall that in a BFF the server signs in and keeps the tokens, and the browser only carries a cookie.
Explain SaveTokens and GetTokenAsync, the login, logout and user endpoints, and why API calls must get 401 rather than a provider redirect.
Cover the operational gaps: token refresh in OnValidatePrincipal, cookie size and SessionStore, open redirects on returnUrl, and CSRF on cookie-authenticated APIs.
Weigh a BFF per front end against shared token handling, and decide where refresh, session storage and downstream authorization belong across teams.
## The shape In a **backend for frontend** (BFF), the browser application never takes part in the OAuth exchange. The ASP.NET Core host that serves the SPA is the confidential OpenID Connect client: - it signs the user in with `AddOpenIdConnect`, using the code flow, PKCE and a client secret; - it stores the resulting tokens in its own **encrypted, HttpOnly cookie** with `SaveTokens = true`; - it calls downstream APIs itself, attaching the access token on the server. The SPA sees only a cookie it cannot read and same-origin endpoints. Script injected into the page has no token to steal, though it can still make calls while the page is open. ## Endpoints the SPA uses 1. **`GET /bff/login?returnUrl=...`**: returns `Results.Challenge(new AuthenticationProperties { RedirectUri = returnUrl }, [OpenIdConnectDefaults.AuthenticationScheme])`. Accept only a local path for `returnUrl`, or the endpoint becomes an open redirect. The SPA reaches it with a full-page navigation, not `fetch`. 2. **`POST /bff/logout`**: `Results.SignOut(...)` with both the cookie and OIDC schemes, so the provider session ends too. 3. **`GET /bff/user`**: returns selected claims, or 401, so the SPA can render "signed in as". 4. **`/api/...`**: endpoints that require the cookie and either do work locally or forward to a downstream API with the saved access token. ## Reading and attaching the token `SaveTokens` stores `access_token`, `id_token`, `refresh_token`, `token_type` and `expires_at` in the cookie's `AuthenticationProperties`, **not** as claims. A server endpoint reads them with `await HttpContext.GetTokenAsync("access_token")`, which authenticates the default scheme and returns the stored value. Typical ways to attach it: - a `DelegatingHandler` on a named or typed `HttpClient` that sets `Authorization: Bearer ...`; - a reverse-proxy route that forwards `/api/...` to the downstream service and adds the header in a request transform. ## The 401-versus-302 trap With `DefaultChallengeScheme` set to the OIDC scheme, an expired session on `fetch("/api/orders")` produces a challenge from the OIDC handler: a **302 to the provider**. `fetch` follows it cross-origin and the browser reports a CORS error the SPA cannot interpret. The OIDC handler has no notion of API endpoints, so make API calls fail with 401 instead: | Approach | How | |---|---| | Challenge with the cookie scheme on API endpoints | a policy with `AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme)`; since **ASP.NET Core 10** the cookie handler answers 401/403 instead of redirecting for endpoints marked as API endpoints (`[ApiController]`, Minimal APIs that read or write JSON) | | Intercept the OIDC redirect | in `OnRedirectToIdentityProvider`, if the path starts with `/api`, set `context.Response.StatusCode = 401` and call `context.HandleResponse()` | On 401 the SPA navigates the whole window to `/bff/login`. ## Refresh is your job ASP.NET Core stores a refresh token but **never uses it**. When the access token expires, downstream calls start failing while the cookie is still valid. The usual fix hooks `CookieAuthenticationEvents.OnValidatePrincipal`, which runs whenever the cookie is read: 1. read `expires_at` with `context.Properties.GetTokenValue("expires_at")`; 2. if it is close, post the `refresh_token` to the provider's token endpoint; 3. on success, call `UpdateTokenValue` for the new tokens and set `context.ShouldRenew = true` so the cookie is rewritten; 4. on failure, call `context.RejectPrincipal()` so the user signs in again. The ASP.NET Core documentation's Blazor BFF sample implements this; maintained libraries for it exist as well. ## Cookie size and other costs Tokens make the cookie large. The cookie handler's default `ChunkingCookieManager` splits it into several cookies, all sent on every request to the host. Setting `CookieAuthenticationOptions.SessionStore` to an `ITicketStore` keeps the ticket on the server and only a key in the cookie, at the cost of a shared store across instances. Because the API is now cookie-authenticated, it is exposed to cross-site request forgery: keep the cookie `SameSite` restrictive and require a custom header or antiforgery token on state-changing calls.
- Why must the SPA reach /bff/login with a full-page navigation rather than fetch?`Results.Challenge` on the OIDC scheme answers with a 302 to the provider, whose sign-in page has to render in the top-level window and set its own cookies. A `fetch` would follow the redirect cross-origin and fail with a CORS error. Accept only a local `returnUrl` on that endpoint, or it becomes an open redirect.
- The access token expired but users still appear signed in. Why, and what do you change?The cookie's lifetime is independent of the token's, and ASP.NET Core does not refresh saved tokens. Add refresh logic in `OnValidatePrincipal` using `expires_at` and the saved `refresh_token`, set `ShouldRenew`, and call `RejectPrincipal` when refresh fails.
- ASP.NET Core 10 makes the OpenID Connect handler answer API calls with 401 instead of redirecting.
- SaveTokens stores the access token as a claim on User.
- The cookie handler refreshes saved access tokens when SlidingExpiration renews the cookie.
- HttpContext.GetTokenAsync returns the access token even when SaveTokens is false.
- Storing tokens in the cookie costs nothing, so cookie size never matters.
Assumes ASP.NET Core 10, where the cookie handler answers 401/403 instead of redirecting for endpoints marked as API endpoints; the OpenID Connect handler's challenge still redirects.