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.
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.
"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
MapForwarderroute, 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."
| 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 |
| 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 |
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.
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
Red flags
βββ /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.
The two apps must agree on who the user is and what is in their session. The System.Web adapters (Microsoft.AspNetCore.SystemWebAdapters) provide:
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.
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.
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.
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.
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.
MapForwarder catch-all to an existing site; migrate one page and confirm both work under the same host./api/** with a bearer token; check browser storage contains no tokens.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();
Order = int.MaxValue on the catch-all.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 |
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.
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.
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.
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.
Last updated 23 Nov 2026.