← Plugin catalog
Developer Tools

Duende Skills

Duende Software v0.3.0

IdentityServer & OAuth skills

Create a free account to save this plugin.

From the developer

Declared capabilities

  • Read

Not specified in the available declarations: limitations, pricing & account requirements.

Onboarding example

My IdentityServer is deployed behind an nginx reverse proxy. How do I fix the wrong URL schema used?
Sources & dates

Developer declarations; not independently tested. Listing last checked Nov 22, 2026. Package observed Nov 21, 2026.

View package source →

Description

From the marketplace listing

Specialized skills and agents covering Duende IdentityServer configuration, OAuth 2.0 / OpenID Connect protocols, ASP.NET Core authentication and authorization, BFF patterns, token management, SAML, key management, deployment, and security hardening.

Language: English · Automatically detected from descriptions.

What changed

Similar plugins

Finding similar plugins… Results will appear here automatically.

Browse plugins →

Keywords

Files & skills

File archives

Plugin package48 files · 191 KBBrowse files →
Skill instructions
aspnetcore-authentication19.4 KB

View saved version →

---
name: aspnetcore-authentication
description: ASP.NET Core authentication middleware configuration including OpenID Connect, JWT Bearer, cookie authentication, authentication schemes, challenge/forbid flows, and external identity provider integration.
invocable: false
---

# ASP.NET Core Authentication

## When to Use This Skill

Use this skill when:
- Configuring OIDC authentication in an ASP.NET Core web application
- Setting up JWT Bearer authentication for an API
- Managing authentication schemes (cookies, OIDC, JWT, external providers)
- Implementing challenge, sign-in, sign-out, and forbid flows
- Debugging authentication failures (401s, redirect loops, claim mapping issues)
- Integrating with Duende IdentityServer as an OpenID Connect provider
- Configuring token validation parameters

## Core Principles

1. **Authentication ≠ Authorization** — Authentication establishes *who* the user is. Authorization (see `aspnetcore-authorization`) determines *what* they can do.
2. **Scheme-Based Architecture** — ASP.NET Core authentication is built around named schemes. Each scheme has a handler that knows how to authenticate, challenge, and sign out.
3. **Cookies for Web Apps, JWT for APIs** — Web applications use cookie authentication (with OIDC for login). APIs use JWT Bearer or introspection.
4. **Never Roll Your Own** — Use the built-in OIDC and JWT Bearer handlers. They handle nonce validation, key rotation, token validation, and dozens of edge cases.
5. **Claim Type Mapping Matters** — The OIDC handler maps JWT claim types to .NET claim types by default. Disable this for predictable claim names.

## Related Skills

- `aspnetcore-authorization` — Policy-based authorization after authentication
- `identityserver-configuration` — Server-side client and resource configuration
- `identityserver-sessions-providers` — Server-side sessions to reduce cookie size and maintain IdP-side data
- `oauth-oidc-protocols` — Protocol fundamentals underlying these handlers
- `token-management` — Automatic token refresh with Duende.AccessTokenManagement

Docs: https://docs.duendesoftware.com/identityserver/apis/aspnetcore/jwt/

---

## Pattern 1: OIDC Authentication for Web Applications

The most common pattern — a server-rendered web app authenticating users via Duende IdentityServer:

```csharp
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies", options =>
{
    options.Cookie.Name = "myapp";
    options.Cookie.SameSite = SameSiteMode.Lax;
    options.ExpireTimeSpan = TimeSpan.FromHours(8);
    options.SlidingExpiration = true;
})
.AddOpenIdConnect("oidc", options =>
{
    options.Authority = "https://identity.example.com";
    options.ClientId = "web.app";
    options.ClientSecret = "secret";
    options.ResponseType = "code"; // Authorization code flow

    // Map scopes to request
    options.Scope.Clear();
    options.Scope.Add("openid");
    options.Scope.Add("profile");
    options.Scope.Add("email");
    options.Scope.Add("api1");
    options.Scope.Add("offline_access"); // For refresh tokens

    // Save tokens in the authentication cookie
    options.SaveTokens = true;

    // Disable Microsoft's JWT claim type mapping
    options.MapInboundClaims = false;

    // Where to get additional user claims
    options.GetClaimsFromUserInfoEndpoint = true;

    options.TokenValidationParameters = new TokenValidationParameters
    {
        NameClaimType = "name",
        RoleClaimType = "role"
    };
});

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

### Critical Settings Explained

| Setting | Why | Default |
|---------|-----|---------|
| `MapInboundClaims = false` | Prevents renaming `sub` → `http://schemas.xmlsoap.org/.../nameidentifier` | `true` (maps) |
| `SaveTokens = true` | Stores access/refresh tokens in the cookie for later API calls | `false

Preview of the first 4,000 characters. Read full instructions →

aspnetcore-authorization15.3 KB

View saved version →

---
name: aspnetcore-authorization
description: ASP.NET Core authorization patterns including policy-based authorization, IAuthorizationHandler implementations, scope-based authorization for APIs, authorization middleware configuration, and minimal API authorization.
invocable: false
---

# ASP.NET Core Authorization

## When to Use This Skill

Use this skill when:
- Implementing policy-based authorization in ASP.NET Core
- Protecting API endpoints with scope-based or claim-based checks
- Writing custom `IAuthorizationHandler` implementations
- Configuring authorization for Minimal APIs, controllers, or Razor Pages
- Enforcing role-based access control using OIDC claims
- Combining multiple authorization requirements into composite policies

## Core Principles

1. **Policy-Based Over Role-Based** — Use authorization policies instead of `[Authorize(Roles = "...")]`. Policies are composable, testable, and decoupled from claim types.
2. **Scope ≠ Permission** — OAuth scopes represent what the *client* is allowed to do. User claims represent what the *user* is allowed to do. Combine both for proper API authorization.
3. **Authorization is Separate from Authentication** — Authentication (see `aspnetcore-authentication`) establishes identity. Authorization decides access based on that identity.
4. **Fail Closed** — Default to denying access. Require explicit authorization on all endpoints.
5. **Resource-Based When Needed** — For decisions that depend on the resource being accessed (e.g., "can this user edit this document?"), use `IAuthorizationService` with resource-based authorization.

## Related Skills

- `aspnetcore-authentication` — Authentication middleware that provides the identity
- `claims-authorization` — Advanced claims transformation and authorization patterns
- `identityserver-configuration` — Server-side scope and resource configuration
- `oauth-oidc-protocols` — Understanding scopes, claims, and token contents

Docs: https://docs.duendesoftware.com/identityserver/apis/aspnetcore/authorization/

---

## Pattern 1: Basic Policy-Based Authorization

Define policies at startup and reference them on endpoints:

```csharp
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAuthorization(options =>
{
    // Policy that requires the user to be authenticated
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();

    // Policy requiring a specific scope in the access token
    options.AddPolicy("read:catalog", policy =>
        policy.RequireClaim("scope", "catalog.read"));

    // Policy requiring a specific role
    options.AddPolicy("admin", policy =>
        policy.RequireRole("admin"));

    // Policy combining multiple requirements
    options.AddPolicy("catalog-editor", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireClaim("scope", "catalog.write");
        policy.RequireClaim("department", "merchandising");
    });
});
```

### Applying Policies

```csharp
// Minimal API
app.MapGet("/products", () => Results.Ok())
    .RequireAuthorization("read:catalog");

// Controller
[Authorize(Policy = "catalog-editor")]
public class CatalogController : ControllerBase { }

// Razor Page
[Authorize(Policy = "admin")]
public class AdminModel : PageModel { }
```

---

## Pattern 2: Scope-Based Authorization for APIs

APIs protected by IdentityServer need to validate scopes from the access token. Scopes represent what the *client application* is permitted to do.

### Simple Scope Check

```csharp
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("api.read", policy =>
        policy.RequireClaim("scope", "catalog.read"));

    options.AddPolicy("api.write", policy =>
        policy.RequireClaim("scope", "catalog.write"));
});

app.MapGet("/products", GetProducts).RequireAuthorization("api.read");
app.MapPost("/products", CreateProduct).RequireAuthorization("api.write");
```

### Scope as Space-Delimited S

Preview of the first 4,000 characters. Read full instructions →

claims-authorization30.9 KB

View saved version →

---
name: claims-authorization
description: Claims transformation and profile service patterns for Duende IdentityServer — IProfileService, IClaimsTransformation, claim type mapping, token claim filtering, extension grant validators, and dynamic claims loading.
invocable: false
---

# Claims Transformation & Profile Service

## When to Use This Skill

- You are implementing or customizing `IProfileService` to control which claims are emitted into identity tokens, access tokens, or the userinfo endpoint.
- You need to map claims from an external identity provider (Google, Azure AD, SAML, etc.) into your IdentityServer user principal during login callback processing.
- You are configuring `IdentityResource`, `ApiScope`, or `ApiResource` `UserClaims` collections and need to understand how requested scopes drive `ProfileDataRequestContext.RequestedClaimTypes`.
- You are troubleshooting missing claims — claims are defined on resources but not appearing in tokens or on the userinfo endpoint.
- You need to load claims dynamically from a database or downstream service at token issuance time.
- You are implementing an `IExtensionGrantValidator` and need to emit custom claims into the resulting access token.
- You are consuming tokens in an ASP.NET Core API or web app and need to handle claim type mapping (`MapInboundClaims`, `JwtClaimTypes` vs. Microsoft `ClaimTypes`).

## Core Principles

- **Claims are opt-in by scope.** IdentityServer only asks your profile service for claims that have been declared on a requested `IdentityResource`, `ApiScope`, or `ApiResource`. Declaring a claim on your user store is not enough — it must be listed in a resource's `UserClaims` collection and the client must request that resource's scope.
- **`IProfileService` is the single authoritative extension point** for controlling which user claims enter tokens. Do not use `IClaimsTransformation` on the IdentityServer host to modify token claims — that interface runs during cookie authentication, not token issuance.
- **Identity tokens are for the client; access tokens are for APIs.** Keep identity tokens small. Use `AlwaysIncludeUserClaimsInIdToken` sparingly. Prefer the userinfo endpoint for full profile data.
- **`AddRequestedClaims` respects consent.** Use `context.AddRequestedClaims(claims)` rather than `context.IssuedClaims.AddRange(claims)` when you want IdentityServer to filter your claims down to only those that were requested and consented to by the user.
- **Claim serialization is type-aware.** Set `ClaimValueType` correctly (e.g. `ClaimValueTypes.Integer64`, `IdentityServerConstants.ClaimValueTypes.Json`) so numeric and structured values arrive in tokens as the right JSON type rather than strings.
- **`MapInboundClaims = false` is required** in consuming APIs and web apps. Without it, the JWT bearer handler silently renames standard OIDC claims (e.g. `sub` → `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier`), breaking `User.FindFirst(JwtClaimTypes.Subject)` lookups.

Docs: https://docs.duendesoftware.com/identityserver/apis/aspnetcore/authorization/

---

## Sub-Documents

| Document | Description | When to Load |
|----------|-------------|--------------|
| [docs/extension-grant-claims.md](docs/extension-grant-claims.md) | `IExtensionGrantValidator` implementation for custom grant types with claim propagation | Extension grants, token exchange, custom grant type, IExtensionGrantValidator, GrantValidationResult |
| [docs/external-provider-claims.md](docs/external-provider-claims.md) | External provider login callback with claim mapping, Google/AAD normalization, and ClaimActions | External provider, Google, Azure AD, OIDC callback, claim mapping, ExternalCookieAuthenticationScheme |

---

## Claims Pipeline Overview

Claims travel through several distinct stages between the user's identity and an API's authorization check. Understanding where each transformation occurs prevents duplicate work and subtle bugs.

```
External IdP 

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 2 — file references are metadata, not package contents.

duende-bff37.1 KB

View saved version →

---
name: duende-bff
description: 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.
invocable: false
---

# 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";
   

Preview of the first 4,000 characters. Read full instructions →

identity-security-hardening36.2 KB

View saved version →

---
name: identity-security-hardening
description: Security hardening for Duende IdentityServer deployments including signing key rotation, HTTPS enforcement, CORS configuration, CSP headers, rate limiting, token lifetime tuning, and security audit patterns.
invocable: false
---

# Identity Security Hardening

## When to Use This Skill

Use this skill when:
- Hardening a Duende IdentityServer deployment before promoting to production
- Configuring HTTPS, HSTS, and TLS requirements for the identity server host
- Evaluating or enforcing client secret policies (shared secrets vs. certificates vs. `private_key_jwt`)
- Setting PKCE requirements, restricting grant types, or locking down redirect URI validation
- Configuring Content Security Policy (CSP) and CORS for IdentityServer UI pages and endpoints
- Applying rate limiting to the token endpoint to protect against brute-force and enumeration attacks
- Tuning token lifetimes, enabling reference tokens, or implementing token replay detection
- Rotating signing keys or choosing between RS256 and ES256 algorithms
- Hardening session lifetimes, idle timeouts, and back-channel logout behavior
- Auditing an existing IdentityServer setup against OAuth 2.0 Security Best Current Practice (RFC 9700)

## Core Principles

1. **HTTPS Everywhere** — IdentityServer must only be reachable over HTTPS in production. Any HTTP request should be permanently redirected. HSTS with `includeSubDomains` and `preload` is the minimum bar.
2. **Reduce Token Blast Radius** — Short access token lifetimes, reference tokens for sensitive APIs, and audience validation ensure that a stolen token can do minimal damage.
3. **PKCE is Non-Negotiable** — Every authorization code flow client must use PKCE, regardless of whether it is a public or confidential client. `RequirePkce = true` is the default; never disable it.
4. **Asymmetric Client Authentication** — Prefer certificate-based or `private_key_jwt` client authentication over shared secrets. Secrets that are never transmitted cannot be stolen in transit.
5. **Strict Redirect URI Matching** — Wildcards in redirect URIs are a critical attack surface. Every production URI must be fully qualified and must match exactly.
6. **Restrict Grant Types Per Client** — Every client should only allow the grant types it actually uses. Disabling implicit flow and unused grants is one of the highest-impact, lowest-effort hardening steps.
7. **Defense in Depth** — Combine transport security, token constraints, rate limiting, CSP, and CORS into a layered defense. No single control is sufficient.

## Related Skills

- `identityserver-configuration` — Server-side configuration of clients, resources, and signing keys that these hardening patterns build upon
- `oauth-oidc-protocols` — Protocol-level context for PKCE, PAR, DPoP, and grant type trade-offs
- `aspnetcore-authentication` — Applying OIDC authentication hardening in client applications
- `aspnetcore-authorization` — Enforcing authorization policies that consume the hardened tokens produced here

Docs: https://docs.duendesoftware.com/general/security-best-practices/

---

## Sub-Documents

| Document | Description | When to Load |
|----------|-------------|--------------|
| [docs/cors-csp.md](docs/cors-csp.md) | CORS `ICorsPolicyService` implementation and CSP middleware with header examples | CORS origins, Content-Security-Policy, X-Frame-Options, clickjacking, custom CORS policy |
| [docs/rate-limiting.md](docs/rate-limiting.md) | ASP.NET Core `AddRateLimiter` configuration for token and authorization endpoints | Rate limiting, brute force, 429, sliding window, fixed window, token endpoint protection |
| [docs/session-hardening.md](docs/session-hardening.md) | Server-side sessions, cookie lifetime configuration, back-channel logout client setup | Session security, CookieSlidingExpiration, BackChannelLogoutUri, session fixation, inactivity |

---

## Pattern 1: Transport Security — HTTPS, HSTS, and TLS

IdentityServer handles

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 3 — file references are metadata, not package contents.

identityserver4-migration31.9 KB

View saved version →

---
name: identityserver4-migration
description: Migrating from IdentityServer4 to Duende IdentityServer v8. Covers NuGet package replacement, namespace changes, API surface changes, EF Core database schema migrations, .NET target framework upgrade, license configuration, signing key migration, data protection, and UI template updates.
invocable: false
---

# Migrating from IdentityServer4 to Duende IdentityServer

> **Scope: IdentityServer4 only.** This skill covers migrating from **IdentityServer4** (v3.x and v4.x) to Duende IdentityServer. It does **not** cover migrating from **IdentityServer3** (the older Thinktecture/`IdentityServer3` NuGet package that ran on OWIN/Katana and .NET Framework). IdentityServer3 is a fundamentally different product with a different API surface, configuration model, and hosting stack. If you are on IdentityServer3, you must first port to IdentityServer4 on ASP.NET Core before using this guide.

## When to Use This Skill

- Planning a migration from IdentityServer4 to Duende IdentityServer — running the migration analysis tool
- Upgrading a project from IdentityServer4 (v3.x or v4.x) to Duende IdentityServer v8
- Replacing IdentityServer4 NuGet packages with Duende equivalents
- Updating `IdentityServer4.*` namespaces to `Duende.IdentityServer.*`
- Migrating EF Core database schemas from IdentityServer4 to Duende IdentityServer
- Upgrading the .NET target framework from `netcoreapp3.1` or `net5.0` to a current LTS version
- Resolving breaking API changes between IdentityServer4 and Duende IdentityServer
- Converting `Startup.cs`/`Program.cs` hosting patterns from Generic Host to minimal hosting
- Configuring the Duende IdentityServer license key after migration
- Determining the right Duende license edition based on client inventory (interactive vs. non-interactive)
- Preserving the issuer URI to maintain token and client trust continuity
- Migrating signing keys from IdentityServer4 developer signing credential to Duende automatic key management
- Verifying third-party authentication scheme compatibility with the new .NET version
- Updating UI templates (login, logout, consent) from IdentityServer4 Quickstart UI to Duende templates

## Core Principles

**Migration has two stages if starting from v3.x.** IdentityServer4 v3 → v4 introduced breaking changes in the `ApiResource`/`ApiScope` relationship (parent-child to many-to-many). If you are on v3, first migrate to v4 semantics, then migrate from v4 to Duende. If you are already on IdentityServer4 v4.x, you can go directly to Duende.

**Duende IdentityServer is the direct successor to IdentityServer4.** The API surface is intentionally similar — most code changes are namespace and package renames. Behavioral changes are minimal, but the database schema has new tables and columns for features like automatic key management, server-side sessions, DPoP, and PAR.

**The .NET target framework must be upgraded alongside the IdentityServer migration.** IdentityServer4 ran on `netcoreapp3.1` or `net5.0`. Duende IdentityServer v8 requires `net10.0`. You must follow Microsoft's ASP.NET Core migration guides for each major version jump.

**Database migrations require careful handling to avoid data loss.** The v3 → v4 schema change renames tables and restructures relationships. A naive EF Core migration will drop and recreate tables, losing data. Use the provided delta SQL scripts or manually craft migrations that preserve data.

**Licensing is required for production use.** Duende IdentityServer requires a valid license key for production. Without one, it runs in community/trial mode and logs a warning on startup.

Docs: https://docs.duendesoftware.com/identityserver/upgrades

---

## Migration Path Overview

```
IdentityServer4 v3.x or v4.x
    │
    ▼ (Step 0: Run Migration Analysis Tool against running instance)
    │
    ▼ (Stage 1: v3 → v4 API changes + DB migration — skip if already on v4)
IdentityServer4 v4.x
    │
    ▼ (Stage 2: packages + namespa

Preview of the first 4,000 characters. Read full instructions →

identityserver-api-protection18.7 KB

View saved version →

---
name: identityserver-api-protection
description: "Protecting APIs with Duende IdentityServer: JWT bearer authentication, reference token introspection, scope-based authorization, DPoP/mTLS proof-of-possession validation, local API authentication, and multi-audience scenarios."
invocable: false
---

# Protecting APIs with IdentityServer

## When to Use This Skill

- Configuring JWT bearer authentication in an ASP.NET Core API to validate tokens from IdentityServer
- Setting up reference token introspection with `AddOAuth2Introspection`
- Handling both JWT and reference tokens in the same API using `ForwardReferenceToken`
- Implementing scope-based authorization policies
- Validating Proof-of-Possession tokens (DPoP and mTLS `cnf` claim)
- Protecting APIs hosted in the same application as IdentityServer (local API authentication)
- Securing multi-audience API deployments

Docs: https://docs.duendesoftware.com/identityserver/apis/

## Core Concepts

APIs are the resources that IdentityServer protects. Clients obtain access tokens from IdentityServer, then present those tokens to APIs. The API must validate the token and enforce authorization based on the token's claims (scopes, audience, subject, etc.).

### Token Formats at the API

| Format         | Validation Method                          | Revocable              | Network Dependency                   |
| -------------- | ------------------------------------------ | ---------------------- | ------------------------------------ |
| JWT (`at+jwt`) | Signature verification using issuer's JWKS | No (expires naturally) | None at validation time              |
| Reference      | Introspection endpoint call                | Yes (immediate)        | Requires IdentityServer availability |

## JWT Bearer Authentication

### Basic Setup

Install the standard Microsoft JWT bearer package:

```bash
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
```

Configure the authentication handler:

```csharp
// Program.cs
builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", options =>
    {
        options.Authority = "https://identity.example.com";
        options.Audience = "api1";

        options.TokenValidationParameters.ValidTypes = ["at+jwt"];
    });
```

### Critical: JWT Type Validation

Always set `ValidTypes` to `["at+jwt"]` to protect against JWT confusion attacks. Without this, an attacker could present an identity token (which is also a JWT signed by the same issuer) to an API:

```csharp
// ❌ WRONG: No type validation — vulnerable to JWT confusion
options.TokenValidationParameters = new TokenValidationParameters
{
    ValidateAudience = true
};

// ✅ CORRECT: Validate the at+jwt type header
options.TokenValidationParameters.ValidTypes = ["at+jwt"];
```

IdentityServer sets the `typ` header to `at+jwt` on all access token JWTs (per RFC 9068). This is controlled by `IdentityServerOptions.AccessTokenJwtType`.

### Audience Validation

The `Audience` property on `JwtBearerOptions` validates the `aud` claim in the access token. The audience value comes from the `ApiResource` name in IdentityServer:

```csharp
// IdentityServer configuration
var apiResource = new ApiResource("api1")
{
    Scopes = { "api1.read", "api1.write" }
};

// API configuration
options.Audience = "api1";
```

If `Audience` is not set, audience validation is skipped (not recommended for production).

### Multi-Audience APIs

When an API belongs to multiple logical resources, configure multiple valid audiences:

```csharp
options.TokenValidationParameters.ValidAudiences = ["api1", "api2"];
```

## Reference Token Introspection

For APIs that receive reference tokens (opaque strings rather than JWTs), use the OAuth 2.0 introspection package:

```bash
dotnet add package Duende.IdentityServer.AccessTokenValidation
```

Or use the introspection handler directly:

```bash
dotnet add package Duende.AspNetCore.Authentication.OAuth2Introspection
```

```csharp
// Program.cs
builder.

Preview of the first 4,000 characters. Read full instructions →

identityserver-aspire17.2 KB

View saved version →

---
name: identityserver-aspire
description: Orchestrate Duende IdentityServer in .NET Aspire AppHost — dependency graphs, authority URL wiring, health checks, and multi-instance.
invocable: false
---

# Orchestrating IdentityServer with .NET Aspire

## When to Use This Skill

Use this skill when:
- Adding Duende IdentityServer to an Aspire-orchestrated solution
- Configuring service dependencies so clients and APIs wait for IdentityServer
- Passing IdentityServer's authority URL to dependent services via Aspire
- Wiring database resources for IdentityServer configuration and operational stores
- Ensuring IdentityServer exposes health checks for Aspire startup ordering
- Adding IdentityServer telemetry sources to Aspire service defaults
- Running multiple IdentityServer replicas in Aspire
- Integration testing an Aspire solution that includes IdentityServer

## Core Principles

1. **IdentityServer is a startup dependency** — Every client app and API depends on IdentityServer being available for discovery, token validation, and OIDC flows. Model this with `WithReference()` + `WaitFor()`.
2. **Explicit configuration over service discovery** — Pass the authority URL, client IDs, and scopes as explicit environment variables. App code reads `IConfiguration`/`IOptions<T>`, never Aspire service discovery.
3. **Health checks enable startup ordering** — Aspire's `WaitFor()` requires the target to expose a healthy health check endpoint. IdentityServer must be configured with health checks for startup ordering to work.
4. **Cross-reference, don't duplicate** — General Aspire and IdentityServer patterns are covered by existing skills. This skill covers only the unique orchestration intersection.

## Related Skills

- `identityserver-hosting-setup` — IdentityServer DI and middleware pipeline
- `identityserver-deployment` — production deployment, data protection, health check implementations
- `identityserver-data-storage` — EF Core stores for configuration and operational data

Docs: https://docs.duendesoftware.com/identityserver/deployment/

---

## Pattern 1: AppHost Orchestration Basics

IdentityServer is added to an Aspire AppHost like any ASP.NET Core project. The key
addition is wiring its database dependency so the database is ready before IdentityServer
starts.

```csharp
var builder = DistributedApplication.CreateBuilder(args);

var sqlServer = builder.AddSqlServer("sql");
var identityDb = sqlServer.AddDatabase("identitydb");

var identityServer = builder.AddProject<Projects.IdentityServer>("identity-server")
    .WithReference(identityDb)
    .WaitFor(sqlServer);

builder.Build().Run();
```

`WaitFor(sqlServer)` ensures the database is accepting connections before IdentityServer
starts. This matters because IdentityServer connects to EF Core stores on startup for
configuration and operational data.

> **Important:** The IdentityServer project itself is a standard ASP.NET Core application.
> See `identityserver-hosting-setup` for DI registration and middleware pipeline setup.
> This skill focuses only on how the AppHost orchestrates it.

---

## Pattern 2: Service Dependency Graph

This is the most critical pattern. Clients and APIs must depend on IdentityServer
because:

- **Clients** download the discovery document (`.well-known/openid-configuration`) at
  startup to configure OIDC flows
- **APIs** configured with JWT Bearer authentication download JWKS (signing keys) from
  IdentityServer at startup to validate tokens
- **OIDC login redirects** fail if IdentityServer isn't running when a user tries to
  sign in

Without explicit dependency ordering, services start in parallel and fail with cryptic
"unable to obtain configuration" errors.

### Full dependency graph

```csharp
var builder = DistributedApplication.CreateBuilder(args);

var sqlServer = builder.AddSqlServer("sql");
var identityDb = sqlServer.AddDatabase("identitydb");

var identityServer = builder.AddProject<Projects.IdentityServer>("identity-server")
    .WithRefer

Preview of the first 4,000 characters. Read full instructions →

identityserver-configuration21.2 KB

View saved version →

---
name: identityserver-configuration
description: Configure Duende IdentityServer including client definitions, API resources, identity resources, scopes, signing credentials, and server-side sessions. Covers client types (M2M, interactive, SPA), grant types, API Scopes vs API Resources vs Identity Resources, secret management, and client authentication methods. Includes both in-memory and database-backed configuration.
invocable: false
---

# Duende IdentityServer Configuration

## When to Use This Skill

Use this skill when:
- Setting up a new Duende IdentityServer host
- Defining or modifying client registrations
- Configuring API resources, API scopes, or identity resources
- Setting up signing key management (automatic or static)
- Enabling server-side sessions
- Tuning `IdentityServerOptions` for production deployments
- Migrating from IdentityServer4 to Duende IdentityServer

## Core Principles

1. **Authorization Code + PKCE by Default** — Use `GrantTypes.Code` for all interactive clients. Never use implicit flow for new applications.
2. **Least Privilege Scopes** — Grant clients only the scopes they need. Avoid wildcard or overly broad scope assignments.
3. **Automatic Key Management** — Prefer the built-in automatic key rotation over static key configuration in production.
4. **API Resources for Audience Isolation** — Use `ApiResource` to control the `aud` claim and isolate API boundaries. Use `ApiScope` for fine-grained permission modeling within those boundaries.
5. **Server-Side Sessions for Enterprise** — Enable server-side sessions when you need centralized session management, back-channel logout, or session queries.

## Related Skills

- `identityserver-stores` — EF Core persistence for configuration and operational data
- `oauth-oidc-protocols` — Protocol fundamentals that underpin these configuration choices
- `identity-security-hardening` — Production hardening of IdentityServer deployments
- `token-management` — Client-side token lifecycle with Duende.AccessTokenManagement
- `aspnetcore-authentication` — Configuring OIDC authentication in client applications

Docs: https://docs.duendesoftware.com/identityserver/configuration

---

## Sub-Documents

Load these sub-documents when the user's question specifically targets one of these areas:

| Document | Description | When to Load |
|----------|-------------|--------------|
| [docs/client-types.md](docs/client-types.md) | Grant type selection matrix, client property reference tables, client authentication methods (shared secret, private_key_jwt, mTLS), secret rollover, and CORS | private_key_jwt, mTLS, secret rotation, refresh token settings, client authentication, CORS origins |
| [docs/resources-scopes.md](docs/resources-scopes.md) | Resource type decision matrix, identity resources, API scopes (including parameterized scopes), and API resources with audience isolation | aud claim, audience isolation, parameterized scopes, IScopeParser, IResourceValidator, EmitStaticAudienceClaim, API Resources, Identity Resources |

---

## Pattern 1: Hosting and Basic Setup

Register Duende IdentityServer in `Program.cs` with `AddIdentityServer`. All configuration flows from the `IdentityServerOptions` lambda and the builder's fluent API.

```csharp
var builder = WebApplication.CreateBuilder(args);

var idsvrBuilder = builder.Services.AddIdentityServer(options =>
{
    // Let the issuer be inferred from the request URL (recommended)
    // options.IssuerUri = "https://identity.example.com"; // Only set when behind a reverse proxy

    // Enable events for diagnostics
    options.Events.RaiseErrorEvents = true;
    options.Events.RaiseInformationEvents = true;
    options.Events.RaiseFailureEvents = true;
    options.Events.RaiseSuccessEvents = true;
})
    .AddInMemoryIdentityResources(Config.IdentityResources)
    .AddInMemoryApiScopes(Config.ApiScopes)
    .AddInMemoryClients(Config.Clients);

var app = builder.Build();
app.UseIdentityServer(); // Includes UseAuthentic

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 2 — file references are metadata, not package contents.

identityserver-dcr11.2 KB

View saved version →

---
name: identityserver-dcr
description: "Configuring Dynamic Client Registration (DCR) in Duende IdentityServer: endpoint setup, authorization policies, custom validation with DynamicClientRegistrationValidator, software statement validation, IClientConfigurationStore, and separate DCR hosting."
invocable: false
---

# Dynamic Client Registration (DCR)

## When to Use This Skill

- Setting up Dynamic Client Registration (DCR) at `/connect/dcr`
- Securing the DCR endpoint with authorization policies
- Customizing DCR validation with `DynamicClientRegistrationValidator`
- Implementing software statement validation
- Persisting dynamically registered clients with `IClientConfigurationStore`
- Hosting DCR in a separate application from IdentityServer

## Core Principles

- DCR requires the `Duende.IdentityServer.Configuration` NuGet package
- Requires **Business Edition** or higher license
- Always secure the `/connect/dcr` endpoint with an authorization policy — never expose it unauthenticated
- Enforce PKCE and restrict allowed grant types in the DCR validator
- Use persistent stores (database) for dynamically registered clients in production

Docs: https://docs.duendesoftware.com/identityserver/configuration/dcr

## Overview

Dynamic Client Registration allows clients to register themselves at the `/connect/dcr` endpoint per RFC 7591. This feature requires the **Business Edition** or higher and has been available since version 6.3.

DCR uses a separate NuGet package and can be hosted in the same application as IdentityServer or in a separate host.

### Setup

```bash
dotnet add package Duende.IdentityServer.Configuration
```

```csharp
// Program.cs
builder.Services.AddIdentityServer()
    .AddInMemoryClients(Config.Clients)
    .AddInMemoryIdentityResources(Config.IdentityResources)
    .AddInMemoryApiScopes(Config.ApiScopes);

builder.Services.AddIdentityServerConfiguration();

var app = builder.Build();

app.UseIdentityServer();
app.UseAuthorization();

app.MapDynamicClientRegistration();

app.Run();
```

`MapDynamicClientRegistration()` is an endpoint-routing extension from the **`Duende.IdentityServer.Configuration`** package (separate from `Duende.IdentityServer`). Call it where you configure the pipeline/endpoint routing — in the quickstart/template hosts this is the `ConfigurePipeline()` method (`HostingExtensions.cs`), alongside `UseIdentityServer()`. `AddIdentityServerConfiguration()` registers the DCR services; `MapDynamicClientRegistration()` maps the `/connect/dcr` endpoint. Both are required.

### Securing the DCR Endpoint

Apply standard ASP.NET Core authorization policies to the DCR endpoint:

```csharp
// Using JWT bearer for the DCR endpoint
builder.Services.AddAuthentication()
    .AddJwtBearer("dcr", options =>
    {
        options.Authority = "https://identity.example.com";
        options.Audience = "IdentityServer.Configuration";
        options.TokenValidationParameters.ValidTypes = ["at+jwt"];
    });

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("dcr", policy =>
    {
        policy.AddAuthenticationSchemes("dcr");
        policy.RequireAuthenticatedUser();
        policy.RequireClaim("scope", "IdentityServer.Configuration");
    });
});

app.MapDynamicClientRegistration()
    .RequireAuthorization("dcr");
```

### DCR Request and Response

**Registration request:**

```
POST /connect/dcr HTTP/1.1
Content-Type: application/json
Authorization: Bearer <access_token>

{
    "client_name": "My Dynamic App",
    "redirect_uris": ["https://app.example.com/callback"],
    "grant_types": ["authorization_code"],
    "response_types": ["code"],
    "token_endpoint_auth_method": "client_secret_basic"
}
```

**Registration response:**

```json
{
  "client_id": "generated-client-id",
  "client_secret": "generated-secret",
  "client_name": "My Dynamic App",
  "redirect_uris": ["https://app.example.com/callback"],
  "grant_types": ["authorization_code"],
  "response_types": ["code"],
  "reg

Preview of the first 4,000 characters. Read full instructions →

identityserver-deployment28.5 KB

View saved version →

---
name: identityserver-deployment
description: "Guide for deploying Duende IdentityServer to production, covering reverse proxy configuration, data protection, health checks, distributed caching, multi-instance deployment, OpenTelemetry integration, logging, and common deployment pitfalls."
invocable: false
---

# IdentityServer Deployment, Proxies, and Production Readiness

## When to Use This Skill

- Deploying IdentityServer behind a reverse proxy or load balancer
- Configuring ASP.NET Core Data Protection for production persistence
- Implementing health checks for monitoring IdentityServer instances
- Setting up distributed caching for multi-instance deployments
- Configuring OpenTelemetry for metrics, traces, and logs
- Troubleshooting common deployment issues (HTTPS downgrade, cookie problems, key rotation failures)
- Understanding the difference between Data Protection keys and IdentityServer signing keys
- Setting up logging and events for production monitoring

Docs: https://docs.duendesoftware.com/identityserver/deployment

## Deployment Architecture

IdentityServer is ASP.NET Core middleware. It can be hosted with the same diversity of technology as any ASP.NET Core application:

- **Hosting**: On-premises, cloud (Azure, AWS, GCP), containers, Kubernetes
- **Web servers**: Kestrel, IIS, Nginx, Apache
- **Artifacts**: Files, containers (no Dockerfile needed with `dotnet publish /t:PublishContainer`)
- **Scaling**: Horizontal with load balancers; requires shared state for multi-instance

## Reverse Proxy and Load Balancer Configuration

### The Problem

When IdentityServer runs behind a proxy that terminates TLS or changes the originating IP, the middleware sees incorrect request information. This causes:

- HTTPS requests downgraded to HTTP
- HTTP issuer published in `.well-known/openid-configuration` instead of HTTPS
- Incorrect host names in discovery document or redirects
- Cookies missing the `Secure` attribute (breaks `SameSite` behavior)

### Solution: ForwardedHeaders Middleware

Most proxies set `X-Forwarded-For` and `X-Forwarded-Proto` headers. Configure ASP.NET Core to read them.

#### Option 1: Environment Variable (Simplest)

Set `ASPNETCORE_FORWARDEDHEADERS_ENABLED=true`. This automatically adds the middleware and accepts forwarded headers from any single proxy. Best for cloud-hosted environments and Kubernetes.

#### Option 2: Explicit Configuration (More Control)

```csharp
// Program.cs
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedHost |
                                ForwardedHeaders.XForwardedProto;

    // Add the IP address of your known proxy
    options.KnownProxies.Add(IPAddress.Parse("203.0.113.42"));

    // Or use a network range
    // var network = new IPNetwork(IPAddress.Parse("198.51.100.0"), 24);
    // options.KnownNetworks.Add(network);

    // Number of proxies in front of the app
    options.ForwardLimit = 1;
});
```

**Important**: The ForwardedHeaders middleware must run **early** in the pipeline, before IdentityServer middleware and ASP.NET authentication middleware.

### Default KnownNetworks

By default, `KnownNetworks` and `KnownProxies` support localhost (`127.0.0.1/8` and `::1`). This is useful for local development or when the proxy and .NET host are on the same machine. In production, configure the actual proxy addresses.

## ASP.NET Core Data Protection

> **Cross-cutting concern:** Data protection is critical for all Duende products — both IdentityServer and BFF. See [ASP.NET Core Data Protection](https://docs.duendesoftware.com/general/data-protection/) for comprehensive guidance covering all Duende SDKs.

### Why It Matters

Data Protection is critical for IdentityServer. It encrypts and signs sensitive data including:

- Signing keys at rest (when automatic key management is used)
- Persisted grants at rest
- Server-side session data at rest
- State parameters for external OIDC providers

Preview of the first 4,000 characters. Read full instructions →

identityserver-hosting-setup14.7 KB

View saved version →

---
name: identityserver-hosting-setup
description: Setting up and hosting Duende IdentityServer in ASP.NET Core applications, including DI registration, middleware pipeline, hosting patterns, essential options, license configuration, and ASP.NET Identity integration.
invocable: false
---

# Setting Up and Hosting IdentityServer

## When to Use This Skill

- Setting up a new Duende IdentityServer project from scratch
- Configuring the ASP.NET Core DI system and middleware pipeline for IdentityServer
- Deciding between separate vs shared hosting patterns
- Integrating IdentityServer with ASP.NET Identity for user management
- Configuring `IdentityServerOptions` (issuer, key management, endpoints)
- Setting up proxy/load balancer forwarded headers
- Configuring data protection for production deployments
- Understanding the IdentityServer middleware pipeline ordering

Docs: https://docs.duendesoftware.com/identityserver/fundamentals

## Core Concepts

Duende IdentityServer is middleware that adds OpenID Connect and OAuth 2.0 endpoints to an ASP.NET Core host. It requires two setup steps: registering services in DI and adding middleware to the request pipeline.

### Architecture Decision: Separate vs Shared Host

IdentityServer should be in its own dedicated application to minimize the attack surface. While it is technically possible to co-host IdentityServer with clients or APIs, this is not recommended.

| Hosting Pattern                 | Pros                                                                 | Cons                                        |
| ------------------------------- | -------------------------------------------------------------------- | ------------------------------------------- |
| **Separate host (recommended)** | Minimal attack surface, independent scaling, clear security boundary | Additional deployment artifact              |
| **Shared with web app**         | Fewer projects                                                       | Larger attack surface, coupled deployments  |
| **Shared with API**             | Fewer projects                                                       | Security risk, conflicting middleware needs |

## Step 1: Install Templates and Create a Project

```bash
dotnet new install Duende.Templates
dotnet new duende-is-empty -n IdentityServer
```

The `duende-is-empty` template creates a minimal project with the IdentityServer NuGet package installed and basic configuration.

## Step 2: Register IdentityServer Services (DI)

Call `AddIdentityServer` on the service collection to register all necessary services. This method also calls `AddAuthentication` internally.

```csharp
// Program.cs
var idsvrBuilder = builder.Services.AddIdentityServer(options =>
{
    // Configure IdentityServerOptions here
});
```

### Adding Configuration Stores

The builder object returned by `AddIdentityServer` provides extension methods to add configuration stores for clients, resources, and scopes:

```csharp
// Program.cs
var idsvrBuilder = builder.Services.AddIdentityServer()
    .AddInMemoryClients(Config.Clients)
    .AddInMemoryIdentityResources(Config.IdentityResources)
    .AddInMemoryApiScopes(Config.ApiScopes);
```

**Store options:**

- **In-memory stores** - good for development, demos, and static configuration
- **EntityFramework stores** - production-ready, supports dynamic configuration
- **Custom stores** - implement the store interfaces for any backing store

### Minimal Working Example

```csharp
// Program.cs
builder.Services.AddIdentityServer()
    .AddInMemoryApiScopes(Config.ApiScopes)
    .AddInMemoryClients(Config.Clients);

var app = builder.Build();

app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthorization();
app.MapDefaultControllerRoute();

app.Run();
```

## Step 3: Configure the Request Pipeline

Add `UseIdentityServer` middleware to the pipeline. Pipeline ordering is critical.

```csharp
// Program.cs
var app = builder.Build();
app.UseStatic

Preview of the first 4,000 characters. Read full instructions →

identityserver-key-management18.7 KB

View saved version →

---
name: identityserver-key-management
description: Managing cryptographic signing keys in Duende IdentityServer, including automatic key management, KeyManagementOptions, data protection at rest, static key configuration, migration from static to automatic, and multi-instance deployment considerations.
invocable: false
---

# Key Management and Signing

## When to Use This Skill

- Configuring automatic key management for signing token keys
- Setting up static/manual signing keys from certificates or key vaults
- Configuring key rotation intervals and key lifecycle
- Migrating from static keys to automatic key management
- Deploying IdentityServer in load-balanced or multi-instance environments
- Protecting keys at rest using data protection
- Configuring per-algorithm or per-resource signing
- Troubleshooting key-related errors (CryptographicException, unprotecting key failures)

Docs: https://docs.duendesoftware.com/identityserver/fundamentals/key-management/

## Core Concepts

IdentityServer issues cryptographically signed tokens: identity tokens, JWT access tokens, and logout tokens. These signatures require key material that can be managed automatically or manually (statically).

### Supported Signing Algorithms

IdentityServer supports the `RS`, `PS`, and `ES` families:

| Family | Algorithms                | Key Type |
| ------ | ------------------------- | -------- |
| RS     | `RS256`, `RS384`, `RS512` | RSA      |
| PS     | `PS256`, `PS384`, `PS512` | RSA      |
| ES     | `ES256`, `ES384`, `ES512` | ECDSA    |

### Core Rotation Rule

Regardless of approach, safe rotation obeys one rule: **publish a new public key in discovery (JWKS) BEFORE using it to sign tokens, and keep a RETIRED public key published until every token signed with it has expired.** Automatic Key Management enforces this overlap for you (Announced → Signing → Retired phases). With static/manual keys you must perform the overlap yourself via phased rotation (see [Manual Key Rotation](#manual-key-rotation-phased-approach)).

## Automatic Key Management (Recommended)

Automatic Key Management handles key creation, rotation, announcement, and retirement. It is enabled by default and is part of the Business and Enterprise editions.

### Key Lifecycle

Keys move through four phases:

```
Announced --> Signing --> Retired --> Deleted
   |             |            |          |
   |<--Propagation-->|        |          |
   |             |<--Rotation-->|        |
   |             |            |<--Retention-->|
```

| Phase         | Duration (default)                           | Purpose                                       |
| ------------- | -------------------------------------------- | --------------------------------------------- |
| **Announced** | 14 days (`PropagationTime`)                  | Published in discovery, not yet signing       |
| **Signing**   | 76 days (RotationInterval - PropagationTime) | Active signing credential                     |
| **Retired**   | 14 days (`RetentionDuration`)                | In discovery for token validation only        |
| **Deleted**   | After retention                              | Removed from discovery and optionally deleted |

**Default schedule:** Keys rotate every 90 days, announced 14 days early, retained 14 days after rotation.

### Configuration

```csharp
// Program.cs
var idsvrBuilder = builder.Services.AddIdentityServer(options =>
{
    // Key rotates every 30 days
    options.KeyManagement.RotationInterval = TimeSpan.FromDays(30);

    // Announce new key 2 days in advance in discovery
    options.KeyManagement.PropagationTime = TimeSpan.FromDays(2);

    // Keep old key for 7 days in discovery for validation
    options.KeyManagement.RetentionDuration = TimeSpan.FromDays(7);

    // Don't delete keys after their retention period is over
    options.KeyManagement.DeleteRetiredKeys = false;
});
```

### KeyManagement Options Reference

| Property                             | Default   | Desc

Preview of the first 4,000 characters. Read full instructions →

identityserver-saml22.4 KB

View saved version →

---
name: identityserver-saml
description: "Configuring Duende IdentityServer as a SAML 2.0 Identity Provider (IdP): service provider registration, SSO and SLO flows, claim mappings, extensibility interfaces, and production deployment patterns."
invocable: false
---

# SAML 2.0 Identity Provider

## When to Use This Skill

- Setting up IdentityServer as a SAML 2.0 Identity Provider (IdP)
- Registering SAML Service Providers with the `SamlServiceProvider` model
- Configuring SP-initiated SSO and Single Logout (SLO) flows
- Customizing claim-to-attribute mappings via `ClaimMappings` or extensibility interfaces
- Implementing production SP stores (EF Core, custom `ISamlServiceProviderStore`)
- Extending SAML behavior (custom NameID generation, signing, metadata, multi-tenant issuer)
- Linking an external SAML IdP as a federated authentication source (SP mode)

## Core Principles

- SAML 2.0 IdP support is **built into Duende.IdentityServer** (v8.0+) — no separate NuGet package
- Requires **Standard (add-on), Advanced, or Custom Edition** license
- SP-initiated SSO is the default; IdP-initiated SSO is opt-in per service provider
- `SignAssertion` is the default signing behavior; `SignResponse` is recommended for most deployments
- Use EF Core stores for service providers in production; in-memory is for development only
- Front-channel SLO uses iframes (not redirect chains); partial logout is expected behavior
- The claim pipeline flows: AllowedScopes → RequestedClaimTypes → ClaimMappings

Docs: https://docs.duendesoftware.com/identityserver/saml

## Setup

```csharp
builder.Services.AddIdentityServer()
    .AddInMemoryClients(Config.Clients)
    .AddInMemoryIdentityResources(Config.IdentityResources)
    .AddSaml()
    .AddInMemorySamlServiceProviders(Config.SamlServiceProviders);
```

Update the login page to call `DenyAuthenticationAsync` for SAML cancellation support (when user cancels login during a SAML flow).

## Endpoints

| Endpoint | Path | Purpose |
|----------|------|---------|
| Metadata | `/Saml2` | IdP metadata (certificates, endpoints, NameID formats) |
| Sign-in | `/Saml2/SSO` | Receives AuthnRequest (GET/POST) |
| Sign-in Callback | `/Saml2/SSO/Callback` | Builds SAML Response after authentication |
| Logout | `/Saml2/SLO` | Handles LogoutRequest/LogoutResponse |
| Logout Callback | `/Saml2/SLO/Callback` | Completes SLO round-trip |

Paths are customizable via `SamlOptions.Endpoints`.

### Profile Active Check

`IProfileService.IsActiveAsync` is called on every SSO request, including when the user already has an active session.
If `IsActive` returns `false`: passive requests (`IsPassive=true`) receive a SAML `NoPassive` error response; all other requests are redirected to the login page.
This is the recommended mechanism for blocking disabled or locked accounts without waiting for session expiry.

### Observability

All SAML endpoints emit audit events and OpenTelemetry telemetry counters.
SSO and SLO endpoints participate in distributed tracing via the `Duende.IdentityServer` activity source.
See docs for SAML audit events and `TelemetryMetricsCounters.SamlSso`.

## SamlServiceProvider Model

```csharp
new SamlServiceProvider
{
    // Required
    EntityId = "https://sp.example.com",
    DisplayName = "Example SP",

    // ACS endpoints (HTTP-POST only, indexed)
    AssertionConsumerServiceUrls =
    [
        new IndexedEndpoint
        {
            Location = "https://sp.example.com/acs",
            Binding = SamlBinding.HttpPost,
            Index = 0,
            IsDefault = true
        }
    ],

    // Single Logout (HTTP-Redirect only)
    SingleLogoutServiceUrls =
    [
        new SamlEndpointType
        {
            Location = "https://sp.example.com/saml/slo",
            Binding = SamlBinding.HttpRedirect
        }
    ],

    // Security
    SigningBehavior = SamlSigningBehavior.SignAssertion,
    RequireSignedAuthnRequests = true,
    Certificates =
    [
        new ServiceProviderCertificate
 

Preview of the first 4,000 characters. Read full instructions →

identityserver-sessions-providers25.7 KB

View saved version →

---
name: identityserver-sessions-providers
description: "Guide for configuring server-side sessions, session management and querying, inactivity timeout, dynamic identity providers, and CIBA (Client Initiated Backchannel Authentication) in Duende IdentityServer."
invocable: false
---

# IdentityServer Sessions, Dynamic Providers, and CIBA

## When to Use This Skill

- Enabling and configuring server-side sessions for authentication state management
- Implementing session querying, revocation, and administrative tooling via `ISessionManagementService`
- Configuring inactivity timeout across IdentityServer and client applications
- Setting up the Entity Framework Core session store or implementing a custom `IServerSideSessionStore`
- Adding dynamic identity providers loaded from a database at runtime
- Implementing custom non-OIDC dynamic provider types (Google, SAML, etc.)
- Building a CIBA (Client Initiated Backchannel Authentication) flow
- Understanding edition requirements (Business vs Enterprise) for these features

Docs: https://docs.duendesoftware.com/identityserver/ui/server-side-sessions/

## Server-Side Sessions

### What Problem Do They Solve?

By default, ASP.NET Core stores all authentication session state in a self-contained cookie. This creates several challenges:

| Problem                      | Impact                                                                            |
| ---------------------------- | --------------------------------------------------------------------------------- |
| Cookie size growth           | As clients are tracked, the cookie grows; large cookies can exceed browser limits |
| No session visibility        | Cannot query how many active sessions exist                                       |
| No administrative revocation | Cannot terminate a session from outside the user's browser                        |
| No server-side coordination  | Cannot detect inactivity or synchronize session expiration across clients         |

Server-side sessions store authentication state on the server, keeping only a session reference in the cookie.

### Edition Requirements

Server-side sessions are part of the **Duende IdentityServer Business and Enterprise Edition**.

### Enabling Server-Side Sessions

```csharp
// Program.cs
builder.Services.AddIdentityServer()
    .AddServerSideSessions();
```

**Important**: This call must come after any custom `IRefreshTokenService` implementation registration. Order matters in the ASP.NET Core service provider.

By default, sessions are stored in-memory. For production, use Entity Framework Core or a custom store.

### Using Entity Framework Core Store

```csharp
// Program.cs
builder.Services.AddIdentityServer()
    .AddServerSideSessions()
    .AddOperationalStore(options =>
    {
        options.ConfigureDbContext = builder =>
            builder.UseSqlServer(connectionString,
                sql => sql.MigrationsAssembly(migrationsAssembly));
    });
```

The EF Core implementation is included in the operational store and supports the `IServerSideSessionStore` interface automatically.

### Custom Session Store

Implement `IServerSideSessionStore` and register it:

```csharp
// Program.cs — two-step registration
builder.Services.AddIdentityServer()
    .AddServerSideSessions()
    .AddServerSideSessionStore<YourCustomStore>();

// Or one-step registration
builder.Services.AddIdentityServer()
    .AddServerSideSessions<YourCustomStore>();
```

### Data Stored Server-Side

The session stores the serialized ASP.NET Core `AuthenticationTicket` (all claims + `AuthenticationProperties.Items`). The data is protected using ASP.NET Core's Data Protection API.

Queryable indices extracted from the session:

| Index        | Source                                            |
| ------------ | ------------------------------------------------- |
| Subject ID   | `sub` claim value                                 |
| Session ID   | `sid` claim value                    

Preview of the first 4,000 characters. Read full instructions →

identityserver-stores37.5 KB

View saved version →

---
name: identityserver-stores
description: Implement and customize Duende IdentityServer stores including configuration store, operational store, and Entity Framework Core integration. Covers migrations, custom store implementations, caching strategies, server-side sessions, signing key storage, token cleanup, and multi-tenant patterns.
invocable: false
---

# Duende IdentityServer Stores

## When to Use This Skill

- You are wiring up `AddConfigurationStore()` or `AddOperationalStore()` with EF Core and need correct registration, migration assembly setup, and schema configuration.
- You are implementing a custom `IClientStore`, `IResourceStore`, `IPersistedGrantStore`, or `ISigningKeyStore` against a non-EF data source (Redis, Mongo, external API, etc.).
- You need to enable and tune configuration store caching (`AddConfigurationStoreCache()`, expiration windows, distributed cache setup) to reduce database load.
- You are managing EF Core migrations across IdentityServer versions and need to correctly handle schema drift for `ConfigurationDbContext` and `PersistedGrantDbContext`.
- You are enabling server-side sessions (`IServerSideSessionStore`) and need to understand session lifecycle, cleanup, and storage integration.
- You are troubleshooting stale client or resource data, expired token accumulation, or signing key rotation failures tied to store configuration.
- You are designing a multi-tenant IdentityServer deployment and need to choose between database-per-tenant and shared-database store strategies.

## Core Principles

**Store interfaces decouple IdentityServer from persistence.** All data access goes through store interfaces registered in the ASP.NET Core DI container. IdentityServer does not care what database backs them — EF Core, Redis, MongoDB, or a static in-memory collection are all equally valid.

**Two independent store categories exist: configuration and operational.** They can be used independently or together. Configuration data is relatively static (clients, resources, CORS); operational data is dynamic and high-write (grants, sessions, signing keys). They should be sized, cached, and maintained with those distinct access patterns in mind.

**Operational data is protected at rest.** The `Data` payload of persisted grants and serialized signing keys is encrypted using the ASP.NET Core Data Protection API. Key rotation and Data Protection configuration must be coordinated — a lost Data Protection key makes stored grants and signing keys unreadable.

**Consumed grants are soft-deleted, not immediately removed.** One-time-use grants (e.g., authorization codes, one-time refresh tokens) are marked with a `ConsumedTime` rather than deleted. This enables threat detection in custom `IRefreshTokenService` implementations. Do not confuse consumed with expired — the token cleanup service only removes records past their `Expiration`, not consumed ones (unless `RemoveConsumedTokens` is enabled).

**EF Core schema changes are your responsibility.** Duende does not ship automatic migration scripts or schema upgrade tooling. You own migration creation, application, and data migration between IdentityServer versions.

Docs: https://docs.duendesoftware.com/identityserver/data

---

## NuGet Package

```bash
dotnet add package Duende.IdentityServer.EntityFramework
```

This package provides EF Core implementations for all configuration and operational store interfaces.

---

## Store Architecture

IdentityServer's data is split into two categories, each with its own set of store interfaces:

```
┌─────────────────────────────────────────────────────────────┐
│                    IdentityServer Runtime                    │
├──────────────────────────┬──────────────────────────────────┤
│    Configuration Data    │       Operational Data           │
│                          │                                  │
│  • Clients               │  • Authorization codes           │
│  • API Resources         │  • Reference tokens

Preview of the first 4,000 characters. Read full instructions →

identityserver-token-lifecycle20.2 KB

View saved version →

---
name: identityserver-token-lifecycle
description: "Guide for implementing token types, refresh token management, token exchange (RFC 8693), extension grants, IProfileService claims customization, and token lifetime best practices in Duende IdentityServer."
invocable: false
---

# IdentityServer Token Types, Refresh Tokens, and Token Exchange

## When to Use This Skill

- Choosing between JWT and reference access tokens for a client
- Configuring refresh token rotation, sliding expiration, or replay detection
- Implementing token exchange (RFC 8693) for impersonation or delegation
- Building an extension grant validator (`IExtensionGrantValidator`)
- Customizing which claims appear in identity tokens, access tokens, or userinfo responses via `IProfileService`
- Setting token lifetime policies for access tokens and refresh tokens
- Issuing internal tokens from extensibility code via `IIdentityServerTools`
- Understanding identity tokens vs access tokens and their intended audiences

Docs: https://docs.duendesoftware.com/identityserver/tokens

## Token Types Overview

Duende IdentityServer issues three primary token types:

| Token Type     | Purpose                                            | Audience                              | Format           |
| -------------- | -------------------------------------------------- | ------------------------------------- | ---------------- |
| Identity Token | Communicates authentication event to the client    | Client application only (`aud` claim) | Always JWT       |
| Access Token   | Authorizes access to a protected resource (API)    | API / Resource Server                 | JWT or Reference |
| Refresh Token  | Obtains new access tokens without user interaction | Token endpoint only                   | Opaque handle    |

### Key Principles

- Identity tokens are **solely for the client application** that initiated the authentication. Never send an identity token to an API.
- Access tokens are for APIs. They contain client ID, scopes, expiration, and optionally user claims.
- Refresh tokens enable long-lived API access by allowing the client to request new access tokens silently.

## Identity Tokens

Identity tokens are JWTs that describe "what happened at the token service". They contain:

- `iss` — the issuer (your IdentityServer URL)
- `sub` — the authenticated user's unique identifier
- `aud` — the client that requested authentication
- `auth_time` — when the user authenticated
- `amr` — authentication method (e.g., `pwd`)
- `idp` — identity provider used (e.g., `local`)
- `sid` — the session ID
- `nonce` — ensures the token is consumed only once at the client

```json
{
  "iss": "https://localhost:5001",
  "nbf": 1609932802,
  "iat": 1609932802,
  "exp": 1609933102,
  "aud": "web_app",
  "amr": ["pwd"],
  "nonce": "63745529591...I3ZTIyOTZmZTNj",
  "sid": "F6E6F2EDE86EB8731EF609A4FE40ED89",
  "auth_time": 1609932794,
  "idp": "local",
  "sub": "88421113",
  "name": "Bob"
}
```

## Access Tokens: JWT vs Reference

### JWT Access Tokens

All claims are embedded in the token. The API validates the token by checking the signature using the issuer's public keys (from the JWKS endpoint). JWTs **cannot be revoked** before their expiration — the only invalidation mechanism is waiting for `exp`.

```json
{
  "iss": "https://localhost:5001",
  "exp": 1609936401,
  "aud": "urn:resource1",
  "scope": "openid resource1.scope1 offline_access",
  "client_id": "web_app",
  "sub": "88421113",
  "jti": "2C56A356A306E64AFC7D2C6399E23A17"
}
```

### Reference Access Tokens

Reference tokens are **pointers** to token data stored in the persisted grant store. The API must call the **introspection endpoint** to validate the token. Reference tokens support **immediate revocation** by deleting the stored data.

```csharp
// Configure a client to use reference tokens
client.AccessTokenType = AccessTokenType.Reference;
```

The API consuming reference tokens must have a secret configured on the `ApiReso

Preview of the first 4,000 characters. Read full instructions →

identityserver-token-security27.4 KB

View saved version →

---
name: identityserver-token-security
description: Advanced token security features in Duende IdentityServer including DPoP, mTLS certificate binding, Pushed Authorization Requests (PAR), JWT Secured Authorization Requests (JAR), and FAPI 2.0 compliance configuration.
invocable: false
---

# Advanced Token Security (DPoP, mTLS, PAR, JAR, FAPI)

## When to Use This Skill

- Implementing Proof-of-Possession (PoP) tokens with DPoP or mTLS
- Configuring Pushed Authorization Requests (PAR) for front-channel parameter security
- Setting up JWT Secured Authorization Requests (JAR) for tamperproof authorize requests
- Building FAPI 2.0 compliant authorization servers
- Choosing between DPoP and mTLS for sender-constrained tokens
- Configuring APIs to validate proof-of-possession tokens
- Meeting regulatory or industry security requirements (open banking, e-health, e-government)

Docs: https://docs.duendesoftware.com/identityserver/tokens/

## Proof-of-Possession Tokens: Why They Matter

Default OAuth access tokens are **bearer tokens** -- anyone who possesses the token can use it. If a token leaks, a malicious third party can impersonate the client/user.

**Proof-of-Possession (PoP) tokens** are cryptographically bound to the client that requested them via the `cnf` (confirmation) claim:

```json
{
  "iss": "https://identity.example.com",
  "aud": "urn:api",
  "client_id": "web_app",
  "sub": "88421113",
  "cnf": "confirmation_method"
}
```

When using reference tokens, the `cnf` claim is returned from the introspection endpoint.

## DPoP vs mTLS: Decision Matrix

| Factor                    | DPoP                               | mTLS                                               |
| ------------------------- | ---------------------------------- | -------------------------------------------------- |
| **Edition required**      | Enterprise                         | All editions (binding); Enterprise (some features) |
| **Minimum version**       | 6.3                                | All versions                                       |
| **Key management**        | Application-layer JWK (dynamic)    | X.509 certificate (TLS layer)                      |
| **Infrastructure**        | No TLS changes needed              | Requires TLS client certificate infrastructure     |
| **Deployment complexity** | Lower                              | Higher (certificate distribution, renewal)         |
| **Protocol layer**        | HTTP headers (`DPoP` header)       | TLS channel                                        |
| **Public clients**        | Supported (mobile/SPA)             | Harder for public clients                          |
| **FAPI 2.0**              | Accepted                           | Accepted                                           |
| **Replay protection**     | Nonce mechanism + `iat` validation | TLS channel binding                                |
| **Recommendation**        | Start here for most use cases      | When TLS infrastructure already exists             |

## Mutual TLS (mTLS)

### How It Works

IdentityServer embeds the SHA-256 thumbprint of the client's X.509 certificate into the access token via the `cnf` claim:

```json
{
  "cnf": { "x5t#S256": "bwcK0esc3ACC3DB2Y5_lESsXE8o9ltc05O89jdN-dg2" }
}
```

The client must use the same certificate when calling APIs. APIs validate the `cnf` claim against the TLS client certificate thumbprint.

### mTLS for Client Authentication

Configure IdentityServer to accept client certificates:

```csharp
// Program.cs
var idsvrBuilder = builder.Services.AddIdentityServer(options =>
{
    options.MutualTls.Enabled = true;
    options.MutualTls.DomainName = "mtls"; // mTLS endpoints on mtls subdomain
    options.MutualTls.ClientCertificateAuthenticationScheme = "Certificate";
});

idsvrBuilder.AddMutualTlsSecretValidators();

builder.Services.AddAuthentication()
    .AddCertificate("Certificate", options =>
    {
        options.AllowedCertificateTypes = CertificateTypes.SelfSign

Preview of the first 4,000 characters. Read full instructions →

identityserver-ui-flows19.9 KB

View saved version →

---
name: identityserver-ui-flows
description: "Guide for building login, logout, consent, error, and federation gateway UI pages in Duende IdentityServer, including IIdentityServerInteractionService usage, external provider integration, and Home Realm Discovery strategies."
invocable: false
---

# IdentityServer UI Flows: Login, Logout, Consent, and Federation

## When to Use This Skill

- Building or customizing the login page (local credentials, MFA, passwordless)
- Integrating external identity providers (Google, Azure AD, SAML, etc.)
- Implementing the consent page for third-party client authorization
- Building the logout flow with session cleanup and client notifications
- Implementing a federation gateway with Home Realm Discovery (HRD)
- Handling and displaying error pages for protocol errors
- Using `IIdentityServerInteractionService` to interact with the protocol engine
- Redirecting users back to clients after login/logout

Docs: https://docs.duendesoftware.com/identityserver/ui

## Architecture Overview

IdentityServer separates the protocol engine from the user interface. The engine handles OAuth/OIDC endpoints and redirects to your UI pages as needed. Your UI code handles all user interaction and then communicates results back to the engine.

```
Browser → IdentityServer Middleware → UI Pages (Login, Consent, Logout, Error)
                                          ↕
                                   IIdentityServerInteractionService
                                          ↕
                                   IdentityServer Protocol Engine
```

### Required Pages

| Page    | Purpose                               | Default URL                               |
| ------- | ------------------------------------- | ----------------------------------------- |
| Login   | Establish authentication session      | Inferred from cookie handler `LoginPath`  |
| Logout  | Terminate session, notify clients     | Set via `opt.UserInteraction.LogoutUrl`   |
| Consent | Grant/deny client access to resources | `/consent`                                |
| Error   | Display protocol error information    | `/home/error`                             |

## Login Page

### Configuring the Login URL

```csharp
// Program.cs — explicit configuration
builder.Services.AddIdentityServer(opt => {
    opt.UserInteraction.LoginUrl = "/path/to/login";
});
```

If not set, IdentityServer infers the URL from the cookie handler's `LoginPath`:

```csharp
// Program.cs — with ASP.NET Identity
builder.Services.AddIdentityServer()
    .AddAspNetIdentity<ApplicationUser>();

builder.Services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/path/to/login/for/aspnet_identity";
});
```

### Authorization Context

When IdentityServer redirects to the login page, it passes a `returnUrl` query parameter. Use `IIdentityServerInteractionService.GetAuthorizationContextAsync` to extract the original authorization request parameters:

```csharp
public class LoginModel : PageModel
{
    private readonly IIdentityServerInteractionService _interaction;

    public LoginModel(IIdentityServerInteractionService interaction)
    {
        _interaction = interaction;
    }

    public async Task<IActionResult> OnGet(string returnUrl)
    {
        var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

        // context contains:
        // - Client (the requesting client)
        // - IdP (requested identity provider hint)
        // - AcrValues (requested authentication context)
        // - Tenant (requested tenant)
        // - LoginHint (suggested username)
        // - Parameters (raw protocol parameters)

        // Use context for branding, HRD, MFA decisions, etc.
    }
}
```

**Important**: Do not parse the `returnUrl` yourself. Always use the interaction service.

### Establishing the Authentication Session

After validating credentials, create the authentication session:

```csharp
var user = new IdentityServerUser("uniq

Preview of the first 4,000 characters. Read full instructions →

identityserver-upgrade-v7-to-v815.1 KB

View saved version →

---
name: identityserver-upgrade-v7-to-v8
description: "Migrating Duende IdentityServer from v7.4 to v8.0: breaking changes, API replacements (ICache→HybridCache, IClock→TimeProvider), CancellationToken additions, EF migrations, and step-by-step upgrade guide."
invocable: false
---

# Upgrading IdentityServer v7 to v8

## When to Use This Skill

- Upgrading a Duende IdentityServer project from v7.4 to v8.0
- Fixing build errors after updating NuGet packages to v8
- Migrating custom stores/services to new v8 interfaces
- Running EF Core database migrations for v8 (SAML tables)
- Replacing deprecated APIs (ICache, IClock, IAuthorizationParametersMessageStore)

## Core Principles

- v8.0 requires **.NET 10** — update TFM before anything else
- All breaking changes are compile-time errors (no silent behavior changes)
- Migration is mechanical — find/replace patterns work for most changes
- Run EF migrations even if you don't use SAML (schema must match)
- **Always check the latest stable 8.x package version** on [NuGet](https://www.nuget.org/packages/Duende.IdentityServer) before upgrading — do not hardcode `8.0.1`; use whatever the latest stable (non-prerelease) 8.x version is at the time of the upgrade.

Docs: https://docs.duendesoftware.com/identityserver/upgrades/v7_4-to-v8_0/

## Step-by-Step Migration

### 1. Update Target Framework

```xml
<!-- ❌ Before -->
<TargetFramework>net8.0</TargetFramework>

<!-- ✅ After -->
<TargetFramework>net10.0</TargetFramework>
```

### 2. Update NuGet Packages

Check [NuGet](https://www.nuget.org/packages/Duende.IdentityServer) for the latest stable 8.x version. At time of writing, that is `8.0.1`, but use whatever is current:

```xml
<PackageReference Include="Duende.IdentityServer" Version="8.0.1" />
<PackageReference Include="Duende.IdentityServer.EntityFramework" Version="8.0.1" />
<!-- Update all Duende.* packages to the latest stable 8.x version -->
```

### 3. Run EF Database Migrations

Two migrations are required — one for the Configuration Store and one for the Operational Store:

```bash
# Configuration Store — adds 7 SAML-related tables
dotnet ef migrations add Update_DuendeIdentityServer_v8_0 \
    -c ConfigurationDbContext -o Migrations/ConfigurationDb
dotnet ef database update -c ConfigurationDbContext

# Operational Store — adds 3 SAML session tables
dotnet ef migrations add Update_DuendeIdentityServer_v8_0_Saml \
    -c PersistedGrantDbContext -o Migrations/PersistedGrantDb
dotnet ef database update -c PersistedGrantDbContext
```

Both are required even if you don't use SAML (schema must match).

### 4. Replace ICache<T> with HybridCache

```csharp
// ❌ Before (v7)
public class MyService
{
    private readonly ICache<MyData> _cache;
    public MyService(ICache<MyData> cache) => _cache = cache;

    public async Task<MyData> GetAsync(string key)
    {
        return await _cache.GetOrAddAsync(key,
            TimeSpan.FromMinutes(5),
            () => LoadFromDbAsync(key));
    }
}

// ✅ After (v8) — use Microsoft HybridCache
public class MyService
{
    private readonly HybridCache _cache;
    public MyService([FromKeyedServices("ConfigurationStoreCache")] HybridCache cache)
        => _cache = cache;

    public async Task<MyData> GetAsync(string key, CancellationToken ct)
    {
        return await _cache.GetOrCreateAsync(key,
            async token => await LoadFromDbAsync(key, token),
            new HybridCacheEntryOptions
            {
                Expiration = TimeSpan.FromMinutes(5)
            }, cancellationToken: ct);
    }
}
```

Key: use keyed service `"ConfigurationStoreCache"` (`ServiceProviderKeys.ConfigurationStoreCache`). `CachingOptions.CacheLockTimeout` is obsolete.

### 5. Replace IClock with TimeProvider

```csharp
// ❌ Before (v7)
public class MyService
{
    private readonly IClock _clock;
    public MyService(IClock clock) => _clock = clock;
    public DateTime Now => _clock.UtcNow.UtcDateTime;
}

// ✅ After (v8)
public class MyService
{
    priva

Preview of the first 4,000 characters. Read full instructions →

identityserver-usermanagement6.36 KB

View saved version →

---
name: identityserver-usermanagement
description: "Setting up Duende User Management with IdentityServer: passwordless authentication (OTP, TOTP, passkeys), storage configuration, user lifecycle, and migration from ASP.NET Identity."
invocable: false
---

# User Management

## When to Use This Skill

- Adding user management to a Duende IdentityServer project
- Setting up passwordless authentication (OTP, TOTP, passkeys)
- Configuring storage providers (PostgreSQL, SQL Server, SQLite)
- Integrating User Management with IdentityServer for claims and login/logout
- Managing user profiles, roles, and groups
- Migrating users from ASP.NET Identity

## Core Principles

- Duende User Management is **passwordless-first** — OTP email/SMS is the default flow
- Requires `Duende.UserManagement.IdentityServer8` NuGet package + .NET 10
- Storage is **document-based** (no EF migrations needed) — schema auto-creates at startup
- Configuration goes **inside** `AddUserManagement()`, not at top level
- Use `app.UseIdentityServer()` (not `UseAuthentication()` separately)

Docs: https://docs.duendesoftware.com/identityserver/usermanagement

## Setup

### 1. Add Packages

```bash
dotnet add package Duende.IdentityServer
dotnet add package Duende.UserManagement.IdentityServer8
dotnet add package Duende.Storage.Sqlite  # or .PostgreSQL, .Mssql
```

### 2. Configure Program.cs

```csharp
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddIdentityServer(options =>
{
    options.UserInteraction.LoginUrl = "/Account/Login";
    options.UserInteraction.LogoutUrl = "/Account/Logout";
})
    .AddInMemoryClients(Config.Clients)
    .AddInMemoryIdentityResources(Config.IdentityResources)
    .AddUserManagement(options =>
    {
        // Storage (pick one)
        options.AddSqliteStore("Data Source=users.db");
        // options.AddPostgreSqlStore(connectionString);
        // options.AddSqlServerStore(connectionString);

        // OTP delivery
        options.UseSmtpOtpDispatcher(smtp =>
            builder.Configuration.GetSection("Smtp").Bind(smtp));
    });

var app = builder.Build();

// Auto-create database schema
var schema = app.Services.GetRequiredService<IDatabaseSchema>();
await schema.CreateIfNotExistsAsync();

app.UseIdentityServer();
app.MapRazorPages();
app.Run();
```

### 3. OTP Dispatcher

**Console (development):**
```csharp
builder.Services.AddSingleton<IOtpDispatcher, ConsoleOtpDispatcher>();
```

**SMTP (production):**
```csharp
options.UseSmtpOtpDispatcher(x =>
{
    x.Host = "smtp.example.com";
    x.Port = 587;
    x.Username = "noreply@example.com";
    x.Password = "secret";
    x.FromAddress = "noreply@example.com";
});
```

## Authentication Methods

| Method | Description | Setup |
|--------|-------------|-------|
| **OTP** (default) | One-time codes via email/SMS | `IOtpDispatcher` implementation |
| **TOTP** | Authenticator apps (RFC 6238) | Built-in, user enrollment required |
| **Passkeys** | WebAuthn/FIDO2 phishing-resistant | Built-in, browser support required |
| **Passwords** | Traditional username/password (PBKDF2) | Opt-in, not recommended as primary |
| **External** | OAuth 2.0 / OIDC federated login | Standard ASP.NET Core auth handlers |
| **Recovery codes** | Single-use backup codes | Auto-generated during 2FA setup |

## IdentityServer Integration

`AddUserManagement()` is called on the IdentityServer builder — it automatically:
- Registers `IProfileService` for claims delivery
- Handles login/logout flows
- Maps user attributes to identity token claims

### Claims Mapping

User profile attributes are mapped to claims based on requested scopes:
- `openid` → `sub`
- `profile` → `name`, `given_name`, `family_name`, etc.
- `email` → `email`, `email_verified`

Custom attributes are available through custom identity resources.

## Storage

| Provider | Package | Connection |
|----------|---------|------------|
| SQLite | `Duende.Storage.Sqlite` | `Data Source=users.db` |
| PostgreSQL | `Duende.S

Preview of the first 4,000 characters. Read full instructions →

identity-testing-patterns34.6 KB

View saved version →

---
name: identity-testing-patterns
description: Testing patterns for IdentityServer-based systems including integration testing with WebApplicationFactory, mock token issuance, test authority configuration, protocol response validation, and end-to-end authentication flow testing.
invocable: false
---

# Identity Testing Patterns

## When to Use This Skill

Use this skill when:
- Writing integration tests for applications that issue or validate tokens using Duende IdentityServer
- Hosting IdentityServer in-memory with `WebApplicationFactory<T>` to test grant flows end-to-end
- Creating mock JWT tokens for testing protected APIs without a live authority
- Testing custom `IProfileService` implementations or claim transformation logic
- Verifying `IAuthorizationHandler` and policy-based authorization against specific claim sets
- Testing BFF endpoints that rely on cookie-based sessions and proxied API calls
- Scaffolding an integration-test project from the `duende-is-inmem` template to test IdentityServer itself
- Running a post-deployment login-flow smoke test without a headless browser

## Core Principles

1. **Integration over unit** — Test token issuance, claim mapping, and policy enforcement against a real (in-process) IdentityServer instance. Avoid mocking the token pipeline itself; mock only external I/O (databases, downstream services).
2. **In-process authority** — Use `WebApplicationFactory<T>` to host IdentityServer inside the test process. This avoids network round-trips, eliminates certificate trust issues, and makes tests deterministic.
3. **Predictable signing keys** — Override key management in tests with a static development signing key so token signatures are verifiable without key rotation logic.
4. **Minimal test clients** — Register only the clients, scopes, and resources each test needs. Over-broad test configurations mask permission bugs.
5. **Test auth handler for API tests** — When testing protected APIs in isolation (without a live token endpoint), replace JWT Bearer authentication with a `TestAuthHandler` that accepts a fake scheme. Never disable authorization wholesale.
6. **Builder pattern for test data** — Use fluent builders for `Client`, `ApiScope`, `ApiResource`, and test users to keep test setup readable and reduce duplication.

## Related Skills

- `identityserver-configuration` — Production client and resource registration patterns
- `aspnetcore-authentication` — OIDC and JWT Bearer handler configuration
- `aspnetcore-authorization` — Policy definitions and requirement handlers
- `claims-authorization` — `IProfileService` and claim pipeline internals
- `duende-bff` — BFF session and proxy architecture being tested

Docs: https://docs.duendesoftware.com/identityserver/fundamentals

---

## Sub-Documents

| Document | Description | When to Load |
|----------|-------------|--------------|
| [docs/bff-testing.md](docs/bff-testing.md) | BFF endpoint testing with cookie simulation, antiforgery headers, and OIDC redirect bypass | BFF testing, CookieContainer, x-csrf header, BffFactory, session simulation |
| [docs/aspire-testing.md](docs/aspire-testing.md) | Full-stack Aspire testing with identity server health checks and token endpoint wiring | Aspire testing, DistributedApplicationTestingBuilder, WaitForResourceHealthyAsync, end-to-end |

---

## Testing Strategy Overview

| What to test | Recommended approach |
|---|---|
| Token issuance (client credentials, code flow) | In-process `WebApplicationFactory` hitting `/connect/token` |
| Claim mapping / `IProfileService` | Unit test with `DefaultProfileService` + mock context, or integration test |
| Authorization policy requirements | `IAuthorizationService` + `TestAuthHandler` in integration test |
| `IAuthorizationHandler` logic | Direct unit test with `AuthorizationHandlerContext` |
| Protected API access control | `WebApplicationFactory` with `TestAuthHandler` and constructed `ClaimsPrincipal` |
| BFF endpoints (login/logout/user) | `WebApplicati

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 2 — file references are metadata, not package contents.

oauth-oidc-protocols19.1 KB

View saved version →

---
name: oauth-oidc-protocols
description: OAuth 2.0 and OpenID Connect protocol fundamentals including authorization code flow with PKCE, client credentials, refresh tokens, discovery documents, JWKS, and token introspection. Protocol-level troubleshooting and compliance.
invocable: false
---

# OAuth 2.0 & OpenID Connect Protocols

## When to Use This Skill

Use this skill when:
- Choosing the correct OAuth 2.0 grant type for a scenario
- Debugging token exchange flows or redirect-based authentication
- Understanding what claims and headers appear in identity tokens vs access tokens
- Implementing or troubleshooting PKCE (Proof Key for Code Exchange)
- Working with discovery documents, JWKS endpoints, or token introspection
- Reviewing security properties of different protocol flows
- Implementing refresh token rotation or token revocation

## Core Principles

1. **OAuth 2.0 is for Authorization, OIDC is for Authentication** — OAuth alone does not tell you *who* the user is. OpenID Connect adds an identity layer (the ID token) on top of OAuth.
2. **Authorization Code + PKCE is the Universal Flow** — Use it for web apps, SPAs (via BFF), native apps, and any interactive scenario. It replaced implicit flow.
3. **Tokens are Opaque to Clients** — Clients should not parse access tokens. Only the resource server (API) validates access tokens. Clients use the ID token for authentication.
4. **Discovery Documents are the Source of Truth** — Always resolve endpoints from `/.well-known/openid-configuration` rather than hardcoding URLs.
5. **Refresh Tokens Require Secure Storage** — Refresh tokens are long-lived credentials. Rotate them on every use (`OneTimeOnly`) and store them server-side.

## Related Skills

- `identityserver-configuration` — Server-side configuration of clients, resources, and scopes
- `aspnetcore-authentication` — Implementing OIDC authentication in ASP.NET Core apps
- `token-management` — Automated token lifecycle with Duende.AccessTokenManagement
- `identity-security-hardening` — Security hardening including DPoP, PAR, and FAPI
- `duende-bff` — Backend-for-Frontend pattern for SPAs

Docs: https://docs.duendesoftware.com/identityserver/fundamentals

---

## Concept 1: The OAuth 2.0 / OIDC Mental Model

### Roles

| Role | OAuth 2.0 Term | OIDC Term | Example |
|------|---------------|-----------|---------|
| User | Resource Owner | End-User | A person logging in |
| Browser/App | Client | Relying Party (RP) | ASP.NET Core web app |
| Token Server | Authorization Server | OpenID Provider (OP) | Duende IdentityServer |
| API | Resource Server | — | ASP.NET Core Web API |

### Tokens

| Token | Purpose | Who Consumes It | Format |
|-------|---------|----------------|--------|
| **ID Token** | Proves user identity | Client application | Always JWT |
| **Access Token** | Authorizes API calls | Resource server (API) | JWT or reference |
| **Refresh Token** | Obtains new access tokens | Client application | Opaque handle |

> **Critical Rule:** Clients authenticate users with the **ID token**. Clients authorize API calls with the **access token**. Never use an access token to determine who a user is. Never send an ID token to an API.

---

## Concept 2: Grant Types (Flows)

### Authorization Code + PKCE (Recommended for All Interactive Scenarios)

The authorization code flow with PKCE is the recommended flow for all clients that involve a user. PKCE prevents authorization code interception attacks.

**How it works:**

1. Client generates a random `code_verifier` and its SHA256 hash `code_challenge`
2. Client redirects user to the authorize endpoint with `code_challenge`
3. User authenticates at IdentityServer and consents (if required)
4. IdentityServer redirects back with an authorization `code`
5. Client exchanges the `code` + `code_verifier` at the token endpoint
6. IdentityServer verifies the verifier matches the original challenge
7. IdentityServer returns ID token + access token (+ refresh token if `offline_acces

Preview of the first 4,000 characters. Read full instructions →

token-management32.7 KB

View saved version →

---
name: token-management
description: Token management patterns using Duende.AccessTokenManagement. Covers client credential token caching, user token refresh, token storage, HttpClientFactory integration, DPoP support, and common configuration pitfalls. Also includes Blazor Server token management.
invocable: false
---

# Token Management

## When to Use This Skill

Use this skill when:
- Building a .NET worker service or daemon that calls APIs using the client credentials flow
- Building an ASP.NET Core web application that calls APIs on behalf of the currently logged-in user
- Integrating `Duende.AccessTokenManagement` or `Duende.AccessTokenManagement.OpenIdConnect` with `IHttpClientFactory`
- Configuring token caching — in-memory, distributed (Redis), or hybrid — for machine-to-machine tokens
- Adding DPoP (Demonstrating Proof-of-Possession) key binding to access tokens
- Implementing API-to-API delegation where a downstream service calls further APIs with either user tokens or client credentials
- Revoking refresh tokens on user sign-out

## Core Principles

1. **Prefer Automatic Over Manual** — Use `IHttpClientFactory`-integrated clients; they acquire, cache, refresh, and attach tokens transparently. Call `GetAccessTokenAsync` manually only when the factory pattern is insufficient.
2. **Never Cache Tokens in Code** — The library owns the cache. Do not store tokens in instance fields, static variables, or application-managed caches. Call the service on every request and let it serve from cache.
3. **`SaveTokens = true` Is Required for User Tokens** — The OIDC handler must persist tokens into the authentication session. This is the most common misconfiguration.
4. **Refresh Tokens Must Be Revoked at Sign-Out** — Call `e.HttpContext.RevokeRefreshTokenAsync()` in `OnSigningOut` to revoke the refresh token at the authorization server, preventing reuse after logout.
5. **v4 Uses `HybridCache`; v3 Uses `IDistributedCache`** — The caching layer changed between major versions. v4's `HybridCache` is two-tier and automatic; v3 requires an explicit `AddDistributedMemoryCache()` or Redis registration.
6. **Resiliency Is Included in `AddClientCredentialsHttpClient`** — This registration adds a once-retry handler for `401 Unauthorized` responses (handles token expiry and DPoP nonce challenges). When using `AddClientCredentialsTokenHandler` directly, add it explicitly.

## Related Skills

- `aspnetcore-authentication` — cookie and OIDC handler setup required for user token management
- `identityserver-configuration` — configuring the authorization server that issues tokens
- `oauth-oidc-protocols` — protocol fundamentals underlying client credentials and refresh token flows
- `duende-bff` — BFF pattern integrates this library automatically for proxied API calls

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

---

## Pattern 1: Machine-to-Machine (Client Credentials) — Worker Services

### Package

```bash
dotnet add package Duende.AccessTokenManagement
```

### Registration

```csharp
// ✅ Register one or more named client definitions
services.AddClientCredentialsTokenManagement()
    .AddClient("catalog.client", client =>
    {
        client.TokenEndpoint = new Uri("https://sts.company.com/connect/token");
        client.ClientId = ClientId.Parse("6f59b670-990f-4ef7-856f-0dd584ed1fac");
        client.ClientSecret = ClientSecret.Parse("d0c17c6a-ba47-4654-a874-f6d576cdf799");
        client.Scope = Scope.Parse("catalog inventory");
    })
    .AddClient("invoice.client", client =>
    {
        client.TokenEndpoint = new Uri("https://sts.company.com/connect/token");
        client.ClientId = ClientId.Parse("ff8ac57f-5ade-47f1-b8cd-4c2424672351");
        client.ClientSecret = ClientSecret.Parse("4dbbf8ec-d62a-4639-b0db-aa5357a0cf46");
        client.Scope = Scope.Parse("invoice customers");
    });
```

Available client options:
- `TokenEndpoint` — URL of the OAuth token endpoint
- `ClientId` / `ClientSecret` — client 

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 5 — file references are metadata, not package contents.

Package details

Publisher declarations from the archived package. These are separate from our research and the live service's terms.

Package license
MIT
Package author
Duende Software
Keywords
See keywords

Declared capabilities

  • Read

Package observed Nov 21, 2026.

Technical details
First seen
Sep 30, 2026 · 22:02 UTC
Last seen
Nov 22, 2026 · 00:00 UTC
Collection status
Collected

plugins_6a86acf7816881918552f3b43bc0db69

Download plugin data (JSON)

Plugin details: freshly prepared. Prepared . Refreshed when plugin data changes or after 6 hours. Your account and Follow status are live.