duendesoftware/duende-skills/duende-bff

Claude Code and agent skill by duendesoftware/duende-skills

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Duende BFF (Backend for Frontend) security framework for securing SPAs. Covers session management, API endpoint proxying, token management, anti-forgery protection, and integration with React/Angular/Blazor frontends.

Install

npx vskill@latest install duendesoftware/duende-skills/duende-bff

SKILL.md

The same SKILL.md was published earlier as duendesoftware/duende-skills/duende-bff.

Duende BFF (Backend for Frontend)

When to Use This Skill

  • Building or securing a SPA (React, Angular, Vue, Blazor WASM) that calls APIs requiring authentication
  • Implementing the Backend-for-Frontend security pattern to keep access tokens out of the browser
  • Configuring BFF session management, login/logout endpoints, and server-side sessions
  • Proxying requests from a frontend to remote APIs while automatically attaching access tokens
  • Adding CSRF/anti-forgery protection to APIs consumed by browser-based applications
  • Integrating Duende.BFF with Duende.AccessTokenManagement for automatic token refresh
  • Deploying a BFF behind a reverse proxy or configuring same-site cookie behavior

Core Principles

  1. Tokens Never Touch the Browser — The BFF holds all OAuth tokens server-side; the browser only ever sees an HTTP-only, Secure, SameSite cookie
  2. CSRF Protection Is Mandatory — Every BFF API endpoint must require the X-CSRF: 1 header; use .AsBffApiEndpoint() or MapRemoteBffApiEndpoint — never skip it without an explicit alternative
  3. Cookie Configuration Determines Security Posture — SameSite=Strict is preferred when the IDP is on the same site; Lax is acceptable when cross-site redirects are required after login
  4. Server-Side Sessions for Production — The default in-memory cookie session is unsuitable for production; persist sessions with Duende.BFF.EntityFramework
  5. Token Management Is Automatic — BFF integrates with Duende.AccessTokenManagement; never manually refresh tokens or pass raw access tokens to the frontend

Docs: https://docs.duendesoftware.com/bff/


Pattern 1: Setup and Registration (BFF v4)

BFF v4 uses a streamlined registration API that auto-configures OpenID Connect and cookie authentication with recommended defaults.

csharp
// ✅ v4: AddBff() with fluent OIDC and cookie configuration
builder.Services.AddBff()
.ConfigureOpenIdConnect(options =>
{
options.Authority = "https://your-idp.example.com";
options.ClientId = "my-bff-client";
options.ClientSecret = "secret";
options.ResponseType = "code";
options.ResponseMode = "query";
options.GetClaimsFromUserInfoEndpoint = true;
options.SaveTokens = true;
options.MapInboundClaims = false;
options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("offline_access"); // Required for refresh tokens
})
.ConfigureCookies(options =>
{
// Use Strict when your IDP is on the same site as the BFF.
// Use Lax when a cross-site redirect is required (e.g., IDP on a different domain).
options.Cookie.SameSite = SameSiteMode.Lax;
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseRouting();
app.UseAuthentication();
app.UseBff(); // Adds CSRF anti-forgery enforcement middleware
app.UseAuthorization();
app.Run();
csharp
// ❌ v4: Do NOT manually wire AddCookie + AddOpenIdConnect when using AddBff()
// ConfigureOpenIdConnect and ConfigureCookies handle this correctly
builder.Services.AddAuthentication()
.AddCookie("cookie")
.AddOpenIdConnect("oidc", ...); // Bypasses BFF's recommended defaults
BFF v3 Registration

For projects still on v3, explicit scheme setup is required and MapBffManagementEndpoints() must be called manually:

csharp
// ✅ v3: explicit authentication scheme wiring
builder.Services.AddBff();
builder.Services
.AddAuthentication(options =>
{
options.DefaultScheme = "cookie";
options.DefaultChallengeScheme = "oidc";
options.DefaultSignOutScheme = "oidc";
})
.AddCookie("cookie", options =>
{
options.Cookie.Name = "__Host-bff";
options.Cookie.SameSite = SameSiteMode.Strict;
})
.AddOpenIdConnect("oidc", options =>
{
options.Authority = "https://your-idp.example.com";
options.ClientId = "my-bff-client";
options.ClientSecret = "secret";
options.ResponseType = "code";
options.SaveTokens = true;
options.Scope.Add("offline_access");
});
// ...
app.MapBffManagementEndpoints(); // ✅ Required in v3
Key Differences: V4 vs V3
FeatureV4V3
Auth handler setupConfigureOpenIdConnect() / ConfigureCookies()Manual AddCookie() / AddOpenIdConnect()
Management endpointsAuto-registeredMapBffManagementEndpoints() required
Remote API token type.WithAccessToken(RequiredTokenType.User).RequireAccessToken(TokenType.User)
Session cleanup.AddSessionCleanupBackgroundProcess()EnableSessionCleanup option
Token retrieverIAccessTokenRetriever (implement directly)DefaultAccessTokenRetriever (inheritable)
Multi-frontendBuilt-in AddFrontend() APINot supported
Middleware controlAutomaticallyRegisterBffMiddleware optionAlways automatic

Pattern 2: Login and Logout Endpoints

In BFF v4, management endpoints (/bff/login, /bff/logout, /bff/user, /bff/backchannel-logout) are registered automatically by AddBff() with the implicit default frontend. In v3, they require an explicit call to MapBffManagementEndpoints().

Login — A browser navigation to /bff/login initiates an OIDC Authorization Code flow. After the IDP redirects back, the BFF sets an HTTP-only authentication cookie.

csharp
// ✅ Trigger login from the SPA (browser navigation, not fetch)
// React example:
// window.location.href = '/bff/login?returnUrl=/dashboard';
// ✅ Optional: supply a returnUrl to redirect after login
// GET /bff/login?returnUrl=/dashboard
// The returnUrl must be a local path; absolute URLs are rejected.

Logout — A browser navigation to /bff/logout signs the user out locally and initiates an OIDC end_session flow. It also revokes the refresh token automatically.

csharp
// ✅ The sid claim from /bff/user must be passed as a query parameter
// GET /bff/logout?sid=<session-id>
// This is required to prevent CSRF attacks on the logout endpoint.
csharp
// ❌ Do NOT call /bff/logout via fetch() without the sid parameter.
// The logout endpoint validates the sid to prevent cross-site logout attacks.

Pattern 3: CSRF / Anti-Forgery Protection

The BFF enforces a custom X-CSRF header on every protected endpoint. This triggers a CORS preflight for cross-origin requests, effectively preventing CSRF attacks. The header value is irrelevant — its presence is sufficient.

Local (Embedded) API Endpoints
csharp
// ✅ Minimal API: decorate with AsBffApiEndpoint()
app.MapGet("/api/data", (HttpContext ctx) => Results.Ok("data"))
.RequireAuthorization()
.AsBffApiEndpoint();
// ✅ MVC Controllers: apply to the entire controller via attribute
[Route("api/data")]
[BffApi]
public class DataController : ControllerBase
{
[HttpGet]
public IActionResult Get() => Ok("data");
}
// ✅ MVC Controllers: apply at mapping time
app.MapControllers()
.RequireAuthorization()
.AsBffApiEndpoint();
csharp
// ❌ Do NOT expose BFF API endpoints without AsBffApiEndpoint() or BffApi attribute.
// Without it, the x-csrf header is not enforced and the endpoint is CSRF-vulnerable.
app.MapGet("/api/data", () => Results.Ok("data"))
.RequireAuthorization(); // Missing .AsBffApiEndpoint()
Middleware Order

UseBff() must appear after UseRouting() but before UseAuthorization(). Incorrect order silently disables anti-forgery enforcement.

csharp
// ✅ Correct middleware order
app.UseRouting();
app.UseAuthentication();
app.UseBff(); // Must be here
app.UseAuthorization();
app.MapControllers().AsBffApiEndpoint();
// ❌ Wrong: UseBff() after UseAuthorization() — anti-forgery is not applied
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseBff(); // Too late
Skipping Anti-Forgery

For specific endpoints that cannot send the anti-forgery header (e.g., webhook receivers), use .SkipAntiforgery():

csharp
// ✅ Webhook receiver: skip anti-forgery for endpoints that cannot send the header
app.MapPost("/api/webhook", (WebhookPayload payload) => Results.Ok())
.AsBffApiEndpoint()
.SkipAntiforgery();
Skipping Response Handling (V4)

By default, BFF converts 401/403 responses from local API endpoints into JSON-friendly responses (no redirect). Use .SkipResponseHandling() to bypass this and trigger normal ASP.NET Core authentication redirects:

csharp
// ✅ Skip BFF's automatic 401/403 conversion — triggers actual OIDC redirect on challenge
app.MapGet("/api/interactive", () => Results.Ok("data"))
.RequireAuthorization()
.AsBffApiEndpoint()
.SkipResponseHandling();
Conditional Anti-Forgery (V4)

In v4, DisableAntiForgeryCheck is a delegate that allows conditionally skipping anti-forgery per-request:

csharp
builder.Services.AddBff(options =>
{
options.DisableAntiForgeryCheck = context =>
context.Request.Path.StartsWithSegments("/api/webhook");
});

Pattern 4: Remote API Proxying

The BFF can act as a reverse proxy to APIs deployed on separate hosts. Requests carry only the session cookie; the BFF exchanges it for an access token before forwarding.

Install the YARP integration package:

dotnet add package Duende.BFF.Yarp
csharp
// ✅ Direct forwarding via MapRemoteBffApiEndpoint
builder.Services.AddBff()
.AddRemoteApis();
// Maps /api/orders and all sub-paths to https://orders-service/orders
app.MapRemoteBffApiEndpoint("/api/orders", new Uri("https://orders-service/orders"))
.WithAccessToken(RequiredTokenType.User); // Attach the user's access token
app.MapRemoteBffApiEndpoint("/api/public", new Uri("https://content-service/public"))
.WithAccessToken(RequiredTokenType.None); // Anonymous remote API
app.MapRemoteBffApiEndpoint("/api/internal", new Uri("https://internal-service/api"))
.WithAccessToken(RequiredTokenType.Client); // Client credentials token (machine-to-machine)
Cookie Header Removal

The BFF removes the browser's Cookie request header before forwarding to a remote API (the API authenticates via the access token the BFF attaches; the BFF session cookie must never leave the BFF). MapRemoteBffApiEndpoint has always done this; YARP routes now do too (every route, with or without token metadata; both AddYarpConfig in 4.x and AddReverseProxy().AddBffExtensions()). Behavior change in patch releases 2.2.1, 2.3.1, 3.0.1, 3.1.1, 4.0.4, 4.1.3, 4.2.1, 4.3.1 (security fix).

The header is removed after YARP copies request headers and after the route's own transforms run, so a route transform that sets Cookie has no effect while removal is on. Transforms registered after AddBffExtensions (e.g. .AddTransforms(...) on the returned IReverseProxyBuilder) run later and can still set a specific Cookie (intentional); don't copy the browser's cookies back.

To opt out (not recommended):

csharp
builder.Services.AddBff(options =>
{
// WARNING: forwards the BFF session cookie to every API proxied through YARP
options.RemoveCookieHeaderFromYarpRequests = false; // default true
});

then remove it per route with YARP: "Transforms": [ { "RequestHeaderRemove": "Cookie" } ] or .WithTransformRequestHeaderRemove("Cookie"). (In 2.x/3.x BffOptions is in Duende.Bff; in 4.x Duende.Bff.Configuration.)

Token Type Options

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
0

Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/duendesoftware/duende-skills/duende-bff/badge)](https://verified-skill.com/skills/duendesoftware/duende-skills/duende-bff)

Something wrong with this skill or its page? Tell us.