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

📚 Interview question

Implement the backend-for-frontend (BFF) pattern for a React SPA in ASP.NET Core. Show the cookie and OpenID Connect setup, how tokens are stored and refreshed server-side, how YARP forwards /api calls to the downstream API with the access token attached, how you protect against CSRF, and how login, logout and a 'who am I' endpoint work for the SPA.

A hand-rolled BFF in .NET 10: cookie + OpenID Connect authentication with SaveTokens, server-side token refresh, YARP forwarding with a bearer-token transform, custom-header CSRF protection, and login, logout and user endpoints for a React SPA.

Senior Coding Advanced bff cookie-authentication csrf frontend openid-connect yarp

🎯 Key points

  • Cookie scheme as default, OpenID Connect as challenge; code flow + PKCE as a confidential client
  • SaveTokens = true stores access and refresh tokens in the encrypted auth ticket (or a server-side ticket store for size and revocation)
  • Refresh the access token server-side before expiry (OnValidatePrincipal); if refresh fails, reject the principal so the API call gets a clean 401 and the SPA sends the user through /bff/login
  • YARP route /api/** -> downstream API, RequireAuthorization, transform adds Authorization: Bearer and strips the Cookie header
  • Cookie: __Host- prefix, HttpOnly, Secure, SameSite=Strict (Lax if needed for top-level OIDC return)
  • API and BFF endpoints never challenge with a 302 to the IdP; they return 401, and only /bff/login starts the OIDC flow
  • CSRF: SameSite plus a required custom header (X-CSRF) on /api and /bff endpoints
  • Scale-out: shared Data Protection key ring (Blob + Key Vault) and an ITicketStore (Redis) so any instance can read and revoke sessions

⏱ 30-second answer

The BFF is an ASP.NET Core app on the SPA's origin. It uses cookie authentication as the default scheme and OpenID Connect as the challenge scheme, acting as a confidential client with the code flow and PKCE. SaveTokens = true keeps the access and refresh tokens inside the encrypted auth ticket (or a server-side ticket store), and a cookie event refreshes the access token before it expires.

YARP forwards /api/** to the downstream API: the route requires an authenticated user, and a request transform adds Authorization: Bearer <token> and strips the browser's cookie. CSRF is handled by a SameSite cookie plus a required custom header that cross-site requests cannot send.

The SPA gets three endpoints: /bff/login, /bff/logout and /bff/user. The trade-off is owning auth plumbing (refresh, logout, key management) in exchange for no tokens in the browser.

🗣 Full answer (senior)

How I would answer this in an interview

"The BFF has one job: be the OAuth client so the browser doesn't have to. I host it on the same origin as the React app. Authentication is two schemes: cookies by default and OpenID Connect for the challenge. OIDC runs the authorisation code flow with PKCE using a client secret or certificate, so the BFF is a confidential client. With SaveTokens on, the access token and refresh token are stored in the authentication ticket, which ASP.NET Core encrypts with Data Protection into the HttpOnly cookie. If the ticket gets too big, or I want server-side revocation, I plug in an ITicketStore backed by Redis so the cookie only carries a session id.

For API calls the SPA calls /api/... on its own origin. YARP matches that route, requires an authenticated user, and a request transform reads the access token with GetTokenAsync and sets the Authorization header, while removing the Cookie header so the downstream API never sees our session. Tokens expire, so in the cookie's OnValidatePrincipal event I check expires_at; within a minute of expiry I call the token endpoint with the refresh token, update the stored tokens and set ShouldRenew so a fresh cookie is issued. If refresh fails, I reject the principal and the SPA gets a 401. For example, at [company] we built this for [a React portal] and [an independent pen test found no token exposure]; the tricky part was concurrent refreshes from parallel requests, which we solved with [a per-session lock / rotation grace period].

CSRF matters because cookies go automatically. I use a __Host- cookie with SameSite=Strict and require an X-CSRF header on every /api and BFF call; a cross-site form can't add it, and a cross-origin fetch with it needs a preflight we never approve. The mistake I see is letting the OIDC handler answer an expired API call with a 302 to the identity provider: fetch follows it and fails with a CORS error. API calls must get a clean 401 and the SPA redirects the whole page to /bff/login."


Moving parts

Piece Responsibility
Cookie scheme Session for the browser; HttpOnly, Secure, SameSite, __Host-
OIDC scheme Code flow + PKCE, confidential client, SaveTokens
Token refresh OnValidatePrincipal refreshes before expiry
YARP /api/** to the downstream API with bearer token, cookie stripped
CSRF guard Requires X-CSRF header on /api and /bff
/bff/login Challenge with a validated local returnUrl
/bff/logout Sign out of cookie and OIDC (end session at the IdP)
/bff/user Returns selected claims, never tokens

Build or buy

Option When it fits Cost
Hand-rolled (this code) Team with OIDC experience, simple needs Refresh races, logout, testing are yours
Duende BFF (v4) Want back-channel logout, server-side sessions, tested refresh Commercial annual licence above community thresholds

Production example

For a React portal with [about 8,000 daily users] behind Azure Front Door, the BFF added about 3 to 5 ms per proxied call, the cookie stayed under 1 KB with a Redis ticket store, and moving tokens server-side closed the pen test's token-theft finding.

🔍 What the interviewer is checking

Checks whether a senior candidate can implement a BFF correctly and knows the production pitfalls, not just the diagram.

Green flags

  • Sets up cookie default + OIDC challenge with SaveTokens and code flow as a confidential client
  • Adds the bearer token in a YARP transform and strips the cookie
  • Handles refresh server-side and fails closed with 401
  • Explains CSRF defences and __Host- cookies
  • Mentions Data Protection key sharing, cookie size and ticket stores

Red flags

  • Returns tokens to the SPA from the BFF
  • Leaves CSRF unaddressed
  • Uses 302 redirects for API calls
  • Hard-codes the client secret

📚 Learn in depth

1. Request flows

Login:
SPA ─► GET /bff/login?returnUrl=/orders ─► 302 to IdP /authorize (code + PKCE)
IdP ─► 302 /signin-oidc?code=... ─► BFF swaps code for tokens (with client secret)
BFF ─► Set-Cookie: __Host-bff=<encrypted ticket or session id> ─► 302 /orders

API call:
SPA ─► GET /api/orders  (Cookie + X-CSRF: 1)
BFF ─► validate cookie ─► maybe refresh ─► YARP ─► GET https://orders-api/orders
                                                  Authorization: Bearer eyJ...

2. Where tokens live

With SaveTokens, the OIDC handler writes access_token, refresh_token, id_token and expires_at into AuthenticationProperties. The cookie handler serialises the ticket, encrypts and signs it with Data Protection, and may split it into chunks if large. Two consequences: the cookie can reach 3 to 4 KB with big tokens, and every instance must share the Data Protection key ring (blob storage + Key Vault) or cookies from one instance fail on another. An ITicketStore (for example Redis) stores the ticket server-side and puts only a key in the cookie, which also allows server-side revocation.

3. Refresh and concurrency

The SPA often fires several requests at once. If each sees an expiring token and refreshes, a refresh-token rotation policy may treat the second use as reuse and revoke the whole family. Mitigations: refresh slightly early, serialise refresh per session (a lock keyed by session id in the ticket store), or rely on the identity provider's rotation grace period.

4. CSRF in a BFF

Cookies are ambient credentials. Defences, in layers:

  1. SameSite=Strict (or Lax) stops cookies on most cross-site requests.
  2. A required custom header: HTML forms cannot set headers, and cross-origin fetch with custom headers triggers a CORS preflight that the BFF does not allow.
  3. Optionally ASP.NET Core antiforgery tokens for extra assurance.

The __Host- prefix forces Secure, Path=/ and no Domain, so a sibling subdomain cannot overwrite the cookie.

5. Making API failures SPA-friendly

By default an unauthenticated request to a protected endpoint triggers the challenge scheme. For OIDC that is a 302 to the IdP, which fetch follows cross-origin and fails confusingly. Override OnRedirectToLogin on the cookie scheme or set a ForwardChallenge policy so /api gets 401 and /bff/login is the only place that challenges.

6. Logout

Sign out of the cookie scheme (clears the session) and the OIDC scheme (redirects to the IdP's end-session endpoint with id_token_hint). For a full solution, support back-channel logout so the IdP can end the BFF session when the user signs out elsewhere, and revoke the refresh token.

7. Costs

One extra hop per API call (typically low single-digit milliseconds in the same region), a stateful concern (keys or ticket store), and auth code your team owns. In return, no token is ever exposed to JavaScript.

Try it yourself

  1. Run the code with a test tenant (Entra ID or a local Keycloak container) and inspect the cookie size in dev tools.
  2. Remove the Cookie header removal transform and log headers on the downstream API to see the session leak.
  3. Set the access token lifetime to 2 minutes and watch refresh happen in logs.
  4. Call /api/orders from a page on another origin with credentials: 'include' and confirm the preflight or the CSRF check blocks it.
  5. Scale to two instances without shared Data Protection keys and observe users being logged out.

💻 Code

A minimal hand-rolled BFF in .NET 10 with cookie + OIDC, server-side refresh, YARP forwarding and a CSRF guard.

// Program.cs (.NET 10) — packages: Microsoft.AspNetCore.Authentication.OpenIdConnect, Yarp.ReverseProxy
using System.Globalization;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Yarp.ReverseProxy.Transforms;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(o =>
    {
        o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    })
    .AddCookie(o =>
    {
        o.Cookie.Name = "__Host-bff";
        o.Cookie.HttpOnly = true;
        o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
        o.Cookie.SameSite = SameSiteMode.Strict;
        o.ExpireTimeSpan = TimeSpan.FromHours(8);
        o.Events.OnRedirectToLogin = ctx => { ctx.Response.StatusCode = 401; return Task.CompletedTask; }; // no 302 for fetch
        o.Events.OnValidatePrincipal = TokenRefresher.RefreshIfExpiringAsync;
    })
    .AddOpenIdConnect(o =>
    {
        builder.Configuration.Bind("Oidc", o);      // Authority, ClientId; secret from Key Vault / user-secrets
        o.ResponseType = OpenIdConnectResponseType.Code; // code flow; PKCE is on by default
        o.SaveTokens = true;                          // tokens stay in the encrypted server-issued ticket
        o.Scope.Add("offline_access");                // refresh token
        o.Scope.Add(builder.Configuration["Oidc:ApiScope"]!);
        o.MapInboundClaims = false;
    });

builder.Services.AddAuthorization();
builder.Services.AddHttpClient();
// Shared keys so any instance can read the cookie (blob + Key Vault in production).
builder.Services.AddDataProtection().SetApplicationName("orders-bff");

builder.Services.AddReverseProxy()
    .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
    .AddTransforms(t =>
    {
        t.AddRequestHeaderRemove("Cookie");            // never forward the browser session downstream
        t.AddRequestTransform(async ctx =>
        {
            var token = await ctx.HttpContext.GetTokenAsync("access_token");
            if (token is not null)
                ctx.ProxyRequest.Headers.Authorization = new("Bearer", token);
        });
    });

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

// CSRF guard: SPA calls must carry X-CSRF; cross-site forms cannot set it.
app.Use(async (ctx, next) =>
{
    var guarded = ctx.Request.Path.StartsWithSegments("/api") || ctx.Request.Path.StartsWithSegments("/bff/user");
    if (guarded && !ctx.Request.Headers.ContainsKey("X-CSRF")) { ctx.Response.StatusCode = 401; return; }
    await next(ctx);
});

var bff = app.MapGroup("/bff");
bff.MapGet("/login", (string? returnUrl, HttpContext ctx) =>
    TypedResults.Challenge(new AuthenticationProperties
    {
        RedirectUri = returnUrl is not null && Uri.IsWellFormedUriString(returnUrl, UriKind.Relative) && returnUrl.StartsWith('/') && !returnUrl.StartsWith("//")
            ? returnUrl : "/", // local URLs only: no open redirect
    }));
bff.MapPost("/logout", () => TypedResults.SignOut(new AuthenticationProperties { RedirectUri = "/" },
    [CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme]))
    .RequireAuthorization();
bff.MapGet("/user", (ClaimsPrincipal user) =>
    TypedResults.Ok(new BffUser(user.FindFirstValue("name"), user.FindFirstValue("email")))) // claims only, never tokens
    .RequireAuthorization();

app.MapReverseProxy().RequireAuthorization();
app.MapFallbackToFile("index.html");
app.Run();

public sealed record BffUser(string? Name, string? Email);

public static class TokenRefresher
{
    public static async Task RefreshIfExpiringAsync(CookieValidatePrincipalContext ctx)
    {
        var expiresAt = ctx.Properties.GetTokenValue("expires_at");
        if (expiresAt is null || DateTimeOffset.Parse(expiresAt, CultureInfo.InvariantCulture) > DateTimeOffset.UtcNow.AddMinutes(1))
            return;

        var oidc = ctx.HttpContext.RequestServices
            .GetRequiredService<Microsoft.Extensions.Options.IOptionsMonitor<OpenIdConnectOptions>>()
            .Get(OpenIdConnectDefaults.AuthenticationScheme);
        var config = await oidc.ConfigurationManager!.GetConfigurationAsync(ctx.HttpContext.RequestAborted);
        var http = ctx.HttpContext.RequestServices.GetRequiredService<IHttpClientFactory>().CreateClient();

        using var response = await http.PostAsync(config.TokenEndpoint, new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["grant_type"] = "refresh_token",
            ["refresh_token"] = ctx.Properties.GetTokenValue("refresh_token") ?? "",
            ["client_id"] = oidc.ClientId!,
            ["client_secret"] = oidc.ClientSecret!,
        }), ctx.HttpContext.RequestAborted);

        if (!response.IsSuccessStatusCode)
        {
            ctx.RejectPrincipal();                    // SPA gets 401 and sends the user to /bff/login
            await ctx.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return;
        }

        var payload = new OpenIdConnectMessage(await response.Content.ReadAsStringAsync(ctx.HttpContext.RequestAborted));
        ctx.Properties.UpdateTokenValue("access_token", payload.AccessToken);
        if (!string.IsNullOrEmpty(payload.RefreshToken))
            ctx.Properties.UpdateTokenValue("refresh_token", payload.RefreshToken); // rotation
        ctx.Properties.UpdateTokenValue("expires_at",
            DateTimeOffset.UtcNow.AddSeconds(int.Parse(payload.ExpiresIn, CultureInfo.InvariantCulture)).ToString("o", CultureInfo.InvariantCulture));
        ctx.ShouldRenew = true;                        // re-issue the cookie with the new tokens
    }
}
// appsettings.json (no secrets here)
{
  "Oidc": { "Authority": "https://login.example.com.au/", "ClientId": "orders-bff", "ApiScope": "api://orders/orders.read" },
  "ReverseProxy": {
    "Routes": { "api": { "ClusterId": "orders", "Match": { "Path": "/api/{**rest}" }, "Transforms": [{ "PathRemovePrefix": "/api" }] } },
    "Clusters": { "orders": { "Destinations": { "d1": { "Address": "https://orders-api.internal/" } } } }
  }
}
// React side: the only auth code the SPA needs.
export async function getUser() {
  const res = await fetch("/bff/user", { headers: { "X-CSRF": "1" } });
  return res.ok ? ((await res.json()) as { name?: string; email?: string }) : null; // 401 = signed out
}
export const login = () => (window.location.href = `/bff/login?returnUrl=${encodeURIComponent(location.pathname)}`);

⚠ Common mistakes

  • Mistake: Letting /api calls trigger the OIDC challenge. Why it is wrong: The challenge is a 302 to the identity provider; fetch follows it cross-origin and fails with a CORS error instead of a usable status. Instead: Make every API and BFF data endpoint return 401 (override OnRedirectToLogin and the forbidden redirect), and let the SPA navigate the whole page to /bff/login, the only endpoint that challenges.
  • Mistake: Signing the user out silently when a token refresh fails mid-task. Why it is wrong: They lose unsaved work with no explanation. Instead: Reject the principal so the call returns 401; the SPA keeps form state (or saves a draft), shows 'Your session has ended' and offers sign-in with a returnUrl back to the same screen.
  • Mistake: Forwarding the browser's Cookie header downstream. Why it is wrong: It leaks the session to other services and logs. Instead: Strip it in a YARP transform and send only the bearer token.
  • Mistake: Returning tokens from /bff/user 'for convenience'. Why it is wrong: It undoes the whole pattern. Instead: Return only the claims the UI needs.
  • Mistake: No CSRF protection because 'it's an API'. Why it is wrong: Cookie authentication sends credentials automatically. Instead: SameSite plus a required custom header or antiforgery.
  • Mistake: Not sharing Data Protection keys. Why it is wrong: Cookies issued by one instance are rejected by another, logging users out on scale-out or restarts. Instead: Persist keys to blob storage protected by Key Vault.
  • Mistake: Ignoring concurrent refreshes. Why it is wrong: Parallel requests reuse a rotated refresh token and trip reuse detection, revoking the session. Instead: Serialise refresh per session or use the IdP's grace period.
  • Mistake: Accepting any returnUrl on login. Why it is wrong: It creates an open redirect. Instead: Allow only local paths.
  • Mistake: Storing the client secret in appsettings.json. Why it is wrong: Secrets in source control. Instead: Key Vault with managed identity, or a certificate credential.

🏛 Senior insight: trade-offs

Writing this is not hard; operating it is. The parts that bite in production are refresh races, cookie size, key ring sharing across instances and slots, logout that actually ends the IdP session, and correct 401 behaviour for fetch. I write integration tests for each with WebApplicationFactory and a fake token endpoint before calling it done.

I would choose hand-rolled for a single SPA with a simple identity provider setup and a team that understands OIDC; I would buy Duende BFF (v4 as of November 2026, licensed annually, with a free community edition for qualifying small organisations) when I need server-side sessions, back-channel logout and multiple frontends, because those features are exactly where hand-rolled versions go wrong. Measure: added latency per proxied call (should be single-digit ms), cookie size, refresh failures per hour, and 401 rate after deploys.

Option When it fits Cost When not to
Hand-rolled cookie + OIDC + YARP One SPA, experienced team Ownership of edge cases Many frontends, back-channel logout needed
Duende BFF Supported implementation, more features Licence, vendor dependency Tight budget for a small internal app (unless community edition applies)
Tokens in SPA + PKCE Truly no server possible Exposure to XSS theft Personal or financial data
Session storage When it fits Cost
Encrypted cookie ticket Small tokens, few claims 2 to 4 KB cookies, no server-side revocation
ITicketStore (Redis) Large tokens, revocation, back-channel logout Redis dependency and availability

🔗 Follow-ups the interviewer may ask

  1. When: Candidate uses YARP as the forwarding layer. Why: Checks broader YARP use: strangler-fig migration and gateway risks.
    How to answer

    For a strangler-fig migration, I put a new ASP.NET Core 10 app in front of the legacy ASP.NET Framework 4.8 app. Routes the new app implements are served locally; everything else is forwarded to the legacy app with YARP's MapForwarder as a lowest-priority catch-all. I migrate one vertical slice at a time, using System.Web adapters to share session and authentication, until the legacy app has no traffic and is switched off. Rollback is a route change.

    For a backend-for-frontend, the SPA authenticates with an HttpOnly, SameSite cookie to the BFF; the BFF holds the OAuth tokens and attaches access tokens server-side when YARP forwards calls to the APIs, so no token ever reaches browser JavaScript.

    The risks are extra latency, shared state coupling the two apps, CSRF on cookie-based calls, and the "temporary" proxy becoming permanent, so I set exit criteria up front.

  2. When: Candidate mentions mobile apps or other clients calling the same API. Why: Checks how one API accepts cookie callers via the BFF and bearer callers directly.
    How to 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.

  3. When: Candidate scales the BFF to several instances. Why: Checks Data Protection key ring sharing and antiforgery across replicas.
    How to answer

    ASP.NET Core's Data Protection system encrypts auth cookies and antiforgery tokens with a key ring. By default each instance creates its own key ring on local disk, so a cookie protected by replica A cannot be decrypted by replica B, and every redeploy creates new keys. Fix it by persisting keys to a shared store (PersistKeysToAzureBlobStorage), protecting them at rest with Key Vault (ProtectKeysWithAzureKeyVault) and setting the same SetApplicationName on every instance. If the app uses session, back it with IDistributedCache (Redis) so any replica can read it. Sticky sessions only hide the problem: they break on scale-in, deploys and pod rescheduling, so treat them as a stopgap, not the fix.

🛠 Real-world problems: how you handle them

Users logged out randomly after the BFF scaled out
Situation
A React portal behind a .NET BFF on Azure Container Apps in Australia East, [about 8,000 daily users]. Autoscaling was enabled for [a marketing campaign].
Signals
Spike in 401s from `/api` and `/bff/user` in Application Insights, correlated with replica count rising from 1 to 4; users reported being sent to the login page mid-task; logs showed 'Unprotect ticket failed' warnings.
Investigation
Application Insights showed failures only on requests routed to new replicas. The logs' Data Protection warnings pointed to key ring mismatches: each container generated its own keys in a local folder. Checked cookie size in dev tools: about 3.8 KB in chunks, which also explained occasional 'request header too large' errors at Front Door.
Resolution
Immediately: pinned replicas to 1 and disabled autoscale. Properly: persisted Data Protection keys to Blob Storage protected with a Key Vault key, added a Redis `ITicketStore` to shrink the cookie to a session id, and serialised token refresh per session.
Prevention
Integration test that issues a cookie on one test server and validates it on another with the shared key ring; load test with autoscaling in staging; alert on 'Unprotect ticket failed' log count; deployment checklist item for key persistence.

How to tell it (STAR)

**S:** On [project], our BFF for [about 8,000] daily users started logging people out at random during [a campaign], right after autoscaling kicked in. **T:** As the owner of the auth layer I had to stop the logouts and make scale-out safe. **A:** Application Insights tied the 401s to new replicas, and the logs showed Data Protection unprotect failures: every replica had its own keys. I pinned to one replica as a stop-gap, then moved keys to Blob Storage with Key Vault protection, introduced a Redis ticket store that cut the cookie from about 3.8 KB to under 200 bytes, and added a cross-instance cookie test. **R:** Unexpected logouts went to [zero] at [4] replicas, and the header-size errors at Front Door disappeared.

More in SPA Integration

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me