Authentication architecture for SPA, API and mobile clients: identity provider and external logins, BFF vs browser tokens, native app flows, and combining cookie and JWT schemes in ASP.NET Core with policy schemes.
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.
"I'd start with one identity provider as the hub. For customers that's something like Microsoft Entra External ID or Auth0; it handles local accounts, passkeys and MFA, and federates Google and Apple. My apps only speak OpenID Connect to the hub, so tokens always have the same issuer and claims shape, and I can add a provider without a release. Each client gets its own registration: the BFF as a confidential web client, the iOS and Android apps as public native clients.
For the SPA I'd use a backend-for-frontend. The React app is served by, or same-site with, a small ASP.NET Core host that does the code flow, stores tokens in a server-side session and gives the browser a
__Host-cookie that'sHttpOnly,SecureandSameSite=Strict. The React app calls/bff/api/..., the BFF attaches the access token and forwards with YARP. Mobile apps use code plus PKCE in the system browser,ASWebAuthenticationSessionon iOS and Custom Tabs on Android, never an embedded web view, and keep refresh tokens in the Keychain or Keystore with rotation. The public API then only has to accept bearer tokens with the right audience and scopes, because both the BFF and the mobile apps send tokens. For example, at [company] we initially let the API accept the SPA's cookie as well as JWTs and had to add CSRF defences to every endpoint; [moving the cookie to the BFF removed that whole class of issues and simplified the API's auth config to a single scheme].If a single host genuinely has to accept both, I'd use a policy scheme whose
ForwardDefaultSelectorpicks JWT when there's a Bearer header and cookies otherwise, and require antiforgery on cookie requests. The mistake I see is SPAs keeping refresh tokens inlocalStorage. The senior line: one issuer, one token shape, and no tokens in the browser."
Google / Apple / passkeys / MFA
|
[ Identity provider ] (OIDC)
/ | \
code+PKCE code+PKCE client credentials
(confidential) (public, native) (partners, jobs)
| | |
[ BFF ] <-cookie- Browser (React) |
| Bearer AT |
v v Bearer AT v Bearer AT
[ Public API: JwtBearer, audience api://product, scope/role policies ]
| Client | Flow | Token storage | Notes |
|---|---|---|---|
| React SPA | BFF: code + PKCE (confidential) | Server session; browser holds cookie | CSRF: SameSite + custom header |
| iOS / Android | Code + PKCE, system browser | Keychain / Keystore | Rotating refresh tokens; claimed HTTPS redirect (universal/app links) |
| Partners | Client credentials | Partner's server | App roles, rate limits per client |
| Public API | Validates JWT | n/a | Audience + scopes; no cookies |
| Approach | Use when |
|---|---|
| Separate hosts (BFF + API) | Default; each host has one scheme |
Policy scheme with ForwardDefaultSelector |
One host, mixed callers |
AddAuthenticationSchemes on specific policies |
Only some endpoints accept cookies |
With this design at [company], adding Apple sign-in for the iOS launch was a configuration change at the identity provider, [no app code]; the API's authentication config is [12 lines], and the next pen test reported [no] token storage or CSRF findings across [three] clients.
Checks that the candidate can design end-to-end authentication across client types with sound reasoning about token storage, flows and scheme handling.
Green flags
Red flags
localStorageEach external provider has its own claims, quirks and lifecycle. Federating them at one IdP gives your apps a single issuer, a stable user id (sub from your IdP, not Google's), consistent MFA and passkey policy, account linking, and one place for audit and Privacy Act obligations such as data residency and access requests.
Browser --GET /bff/login--> BFF --302--> IdP (code + PKCE, confidential client)
Browser <--Set-Cookie __Host-bff (HttpOnly, Secure, SameSite=Strict)-- BFF
Browser --fetch /bff/api/orders, X-CSRF: 1, cookie--> BFF --Bearer AT--> API
'-- refresh AT with RT when near expiry
CSRF: SameSite=Strict stops cross-site requests carrying the cookie; requiring a custom header means a cross-site fetch needs a CORS preflight, which the BFF doesn't allow.
AddPolicyScheme("smart", ForwardDefaultSelector = ctx =>
ctx.Request.Headers.Authorization starts with "Bearer " ? "Bearer" : "Cookies")
DefaultScheme = "smart"
Cookie-authenticated requests are vulnerable to CSRF, JWT ones aren't. So cookie requests need antiforgery validation, and you must make sure that a Bearer request can't also be satisfied by a cookie in a way that bypasses checks.
Logout should end the BFF session, revoke refresh tokens (RFC 7009), and optionally call the IdP's end-session endpoint. Front-channel or back-channel logout (OIDC specs) lets the IdP tell the BFF when a session ends elsewhere. Mobile sessions are typically longer (30 days with rotation) than web sessions (8–24 hours); write the numbers in an ADR.
Default design: the public API accepts only bearer tokens with the right audience and scopes.
// Public API - Program.cs (.NET 10)
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
o.Authority = builder.Configuration["Idp:Authority"];
o.Audience = "api://product";
o.MapInboundClaims = false;
});
builder.Services.AddAuthorizationBuilder()
.AddPolicy("orders.read", p => p.RequireAssertion(c =>
c.User.FindFirst("scope")?.Value.Split(' ').Contains("orders.read") == true));
When one host must accept both cookies (browser) and JWTs (mobile, partners): a policy scheme plus antiforgery for cookie requests.
// Mixed host - Program.cs (.NET 10)
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication("smart")
.AddPolicyScheme("smart", "Cookie or Bearer", o =>
{
o.ForwardDefaultSelector = ctx =>
ctx.Request.Headers.Authorization.ToString().StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)
? JwtBearerDefaults.AuthenticationScheme
: CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(o =>
{
o.Cookie.Name = "__Host-app";
o.Cookie.SameSite = SameSiteMode.Strict;
o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
})
.AddJwtBearer(o =>
{
o.Authority = builder.Configuration["Idp:Authority"];
o.Audience = "api://product";
});
builder.Services.AddAuthorization();
builder.Services.AddAntiforgery(o => o.HeaderName = "X-XSRF-TOKEN");
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
// Cookie-authenticated, state-changing requests must carry an antiforgery token; bearer requests can't be forged cross-site.
app.Use(async (ctx, next) =>
{
var isCookieAuth = ctx.User.Identity?.AuthenticationType == CookieAuthenticationDefaults.AuthenticationScheme;
if (isCookieAuth && !HttpMethods.IsGet(ctx.Request.Method) && !HttpMethods.IsHead(ctx.Request.Method))
{
var antiforgery = ctx.RequestServices.GetRequiredService<IAntiforgery>();
if (!await antiforgery.IsRequestValidAsync(ctx)) { ctx.Response.StatusCode = StatusCodes.Status400BadRequest; return; }
}
await next();
});
app.MapPost("/orders", () => Results.Created()).RequireAuthorization();
app.Run();
HttpOnly cookie.sub, with external ids stored as linked logins.The architecture is a set of decisions about where trust and tokens live. My defaults: one IdP, one token shape, confidential clients wherever a server exists, and APIs that only understand bearer tokens. Mixed schemes on one host are a smell I accept only with a clear reason, because they double the attack surface (CSRF plus token handling).
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| BFF for the SPA | Any SPA with personal or financial data | Extra service, session store, a hop | Fully public, read-only sites |
| Tokens in the SPA (MSAL.js) | Internal tools, low risk, no backend | XSS exposure | Regulated data (Privacy Act sensitive information, payments) |
| Separate BFF and API hosts | Most products | Two deployables | Very small apps |
| Policy scheme on one host | Legacy constraints, small teams | CSRF and scheme-confusion risk | When you can split hosts |
Measure: sign-in success by provider and client, token refresh failures, session length distribution, and logout completion.
A refresh token lets a client get new short-lived access tokens without asking the user to sign in again. Because it is long-lived, it is the most valuable token to steal.
HttpOnly, Secure, SameSite cookie.The trade-off: a BFF adds a server hop and session state, in exchange for tokens that never reach the browser.
OAuth 2.0 is a framework for delegated authorisation: a client gets an access token to call an API on a user's (or its own) behalf. It says nothing about who the user is. OpenID Connect is a thin identity layer on top that adds the ID token (a JWT about the user, for the client), the userinfo endpoint and discovery metadata.
code_verifier that it started the flow. Use it for web apps, SPAs and mobile.The trade-off: the redirect-based flows are more moving parts, but credentials never touch your app.
After a successful login the app calls HttpContext.SignInAsync: the cookie handler serialises the ClaimsPrincipal into an authentication ticket, encrypts and signs it with Data Protection, and sends it as a cookie. On each request the handler decrypts the cookie and rebuilds HttpContext.User, with no database call.
HttpOnly (JavaScript can't read it), Secure (HTTPS only), SameSite=Lax by default (not sent on most cross-site requests).ExpireTimeSpan (default 14 days) with sliding expiration that reissues the cookie once half the window has passed; IsPersistent decides whether it survives closing the browser.The trade-off: a self-contained cookie is fast and stateless, but you can't revoke it without extra checks or a server-side ticket store.
How to tell it (STAR)
**S:** We were about to launch mobile apps with social sign-in, while our SPA kept JWTs in `localStorage` and our API mixed cookies and tokens, which a pen test had flagged. **T:** I was asked to design authentication for all three clients in [three months]. **A:** I proposed a hub identity provider with federation, a BFF for the SPA, PKCE in the system browser for mobile and a bearer-only API, wrote the ADR and threat model, and built the BFF and API changes with [two] colleagues. **R:** We launched on time, the pre-launch pen test had [no] authentication findings, and adding a new login provider went from a multi-team release to a [one-hour] configuration change.
Last updated 23 Nov 2026.