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

πŸ“š Interview question

You have a large ASP.NET Framework 4.8 application and a React SPA calling several APIs. How would you use YARP to migrate the legacy app to ASP.NET Core 10 incrementally with the strangler-fig pattern, and to build a backend-for-frontend that keeps tokens out of the browser? What are the risks?

Covers YARP as an architectural tool: strangler-fig migration from ASP.NET Framework to ASP.NET Core 10 with MapForwarder and System.Web adapters (shared session and authentication), and a backend-for-frontend that uses cookies and attaches access tokens server-side, plus the risks and exit criteria.

Senior Architecture Advanced aspnet-core backend-for-frontend devops migration strangler-fig yarp

🎯 Key points

  • New ASP.NET Core 10 app sits in front; unmatched routes forwarded to the legacy app with MapForwarder at lowest route order
  • Move one vertical slice at a time; the route table is the migration progress tracker, reported to stakeholders
  • System.Web adapters: remote app authentication shares identity; remote session works only for explicitly registered, serialisable keys and costs a call per request
  • Rollback is a routing change, provided the slice's data and state stay readable by legacy (no one-way schema or session changes)
  • BFF: SPA uses an HttpOnly SameSite cookie; the BFF holds tokens and attaches them to downstream calls
  • BFF needs CSRF protection (custom header or antiforgery) because cookies ride on every request
  • Risks: added latency, shared-state coupling, the proxy becoming permanent, double-auth bugs; define exit criteria
  • One BFF per frontend, owned by the frontend team; no business logic in it

⏱ 30-second 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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"For the migration I'd use the strangler-fig pattern with YARP doing the routing. I create a new ASP.NET Core 10 app and put it in front, so it receives all traffic. Endpoints I've rebuilt are served by the new app; everything else falls through to a catch-all MapForwarder route, with the lowest route order, that proxies to the legacy 4.8 app. Microsoft's System.Web adapters help with the hard part, shared state: the new app can read the legacy app's session and authentication through remote app endpoints, so a user logged in on legacy pages stays logged in on new ones. I migrate by vertical slice, a whole feature with its pages and APIs, not by layer, and the route table becomes the progress tracker.

For example, at [company] we [migrated a policy administration system of about 400 pages] this way. We moved [the quoting feature first, because it had the most change requests], and the legacy app's traffic dropped [from 100% to 15% over 10 months] before we switched it off. Rolling back a slice was a configuration change, not a redeploy, which made the business comfortable releasing weekly.

For the SPA, I'd put a BFF in front of the APIs, again built on YARP. The browser authenticates against the BFF with OpenID Connect and gets an HttpOnly, Secure, SameSite cookie. When the SPA calls /api/orders, the BFF looks up the user's access token server-side, attaches it as a bearer token and forwards the call. Tokens never touch JavaScript, so an XSS bug can't steal them. Because cookies are sent automatically, I add CSRF protection, usually a required custom header.

The risk I watch most is the strangler proxy becoming permanent. I agree exit criteria with the business up front: legacy traffic under 5%, then a date to switch it off."


Strangler fig with YARP: the moving parts

Part Role
New ASP.NET Core 10 app Owns the public host name, serves migrated routes
MapForwarder catch-all (lowest order) Sends unmigrated routes to legacy
System.Web adapters Shared session and auth via remote app endpoints
Feature flags / route config Switch a slice between new and legacy without redeploy
Telemetry Traffic share per app, error rate per slice

BFF vs SPA holding tokens

SPA holds tokens (public client) BFF holds tokens
Token exposure In browser memory or storage; XSS can steal Server-side only
Session Refresh tokens in browser HttpOnly cookie, server-side token store
CSRF Not an issue for bearer tokens Must defend (custom header, SameSite)
Extra hop No Yes, a few ms
Current guidance Discouraged for sensitive apps by the IETF browser-based apps draft Recommended pattern

Production example

A [state government] licensing portal migrated from Web Forms to ASP.NET Core over [14] months behind a YARP front door. The proxy added about [2 ms] p50. Migrated slices showed a [40%] drop in p95 response time, and the BFF removed tokens from browser storage, closing a finding from the previous [IRAP] assessment.

πŸ” What the interviewer is checking

Checks that the candidate can use a proxy as a migration and security tool, handle shared state and auth between old and new stacks, and recognise when the pattern is the wrong choice.

Green flags

  • Describes the catch-all forwarder with lowest priority and slice-by-slice migration
  • Raises shared session and authentication and knows the System.Web adapters
  • Explains the BFF's cookie plus server-side token model and the CSRF trade-off
  • Sets exit criteria and keeps business logic out of the proxy

Red flags

  • Proposes a big-bang rewrite of a large live system without discussing risk
  • Forgets that users must stay logged in across old and new pages
  • Stores access tokens in localStorage and calls it a BFF

πŸ“š Learn in depth

1. Strangler fig request flow

                        β”Œβ”€β”€ /quotes/**   ──▢ new endpoints (ASP.NET Core 10)
Browser ──▢ New app ──────
         (public host)  β”œβ”€β”€ /claims/**   ──▢ new endpoints
                        β”‚
                        └── /{**catch-all} (Order = int.MaxValue)
                                  β”‚ MapForwarder (YARP IHttpForwarder)
                                  β–Ό
                            Legacy ASP.NET 4.8 on IIS
                                  β–²
          remote session / auth β”€β”˜  (System.Web adapters remote app endpoints)

Endpoint routing picks the most specific route first; the catch-all has the highest Order value, so it only matches when nothing else does.

2. Shared state is the hard part

The two apps must agree on who the user is and what is in their session. The System.Web adapters (Microsoft.AspNetCore.SystemWebAdapters) provide:

  • Remote app authentication: the new app asks the legacy app to authenticate the request and returns its claims.
  • Remote app session: the new app reads and writes the legacy session over an authenticated endpoint, with session keys registered and serialised explicitly.
  • System.Web.HttpContext shims: let shared libraries targeting .NET Standard 2.0 use familiar APIs in both apps.

Remote session adds a call per request that touches session, so the goal is to remove session dependence slice by slice.

3. Choosing slices

Good first slices are high-change, low-coupling features. Avoid starting with the feature that touches shared session everywhere. Migrate by vertical slice (UI + API + data access for one feature), because layer-by-layer migration keeps both apps fully in use for years.

4. The BFF pattern

SPA ──cookie──▢ BFF (ASP.NET Core + YARP) ──Bearer token──▢ Orders API
                  β”‚                                     Billing API
                  └── OIDC code flow + PKCE with Entra ID
                       tokens stored server-side (auth cookie or distributed cache)

The BFF is a confidential client: it uses the authorisation code flow with PKCE and a client credential (ideally a managed identity federated credential or certificate). YARP's request transform reads the access token with GetTokenAsync("access_token") and sets Authorization: Bearer. Refresh happens server-side.

5. CSRF and cookie settings

Cookies are sent automatically, so a malicious site could trigger calls. Defences: SameSite=Strict or Lax, HttpOnly, Secure, plus a required custom header such as X-CSRF: 1 on API calls. A custom header forces a CORS preflight, which a cross-site attacker cannot pass.

6. Off-the-shelf options

Duende BFF packages this pattern (commercial licence for most organisations). Microsoft's Blazor and SPA documentation shows a YARP-based BFF sample. Writing your own is a few hundred lines; the risk is getting token refresh and logout right.

Try it yourself

  1. Create a new ASP.NET Core app with a MapForwarder catch-all to an existing site; migrate one page and confirm both work under the same host.
  2. Add the System.Web adapters remote authentication and log in on a legacy page, then hit a new page.
  3. Build a BFF that signs in with Entra ID and proxies /api/** with a bearer token; check browser storage contains no tokens.
  4. Try a cross-site form post to the BFF and confirm the custom header check blocks it.
  5. Measure the proxy's added latency with Application Insights dependency timings.

πŸ’» Code

Strangler-fig front door: migrated routes served locally, the rest forwarded to the legacy app.

// Program.cs in the new ASP.NET Core 10 app (packages: Yarp.ReverseProxy, Microsoft.AspNetCore.SystemWebAdapters)
var builder = WebApplication.CreateBuilder(args);
var legacyUrl = builder.Configuration["Legacy:Url"]
    ?? throw new InvalidOperationException("Legacy:Url is required");

builder.Services.AddHttpForwarder();

// Share session and auth with the legacy app during the migration.
builder.Services.AddSystemWebAdapters()
    .AddRemoteAppClient(o =>
    {
        o.RemoteAppUrl = new Uri(legacyUrl);
        o.ApiKey = builder.Configuration["Legacy:RemoteAppApiKey"]!; // from Key Vault, not appsettings
    })
    .AddSessionClient()
    .AddAuthenticationClient(isDefaultScheme: true);

var app = builder.Build();

app.UseSystemWebAdapters();

// Migrated slice.
app.MapGet("/quotes/{id:int}", (int id) => Results.Ok(new QuoteDto(id, "Comprehensive", 1_240m)));

// Everything not yet migrated goes to legacy. Lowest priority so new routes always win.
app.MapForwarder("/{**catch-all}", legacyUrl)
   .Add(static b => ((RouteEndpointBuilder)b).Order = int.MaxValue);

app.Run();

public sealed record QuoteDto(int Id, string Cover, decimal AnnualPremium);

A BFF: cookie session for the SPA, bearer token attached server-side, CSRF header required.

// Program.cs in the BFF
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.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.HttpOnly = true;
        o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
        o.Cookie.SameSite = SameSiteMode.Strict;
    })
    .AddOpenIdConnect(o =>
    {
        builder.Configuration.Bind("EntraId", o);
        o.ResponseType = "code";          // code flow + PKCE (on by default)
        o.SaveTokens = true;              // tokens kept in the encrypted auth cookie
        o.Scope.Add("api://orders/Orders.Read");
    });

builder.Services.AddAuthorization();

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

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

// CSRF: API calls must carry a custom header, which forces a CORS preflight cross-site.
app.Use(async (ctx, next) =>
{
    if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Request.Headers["X-CSRF"] != "1")
    {
        ctx.Response.StatusCode = StatusCodes.Status400BadRequest;
        return;
    }
    await next(ctx);
});

app.MapGet("/login", () => Results.Challenge(new AuthenticationProperties { RedirectUri = "/" }));
app.MapReverseProxy().RequireAuthorization();

app.Run();

⚠ Common mistakes

  • Mistake: Migrating layer by layer (data access first, then services, then UI). Why it is wrong: Both apps stay fully in use, shared session and database dependencies persist across every page, and nothing can be switched off for years. Instead: Migrate vertical slices and track progress by routes moved.
  • Mistake: Giving the catch-all forwarder normal route priority. Why it is wrong: It can shadow new endpoints, so migrated routes still go to legacy. Instead: Set Order = int.MaxValue on the catch-all.
  • Mistake: Assuming the System.Web adapters share all session state automatically. Why it is wrong: Remote session only exposes keys you register with a serialiser, and every access is a network call to legacy. Instead: Register the minimum keys, and remove session dependence as slices move, using explicit state stores.
  • Mistake: Treating rollback as always "just a route change". Why it is wrong: If the new slice wrote data in a shape legacy cannot read, or moved state out of session, routing back breaks users. Instead: Use expand-and-contract schema changes and keep legacy-readable state until the slice is proven.
  • Mistake: No exit criteria for the legacy app. Why it is wrong: The proxy and two codebases become permanent, doubling maintenance. Instead: Agree a traffic threshold and a switch-off date with the business.
  • Mistake: Building a BFF without CSRF protection. Why it is wrong: Cookie-authenticated endpoints can be triggered from other sites. Instead: SameSite cookies plus a required custom header or antiforgery tokens.
  • Mistake: Forwarding the BFF's session cookie to downstream APIs. Why it is wrong: Leaks the session to every backend and its logs. Instead: Strip the cookie and send only the bearer token.
  • Mistake: One shared BFF for web, mobile and partners. Why it is wrong: It becomes a general gateway with conflicting needs and owners. Instead: One BFF per frontend, owned by that frontend's team.
  • Mistake: Putting business logic in the BFF or strangler proxy. Why it is wrong: Creates a third codebase to migrate later. Instead: Keep them to routing, auth and shaping.

πŸ› Senior insight: trade-offs

Strangler fig works because it turns a risky big-bang rewrite into many small, reversible routing changes. The proxy is cheap; the real cost is shared state and running two stacks. I'd budget for the System.Web adapters' remote session overhead, double hosting cost during the migration, and the team's time on both codebases, and I'd report legacy traffic share to stakeholders monthly so the end is visible. For a small app (say under [50] pages) with low change, a planned rewrite or the .NET Upgrade Assistant may be faster than running a strangler for a year.

The BFF is the current recommendation for browser apps handling sensitive data: the IETF's OAuth 2.0 for Browser-Based Applications guidance prefers a backend that keeps tokens server-side, and for Australian systems it maps cleanly onto the Privacy Act's security obligations (APP 11) and reduces what an XSS bug can exfiltrate. It is overkill for a public, read-only site with no user data.

Option When it fits Cost When not to
Strangler fig with YARP Large, live legacy app; continuous delivery needed Two stacks, shared state work Small app, or the legacy app is frozen and can be rewritten in one go
Big-bang rewrite Small scope, stable requirements High release risk Business cannot pause features
BFF with YARP SPA with sensitive data, several APIs Extra hop, CSRF work, token store Public, anonymous, read-only frontends
SPA as public client Low-sensitivity apps, no backend wanted Token theft via XSS risk Health, finance, government data

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions YARP routes, clusters or transforms Why: Checks hands-on YARP configuration, health checks and per-route policies
    How to answer

    YARP is Microsoft's reverse proxy toolkit, shipped as the Yarp.ReverseProxy NuGet package and run as ASP.NET Core middleware. You define routes (what to match: path, host, headers) that point at clusters (a set of destinations plus policies). Transforms rewrite the request on the way through, such as stripping /api or adding headers. Each cluster picks a destination with a load balancing policy (PowerOfTwoChoices by default) and keeps the list healthy with active probes and passive failure detection.

    Because it is ASP.NET Core, the gateway reuses normal authentication, authorisation, rate limiting and CORS middleware, attached per route by policy name. The trade-off: you get full C# control and one stack for the team, but you now run, scale and patch the gateway yourself, which a managed service like API Management would do for you.

  2. When: Candidate mentions a BFF or an API gateway Why: Checks what belongs in a gateway versus a BFF and when to use API Management
    How to answer

    An API gateway is a single entry point in front of your services that routes requests and applies cross-cutting concerns: TLS termination, token validation, rate limiting and quotas, request ids, IP filtering, header rewriting and sometimes caching. Azure API Management is a managed gateway with XML policies, products and subscriptions, a developer portal and analytics; YARP is a .NET reverse-proxy library you host yourself and extend in C#. A backend-for-frontend (BFF) is a gateway per client (web, mobile) that aggregates and shapes data for that client. The danger is a smart gateway: business rules and orchestration in policies become untested, hard-to-version logic owned by nobody. Keep the gateway thin and services authoritative.

  3. When: Candidate mentions SameSite cookies for the BFF session Why: Checks SameSite behaviour and its interaction with the OpenID Connect sign-in flow
    How to answer

    SameSite tells the browser whether to send a cookie on cross-site requests. Strict: never cross-site. Lax: cross-site only on top-level GET navigations (clicking a link), not on cross-site POSTs, iframes or fetch. None: always, and it must also be Secure. 'Site' means scheme plus registrable domain, so app.example.com.au and api.example.com.au are the same site.

    Chromium now treats cookies without the attribute as Lax by default, which broke flows that relied on cross-site POSTs, most famously OpenID Connect form_post callbacks: the identity provider POSTs back to /signin-oidc, so the correlation and nonce cookies must be SameSite=None; Secure, which ASP.NET Core sets for you over HTTPS. The trade-off: Strict is safest but hurts UX; None is needed for embedding and federation but loses CSRF protection.

πŸ›  Real-world problems: how you handle them

Strangler-fig migration stalled by shared session
Situation
[Insurance] policy administration system on ASP.NET Web Forms 4.8 on IIS VMs, about [400] pages and [3,000] daily staff users; the business wanted weekly releases and a move to Azure Container Apps in Australia East.
Signals
Six months in, only [10%] of traffic was on the new app; every new page called remote session; p95 for migrated pages was [180 ms] slower than expected; users were intermittently logged out when moving between old and new pages.
Investigation
Application Insights dependency telemetry showed a remote session call on nearly every new request; KQL on `dependencies` grouped by operation showed session reads of [40 KB] serialised objects. Auth cookies were issued by legacy with a path and domain that did not match the new app's host after a DNS change. Route analysis showed the team had migrated shared components rather than whole features.
Resolution
Fixed the cookie domain and moved authentication to remote app authentication so both apps agreed on the user. Replaced the large session object with explicit, per-feature state in Azure SQL and Redis for migrated slices. Re-planned the backlog as vertical slices, starting with quoting and claims lodgement.
Prevention
Dashboard of traffic share and p95 per app; an architecture rule that new code must not add session keys; exit criteria (legacy under [5%] for 30 days, then switch-off) recorded in an ADR and reported monthly.

How to tell it (STAR)

**S:** At [company] we were six months into moving a [400]-page Web Forms system to ASP.NET Core behind a YARP front door, and only [10%] of traffic had moved. **T:** As [tech lead] I needed to get the migration moving and stop users being logged out between old and new pages. **A:** Application Insights showed remote session calls on almost every new request and an auth cookie scoped to the old host. I fixed the cookie and switched to remote app authentication, replaced the giant session object with explicit state for migrated features, and re-planned the work as vertical slices, starting with quoting. **R:** Within [eight] more months legacy traffic was under [5%], migrated pages were [40%] faster at p95, and we switched the IIS servers off on [date], saving about [$X] a year.

↩ Usually asked after

More in Reverse Proxy and Gateway

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me