duendesoftware/duende-skills/identityserver-api-protection

Claude Code and agent skill by duendesoftware/duende-skills

Trust tier 2
  • community
LLM review pending
Source check pending

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

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.

Install

npx vskill@latest install duendesoftware/duende-skills/identityserver-api-protection

SKILL.md

The same SKILL.md was published earlier as duendesoftware/duende-skills/identityserver-api-protection.

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
FormatValidation MethodRevocableNetwork Dependency
JWT (at+jwt)Signature verification using issuer's JWKSNo (expires naturally)None at validation time
ReferenceIntrospection endpoint callYes (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.Services.AddAuthentication("token")
.AddOAuth2Introspection("token", options =>
{
options.Authority = "https://identity.example.com";
options.ClientId = "api1";
options.ClientSecret = "api1_secret";
});

The ClientId and ClientSecret correspond to the ApiResource name and secret configured in IdentityServer:

csharp
// IdentityServer configuration
var apiResource = new ApiResource("api1")
{
ApiSecrets = { new Secret("api1_secret".Sha256()) },
Scopes = { "api1.read" }
};
Common Pitfall: Missing ApiSecrets
csharp
// ❌ WRONG: No secret configured — introspection will fail with 401
var apiResource = new ApiResource("api1")
{
Scopes = { "api1.read" }
};
// ✅ CORRECT: ApiSecrets required for introspection
var apiResource = new ApiResource("api1")
{
ApiSecrets = { new Secret("secret".Sha256()) },
Scopes = { "api1.read" }
};

Handling Both JWT and Reference Tokens

Use ForwardReferenceToken from the Duende.AspNetCore.Authentication.JwtBearer package to support both token formats in a single API. This selector inspects the token: if it contains a dot (.) it is treated as a JWT; otherwise it is forwarded to the introspection handler.

bash
dotnet add package Duende.AspNetCore.Authentication.JwtBearer
csharp
// Program.cs
builder.Services.AddAuthentication("token")
.AddJwtBearer("token", options =>
{
options.Authority = "https://identity.example.com";
options.Audience = "api1";
options.TokenValidationParameters.ValidTypes = ["at+jwt"];
// Forward reference tokens to the introspection handler
options.ForwardDefaultSelector =
Selector.ForwardReferenceToken("introspection");
})
.AddOAuth2Introspection("introspection", options =>
{
options.Authority = "https://identity.example.com";
options.ClientId = "api1";
options.ClientSecret = "api1_secret";
});
How ForwardReferenceToken Works

The selector checks whether the incoming Bearer token string contains a dot (.):

  • Contains a dot → treated as a JWT, validated by AddJwtBearer
  • No dot → treated as a reference token, forwarded to AddOAuth2Introspection

This is a simple heuristic: JWTs always contain dots (header.payload.signature), while reference tokens are opaque identifiers.

Scope-Based Authorization

Scope Claim Format

IdentityServer can emit scopes in two formats, controlled by EmitScopesAsSpaceDelimitedStringInJwt:

SettingClaim FormatExample
false (default)JSON array"scope": ["api1.read", "api1.write"]
trueSpace-delimited string"scope": "api1.read api1.write"
Normalizing Scope Claims

When scopes are emitted as a space-delimited string, the scope claim appears as a single string value. To normalize it back to individual claims for easier policy checks, implement a custom IClaimsTransformation:

csharp
// Program.cs
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "https://identity.example.com";
options.Audience = "api1";
options.TokenValidationParameters.ValidTypes = ["at+jwt"];
});
// Register a custom claims transformation to split space-delimited scopes
builder.Services.AddTransient<IClaimsTransformation, ScopeClaimsTransformation>();
csharp
// ScopeClaimsTransformation.cs
public class ScopeClaimsTransformation : IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var identity = (ClaimsIdentity)principal.Identity!;
var scopeClaim = identity.FindFirst("scope");
if (scopeClaim != null && scopeClaim.Value.Contains(' '))
{
identity.RemoveClaim(scopeClaim);
foreach (var scope in scopeClaim.Value.Split(' '))
{
identity.AddClaim(new Claim("scope", scope));
}
}
return Task.FromResult(principal);
}
}

This transformation converts a space-delimited scope claim into individual scope claims, so authorization policies work consistently regardless of the format.

Defining Authorization Policies
csharp
// Program.cs
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("read", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim("scope", "api1.read");
});
options.AddPolicy("write", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim("scope", "api1.write");
});
});

Apply policies to endpoints:

csharp
app.MapGet("/data", () => Results.Ok(data))
.RequireAuthorization("read");
app.MapPost("/data", (DataModel model) => Results.Created())
.RequireAuthorization("write");

Or with controllers:

csharp
[Authorize(Policy = "read")]
[ApiController]
[Route("api/[controller]")]
public class DataController : ControllerBase
{
[HttpGet]
public IActionResult Get() => Ok(data);
[HttpPost]
[Authorize(Policy = "write")]
public IActionResult Post(DataModel model) => Created();
}

Proof-of-Possession (PoP) Token Validation

Proof-of-Possession binds an access token to a specific client's cryptographic key, preventing token theft/replay. IdentityServer supports two PoP mechanisms: Mutual TLS (mTLS) and DPoP.

mTLS Confirmation (cnf Claim)

When mTLS is used, the access token contains a cnf claim with the SHA-256 thumbprint of the client certificate:

json
{
"cnf": {
"x5t#S256": "bBBDDeEFSS..."
}
}

To validate at the API, confirm the cnf thumbprint matches the client certificate presented on the TLS connection:

csharp
// Program.cs
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "https://identity.example.com";
options.Audience = "api1";
options.TokenValidationParameters.ValidTypes = ["at+jwt"];
options.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
var cnfClaim = context.Principal?.FindFirst("cnf");
if (cnfClaim != null)
{
var certificate = context.HttpContext.Connection.ClientCertificate;
if (certificate == null)
{
context.Fail("Client certificate required for mTLS tokens");
return Task.CompletedTask;
}
var thumbprint = Base64UrlEncoder.Encode(
certificate.GetCertHash(HashAlgorithmName.SHA256));
var cnf = JsonDocument.Parse(cnfClaim.Value);
var expectedThumbprint = cnf.RootElement
.GetProperty("x5t#S256").GetString();
if (thumbprint != expectedThumbprint)
{
context.Fail("Certificate thumbprint does not match cnf claim");
}
}
return Task.CompletedTask;
}
};
});
DPoP Validation

DPoP (Demonstration of Proof-of-Possession) uses a separate proof JWT in the DPoP HTTP header. Use the Duende.AspNetCore.Authentication.JwtBearer package which provides built-in DPoP validation:

bash
dotnet add package Duende.AspNetCore.Authentication.JwtBearer
csharp
// Program.cs
builder.Services.AddAuthentication("token")
.AddJwtBearer("token", options =>
{
options.Authority = "https://identity.example.com";
options.Audience = "api1";
options.TokenValidationParameters.ValidTypes = ["at+jwt"];
});
// Configure DPoP on the service collection, NOT inside AddJwtBearer
builder.Services.ConfigureDPoPTokensForScheme("token");
// DPoP replay detection (on by default) requires a keyed HybridCache
builder.Services.AddKeyedHybridCache(ServiceProviderKeys.ProofTokenReplayHybridCache);

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

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

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

Source

Popularity

7-day trend score
0

Not refreshed yet.

Works with

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

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

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