identityserver-token-lifecycle
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.
What this skill does
# 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 `ApiResource`:
```csharp
var api = new ApiResource("api1")
{
ApiSecrets = { new Secret("secret".Sha256()) },
Scopes = { "read", "write" }
};
```
### Decision Matrix: JWT vs Reference Tokens
| Criterion | JWT | Reference |
| -------------------- | ----------------------------------- | ------------------------------------ |
| Revocability | No (expires naturally) | Yes (immediate, delete from store) |
| API call to validate | No (self-contained) | Yes (introspection endpoint) |
| Network dependency | None at validation time | Requires IdentityServer availability |
| Token size | Larger (contains all claims) | Small (just a handle) |
| Performance at scale | Better (no server call) | Introspection adds latency |
| Best for | High-throughput APIs, microservices | Sensitive APIs needing revocation |
### Controlling Token Format Per Client
```csharp
// Set on the Client model
client.AccessTokenType = AccessTokenType.Jwt; // default
client.AccessTokenType = AccessTokenType.Reference; // reference tokens
```
## Refresh Tokens
Refresh tokens allow clients to obtain new access tokens without user interaction. They are supported for authorization code, hybrid, and resource owner password credential flows.
### Requesting Refresh Tokens
The client must:
1. Have `AllowOfflineAccess = true` on its configuration
2. Request the `offline_access` scope in the authorize request
```
POST /connect/token
Content-Type: application/x-www-form-urlencoded
client_id=client&
client_secret=secret&
grant_type=refresh_token&
refresh_token=hdh922
```
Using Duende.IdentityModel:
```csharp
using Duende.IdentityModel.Client;
var client = new HttpClient();
var response = await client.RequestRefreshTokenAsync(new RefreshTokenRequest
{
Address = TokenEndpoint,
ClientId = "client",
ClientSecret = "secret",
RefreshToken = "..."
});
```
### Refresh Token Lifetime Settings
| Setting | Description | Recommendation |
| ------------------------------ | -------------------------------------------------------- | ----------------------------------------------------- |
| `AbsoluteRefreshTokenLifetime` | Maximum lifetime regardless of activity (seconds) | Set based on security policy (e.g., 30 days) |
| `SlidingRefreshTokenLifetime` | Extends token life on each use, up to the absolute limit | Use for "remember me" scenarios (e.g., 1 day sliding) |
| `RefreshTokenExpiration` | `Absolute` or `Sliding` | Use `Sliding` with a reasonable absolute cap |
### Rotation (OneTime vs ReUse)
Configured via `RefreshTokenUsage` on the client:
| Mode | Behavior | Trade-offs |
| ---------------------------- | ------------------------------------------------------ | ----------------------------------------------------------------- |
| `ReUse` (default since v7.0) | Same refresh token is reused across requests | Robust to network failures, lower DB pressure |
| `OneTime` | New refresh token issued on each use; old one consumed | Limited security benefit, risk of losing token on network failure |
**Why `ReUse` is the default**: Rotating tokens on every use has limited security benefits regardless of client type. Reusable tokens are robust to network failures — if a one-time-use token is used but the response is lost, the client cannot recover without forcing a new login. Reusable tokens also have better performance since they avoid extra writes to the persisted grant store.
### Accepting Consumed Tokens (Network Failure Resilience)
To make one-time-use tokens more resilient, subclass `DefaultRefreshTokenService` and override `AcceptConsumedTokenAsync`:
```csharp
public class ResilientRefreshTokenService : DefaultRefreshTokenService
{
protected override Task<bool> AcceptCRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.