duendesoftware/duende-skills/token-management

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.

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.

Install

npx vskill@latest install duendesoftware/duende-skills/token-management

SKILL.md

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

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 credentials
  • ClientCredentialStyle — AuthorizationHeader (default) or PostBody
  • Scope — requested scope (optional; overridable per request)
  • Resource — resource indicator per RFC 8707 (optional)
  • HttpClientName — custom backchannel HTTP client name from the factory
  • DPoPJsonWebKey — JWK for DPoP-bound tokens (see Pattern 5)
Automatic via HttpClientFactory (Recommended)
csharp
// ✅ Named client — token acquired, cached, and attached automatically
services.AddClientCredentialsHttpClient(
"invoices",
ClientCredentialsClientName.Parse("invoice.client"),
client => { client.BaseAddress = new Uri("https://apis.company.com/invoice/"); });
// ✅ Typed client — identical behaviour, strongly typed
services.AddHttpClient<CatalogClient>(client =>
{
client.BaseAddress = new Uri("https://apis.company.com/catalog/");
})
.AddClientCredentialsTokenHandler(ClientCredentialsClientName.Parse("catalog.client"));

Usage — no token code required at the call site:

csharp
public sealed class WorkerHttpClient(IHttpClientFactory factory) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
// ✅ Token acquired, cached, and refreshed transparently
var client = factory.CreateClient("invoices");
var response = await client.GetAsync("list", stoppingToken);
// ...
}
}
}
Resiliency handler — AddClientCredentialsHttpClient automatically adds a resiliency handler that retries once on 401 Unauthorized. This covers token expiry and DPoP nonce challenges. When using AddClientCredentialsTokenHandler directly, add it explicitly:
```csharp
services.AddHttpClient<CatalogClient>(...)
.AddDefaultAccessTokenResiliency()
.AddClientCredentialsTokenHandler("catalog.client");
```
Manual Token Retrieval (Advanced)
csharp
// ✅ Inject IClientCredentialsTokenManager (v4)
public sealed class WorkerManual(
IHttpClientFactory factory,
IClientCredentialsTokenManager tokenManager) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var tokenResult = await tokenManager.GetAccessTokenAsync(
ClientCredentialsClientName.Parse("catalog.client"),
ct: stoppingToken);
if (!tokenResult.Succeeded)
{
// log and handle — do not call .GetToken() without checking first
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
continue;
}
var token = tokenResult.GetToken();
var client = factory.CreateClient();
client.SetBearerToken(token.AccessToken.ToString());
var response = await client.GetAsync("https://apis.company.com/catalog/list", stoppingToken);
// ...
}
}
}
In v3, the service was IClientCredentialsTokenManagementService and the result was read via .Value. In v4 it is IClientCredentialsTokenManager and the result is TokenResult<ClientCredentialsToken> — use .Succeeded / .GetToken().

Pattern 2: User Token Management — Web Applications

Package
bash
dotnet add package Duende.AccessTokenManagement.OpenIdConnect
Registration
csharp
// ✅ Full setup: cookie + OIDC handler + token management
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = "cookie";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("cookie", options =>
{
options.Cookie.Name = "web";
// ✅ Revoke refresh token at sign-out
options.Events.OnSigningOut = async e =>
{
await e.HttpContext.RevokeRefreshTokenAsync();
};
})
.AddOpenIdConnect("oidc", options =>
{
options.Authority = "https://sts.company.com";
options.ClientId = "webapp";
options.ClientSecret = "secret";
options.ResponseType = "code";
options.ResponseMode = "query";
options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
options.Scope.Add("invoice");
options.Scope.Add("offline_access"); // ← required for refresh tokens
options.GetClaimsFromUserInfoEndpoint = true;
options.MapInboundClaims = false;
// ✅ REQUIRED — persists access and refresh tokens into the auth session
options.SaveTokens = true;
});
// ✅ Adds all token management services
builder.Services.AddOpenIdConnectAccessTokenManagement();
`SaveTokens = true` is mandatory. Without it, the library cannot read or refresh the user's access token. This is the most common misconfiguration causing InvalidOperationException at runtime.
Automatic via HttpClientFactory (Recommended)
csharp
// ✅ Named client using the current user's access token
builder.Services.AddUserAccessTokenHttpClient(
"invoices",
configureClient: client =>
{
client.BaseAddress = new Uri("https://api.company.com/invoices/");
});
// ✅ Typed client using the current user's access token
builder.Services.AddHttpClient<InvoiceClient>(client =>
{
client.BaseAddress = new Uri("https://api.company.com/invoices/");
})
.AddUserAccessTokenHandler();
// ✅ Named client using a client credentials token (machine-to-machine, user-independent)
builder.Services.AddClientAccessTokenHttpClient(
"masterdata.client",
configureClient: client =>
{
client.BaseAddress = new Uri("https://api.company.com/masterdata/");
});
// ✅ Typed client using a client credentials token
builder.Services.AddHttpClient<MasterDataClient>(client =>
{
client.BaseAddress = new Uri("https://api.company.com/masterdata/");
})
.AddClientAccessTokenHandler();

Usage in a controller:

csharp
public sealed class ApiController(IHttpClientFactory httpClientFactory) : Controller
{
public async Task<IActionResult> CallApi(CancellationToken ct)
{
// ✅ Token attached automatically; refreshed silently if expired
var client = httpClientFactory.CreateClient("invoices");
var response = await client.GetAsync("list", ct);
// ...
}
}
Manual Token Retrieval (Advanced)
csharp
// ✅ v4 — inject IUserTokenManager
public sealed class HomeController(
IHttpClientFactory httpClientFactory,
IUserTokenManager userTokenManager) : Controller
{
public async Task<IActionResult> CallApi(CancellationToken ct)
{
var token = await userTokenManager.GetAccessTokenAsync(User, ct: ct);
var client = httpClientFactory.CreateClient();
client.SetBearerToken(token.Value);
var response = await client.GetAsync("https://api.company.com/invoices", ct);
// ...
}
}

HttpContext extension methods are also available:

csharp
// ✅ User access token — refreshed automatically via refresh token if expired
var userToken = await HttpContext.GetUserAccessTokenAsync();
// ✅ Client credentials token — re-requested from the token server if expired
var clientToken = await HttpContext.GetClientAccessTokenAsync();
// ✅ Revoke refresh token explicitly (also wired into OnSigningOut above)
await HttpContext.RevokeRefreshTokenAsync();
gRPC Support

Use AddUserAccessTokenHandler and AddClientAccessTokenHandler when registering typed gRPC clients:

csharp
// ✅ gRPC client using the current user's access token
builder.Services.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://grpc.company.com");
})
.AddUserAccessTokenHandler();
// ✅ gRPC client using a client credentials token
builder.Services.AddGrpcClient<Inventory.InventoryClient>(o =>
{
o.Address = new Uri("https://grpc.company.com");
})
.AddClientAccessTokenHandler();

Pattern 3: Token Caching

v4 — HybridCache (Default)

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/token-management/badge)](https://verified-skill.com/skills/duendesoftware/duende-skills/token-management)

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