duendesoftware/duende-skills/claims-authorization

Claude Code and agent skill by duendesoftware/duende-skills

Trust tier 3
  • community
Source check pending

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

Claims transformation and profile service patterns for Duende IdentityServer — IProfileService, IClaimsTransformation, claim type mapping, token claim filtering, extension grant validators, and dynamic claims loading.

Install

npx vskill@latest install duendesoftware/duende-skills/claims-authorization

SKILL.md

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

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

DocumentDescriptionWhen to Load
docs/extension-grant-claims.mdIExtensionGrantValidator implementation for custom grant types with claim propagationExtension grants, token exchange, custom grant type, IExtensionGrantValidator, GrantValidationResult
docs/external-provider-claims.mdExternal provider login callback with claim mapping, Google/AAD normalization, and ClaimActionsExternal 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 ──► IdentityServer login callback
│
▼
Cookie principal (ClaimsPrincipal)
– built during SignInAsync
– stored in authentication session
│
▼
IProfileService.GetProfileDataAsync
– called at token issuance time
– selects/augments claims for each token type
│
┌──────┴──────┐
▼ ▼
Identity Token Access Token
(for client) (for API)
│
▼
API JWT bearer handler
– IClaimsTransformation (optional)
– MapInboundClaims = false
│
▼
HttpContext.User
– used by [Authorize], policies, handlers

Stage 1 — Login callback: Claims from the external provider (or local user store) are incorporated into the IdentityServerUser and persisted in the session cookie. This is where you map external IdP claims to internal claim types.

Stage 2 — Token issuance: When a client requests a token, IdentityServer calls IProfileService.GetProfileDataAsync. The ProfileDataRequestContext tells you which claims are requested (derived from scopes/resources) and what token type is being built. This is where you load dynamic claims from your database.

Stage 3 — Token consumption: APIs receive the JWT and validate it. IClaimsTransformation can augment the ClaimsPrincipal after validation — useful for adding application-specific roles or denormalized data that doesn't belong in the token itself.


IProfileService

IProfileService is the primary extensibility point for claims in Duende IdentityServer. Register your implementation with AddProfileService<T>() during startup.

Interface Contract
csharp
// Duende.IdentityServer.Services
public interface IProfileService
{
// Called to get claims for a token or the userinfo endpoint.
Task GetProfileDataAsync(ProfileDataRequestContext context);
// Called to check whether the user is still active (e.g. not disabled).
// context.Caller is a ProfileIsActiveCallers constant that tells you WHY
// the check is being made (e.g. AuthorizeEndpoint, Token, RefreshTokenValidation).
Task IsActiveAsync(IsActiveContext context);
}
ProfileDataRequestContext Key Members
MemberDescription
SubjectThe ClaimsPrincipal from the authentication session (or from the access token for userinfo calls).
ClientThe Client making the request — use for per-client filtering.
CallerWhat triggered this call: ClaimsProviderAccessToken, ClaimsProviderIdentityToken, UserInfoEndpoint.
RequestedClaimTypesClaim types requested by the client, built from the UserClaims of the resources (IdentityResource/ApiScope/ApiResource) resolved for the request.
IssuedClaimsPopulate this collection with claims to include in the token.
AddRequestedClaims(IEnumerable<Claim>)Helper that filters your claims to only those in RequestedClaimTypes.
Minimal Implementation
csharp
// ✅ Correct: extend DefaultProfileService, use AddRequestedClaims
public sealed class ApplicationProfileService : DefaultProfileService
{
private readonly IUserRepository _users;
private readonly ILogger<ApplicationProfileService> _logger;
public ApplicationProfileService(
IUserRepository users,
ILogger<ApplicationProfileService> logger)
: base(logger)
{
_users = users;
_logger = logger;
}
public override async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
// Source claims from Subject (cheap — already in memory)
var subjectId = context.Subject.GetSubjectId();
// Load additional claims from the database
var user = await _users.FindBySubjectIdAsync(subjectId);
if (user is null)
{
_logger.LogWarning("Profile service: user {SubjectId} not found", subjectId);
return;
}
var claims = new List<Claim>
{
new(JwtClaimTypes.Name, user.DisplayName),
new(JwtClaimTypes.Email, user.Email),
new("tenant_id", user.TenantId),
new("subscription_tier", user.SubscriptionTier),
};
// Only emit claims that were requested by the client's scopes
context.AddRequestedClaims(claims);
}
public override async Task IsActiveAsync(IsActiveContext context)
{
var subjectId = context.Subject.GetSubjectId();
var user = await _users.FindBySubjectIdAsync(subjectId);
context.IsActive = user is { IsEnabled: true };
}
}
`ProfileIsActiveCallers`: IsActiveContext.Caller is a ProfileIsActiveCallers constant indicating why the check is being made — e.g. AuthorizeEndpoint, Token, RefreshTokenValidation, UserInfoRequestValidation. Use it to apply different strictness levels; for example, you might allow a soft-disabled account to complete an in-flight refresh but deny new interactive logins.
csharp
// Program.cs
builder.Services.AddIdentityServer()
.AddProfileService<ApplicationProfileService>();
Emitting Claims Unconditionally

Use context.IssuedClaims.AddRange(...) when a claim must always appear regardless of requested scopes — for example, a mandatory tenant_id that APIs rely on for multi-tenancy:

csharp
// ✅ Always emit tenant_id, regardless of requested scopes
public override async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var subjectId = context.Subject.GetSubjectId();
var user = await _users.FindBySubjectIdAsync(subjectId);
// Mandatory claim — bypasses scope-based filtering
context.IssuedClaims.Add(new Claim("tenant_id", user.TenantId));
// Scope-filtered claims
var profileClaims = BuildProfileClaims(user);
context.AddRequestedClaims(profileClaims);
}
csharp
// ❌ Wrong: adding all claims directly bypasses consent and scope filtering
public override Task GetProfileDataAsync(ProfileDataRequestContext context)
{
// This ignores RequestedClaimTypes and consent — user agreed to share only
// the claims associated with the requested scopes.
context.IssuedClaims.AddRange(GetAllUserClaims());
return Task.CompletedTask;
}
Differentiating by Caller

The Caller property lets you tailor claims for each token type:

csharp
public override async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var user = await _users.FindBySubjectIdAsync(context.Subject.GetSubjectId());
if (context.Caller == IdentityServerConstants.ProfileDataCallers.ClaimsProviderIdentityToken)
{
// Identity tokens go to the browser — keep them small
context.IssuedClaims.Add(new Claim(JwtClaimTypes.Name, user.DisplayName));
return;
}
// Access tokens and userinfo can include richer application claims
var claims = BuildFullClaimSet(user);
context.AddRequestedClaims(claims);
}
Detecting Userinfo Endpoint Calls

When called for the userinfo endpoint, Subject is populated from the access token rather than the session principal. Guard against assuming session-only data is available:

csharp
public override async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
// context.Subject.GetSubjectId() works for all callers
var subjectId = context.Subject.GetSubjectId();
// For userinfo, context.Subject contains access-token claims only —
// not the full session principal. Load from database instead.
var user = await _users.FindBySubjectIdAsync(subjectId);
context.AddRequestedClaims(BuildProfileClaims(user));
}
Profile Service Invocation Count (Lifecycle)

For an authorization-code + userinfo flow, GetProfileDataAsync can be called up to three times per login, distinguished by context.Caller:

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

Security

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

Quality evaluation

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

Source

Popularity

7-day trend score
0

Not refreshed yet.

Works with

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

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

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