📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Design authentication for a product with a React SPA, a public ASP.NET Core API and native mobile apps, where customers can also sign in with Google or Apple. Would you put tokens in the browser or use a backend-for-frontend, how do mobile apps sign in, and how does one API accept both cookie and JWT callers safely?

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.

Senior Architecture Advanced architecture authentication bff mobile oauth2 security

🎯 Key points

  • One identity provider federates Google/Apple; apps only speak OIDC to it
  • SPA: BFF with a __Host- prefixed, HttpOnly, Secure, SameSite cookie; tokens stay server-side and never in browser storage
  • Mobile: code + PKCE in the system browser (RFC 8252), tokens in Keychain/Keystore, refresh rotation, DPoP where the IdP supports it
  • API accepts JWT from mobile, BFF and partners, so it needn't accept cookies
  • If one host must accept both: policy scheme (Bearer header -> JwtBearer, else cookie) plus antiforgery on cookie-authenticated writes
  • Per-client registrations, audiences and scopes
  • Lifetimes per channel (web 8-24 h, mobile up to 30 days with rotation) and logout that revokes refresh tokens and ends the IdP session

⏱ 30-second answer

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.

  • SPA: a BFF (ASP.NET Core) runs the code flow as a confidential client, keeps tokens server-side and gives the browser an HttpOnly, SameSite cookie; it proxies API calls with an access token.
  • Mobile: authorisation code + PKCE in the system browser (RFC 8252), tokens in Keychain/Keystore, rotating refresh tokens.
  • API: accepts JWT bearer only. The BFF and mobile apps both send tokens, so the API never needs cookies. If one host must accept both, use a policy scheme that forwards by header, plus CSRF protection for cookie requests.

The trade-off: a BFF adds a hop and state, in exchange for no tokens in the browser.

🗣 Full answer (senior)

How I would answer this in an interview

"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's HttpOnly, Secure and SameSite=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, ASWebAuthenticationSession on 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 ForwardDefaultSelector picks 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 in localStorage. The senior line: one issuer, one token shape, and no tokens in the browser."


The architecture

           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 ]

Choices per client

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

Combining schemes when you must

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

Production example

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.

🔍 What the interviewer is checking

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

  • Centralises identity and federates external providers
  • Chooses a BFF for the SPA and explains CSRF protection
  • Uses the system browser with PKCE for mobile
  • Keeps the API bearer-only, or knows how to combine schemes safely
  • Considers logout, lifetimes and per-client registrations

Red flags

  • Tokens in localStorage
  • Embedded web views for mobile login
  • Treats cookies and JWTs as interchangeable without mentioning CSRF

📚 Learn in depth

1. Why a hub identity provider

Each 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.

2. The BFF in detail

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.

3. Native apps (RFC 8252)

  • System browser, not an embedded web view: the user's IdP session and password manager work, and the app can't read the credentials.
  • Redirect via claimed HTTPS links (universal links / app links) rather than custom schemes where possible, to prevent another app intercepting the code; PKCE covers the rest.
  • Refresh tokens in secure hardware-backed storage, rotation on, optional DPoP if the IdP supports it.

4. Accepting cookies and JWTs on one host

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.

5. Logout and sessions across channels

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.

Try it yourself

  1. Build a minimal BFF with cookie + OIDC + YARP and confirm in browser dev tools that no token is stored.
  2. Add a policy scheme to a test API and send requests with a cookie, a Bearer token and both; check which scheme handles each.
  3. Try a cross-site form POST against the BFF and confirm it is rejected.
  4. Configure Google federation in a dev identity provider tenant and note that your app config didn't change.
  5. Draw the threat model (STRIDE) for the token paths and list a control for each threat.

💻 Code

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();

⚠ Common mistakes

  • Mistake: Integrating Google, Apple and local accounts separately in each app. Why it is wrong: every app handles different tokens and claims, and adding a provider means releases everywhere. Instead: federate at one identity provider.
  • Mistake: Keeping access and refresh tokens in browser storage. Why it is wrong: any XSS steals them. Instead: a BFF with an HttpOnly cookie.
  • Mistake: Using an embedded web view for mobile sign-in. Why it is wrong: the app can read credentials, passkeys and SSO don't work, and providers like Google block it. Instead: the system browser per RFC 8252.
  • Mistake: Letting the public API accept cookies without CSRF protection. Why it is wrong: a cross-site page can trigger authenticated state changes. Instead: keep cookies at the BFF, or add antiforgery for cookie-authenticated requests.
  • Mistake: One client registration shared by web and mobile. Why it is wrong: a public client's settings weaken the confidential one, and you can't revoke or monitor them separately. Instead: one registration per client type.
  • Mistake: Using the external provider's user id as your primary key. Why it is wrong: account linking and provider changes break identity. Instead: your IdP's sub, with external ids stored as linked logins.
  • Mistake: Logout that only clears the browser cookie. Why it is wrong: refresh tokens and IdP sessions remain. Instead: revoke refresh tokens and call the IdP's end-session endpoint.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate proposes a BFF or refresh tokens Why: Checks depth on rotation, lifetimes and storage
    How to answer

    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.

    • Rotation: every refresh returns a new refresh token and invalidates the old one. Reuse detection: if an old one is used again, someone has a copy, so the server revokes the whole token family.
    • Lifetimes: access tokens 5–15 minutes; refresh tokens bounded by an idle timeout and an absolute session limit.
    • Storage: in a SPA, anything JavaScript can read, XSS can steal. The BFF pattern keeps tokens on the server and gives the browser only an 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.

  2. When: Candidate mentions code + PKCE Why: Checks understanding of the flows and why PKCE matters
    How to answer

    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.

    • Authorisation code + PKCE: the browser gets a one-time code, and the client swaps it for tokens, proving with a code_verifier that it started the flow. Use it for web apps, SPAs and mobile.
    • Client credentials: a service authenticates as itself; no user.
    • Implicit and password flows are deprecated (RFC 9700); OAuth 2.1, still an IETF draft in late 2026, makes that official.

    The trade-off: the redirect-based flows are more moving parts, but credentials never touch your app.

  3. When: Candidate mentions the BFF session cookie Why: Checks cookie flags, expiry and Data Protection
    How to answer

    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.

    • Flags: HttpOnly (JavaScript can't read it), Secure (HTTPS only), SameSite=Lax by default (not sent on most cross-site requests).
    • Expiry: 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.
    • Keys: every instance must share the Data Protection key ring, or cookies issued by one server can't be read by another.

    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.

🛠 Real-world problems: how you handle them

Rebuilding authentication for a web and mobile launch
Situation
A [subscription] product with [~150,000] Australian customers had a React SPA storing JWTs in `localStorage`, an API accepting both cookies and JWTs, and a planned iOS/Android launch with Google and Apple sign-in in [three months].
Signals
A pen test raised token storage and CSRF findings; the mobile team prototyped login in an embedded web view that Google rejected; every new login provider required changes in [three] codebases.
Investigation
Mapped all token paths and storage locations; threat-modelled the flows with STRIDE; reviewed the IETF browser-based apps guidance and RFC 8252; compared identity providers on federation, passkeys, data residency in Australia and cost per monthly active user.
Resolution
Adopted [the identity provider] as the hub with Google and Apple federation; built an ASP.NET Core BFF for the SPA; mobile apps used code + PKCE in the system browser with rotating refresh tokens; the API became bearer-only with per-client scopes. Migrated existing users by linking their old ids to the new `sub` on first sign-in.
Prevention
An ADR for token storage and session lifetimes, client registrations in infrastructure as code, automated ZAP scans and a pen test before launch, dashboards for sign-in success by provider.

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.

↩ Usually asked after

More in Authentication

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me