← Duende SkillsCONTENT HISTORY

Update to Duende Skills

Snapshot Sep 30, 2026 · 23:14 UTC · version 0.3.0

Collection source: not recorded for this historical snapshot.

WHAT CHANGED · RULE-BASED ANALYSIS

First saved snapshot

No earlier snapshot is available to establish a change.

Compare saved observations

Download comparison JSON
Full technical diff · 0 changed fields
Full snapshot data
{
  "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.",
  "included_files": [],
  "skill_md_contents": "---\nname: oauth-oidc-protocols\ndescription: 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.\ninvocable: false\n---\n\n# OAuth 2.0 & OpenID Connect Protocols\n\n## When to Use This Skill\n\nUse this skill when:\n- Choosing the correct OAuth 2.0 grant type for a scenario\n- Debugging token exchange flows or redirect-based authentication\n- Understanding what claims and headers appear in identity tokens vs access tokens\n- Implementing or troubleshooting PKCE (Proof Key for Code Exchange)\n- Working with discovery documents, JWKS endpoints, or token introspection\n- Reviewing security properties of different protocol flows\n- Implementing refresh token rotation or token revocation\n\n## Core Principles\n\n1. **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.\n2. **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.\n3. **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.\n4. **Discovery Documents are the Source of Truth** — Always resolve endpoints from `/.well-known/openid-configuration` rather than hardcoding URLs.\n5. **Refresh Tokens Require Secure Storage** — Refresh tokens are long-lived credentials. Rotate them on every use (`OneTimeOnly`) and store them server-side.\n\n## Related Skills\n\n- `identityserver-configuration` — Server-side configuration of clients, resources, and scopes\n- `aspnetcore-authentication` — Implementing OIDC authentication in ASP.NET Core apps\n- `token-management` — Automated token lifecycle with Duende.AccessTokenManagement\n- `identity-security-hardening` — Security hardening including DPoP, PAR, and FAPI\n- `duende-bff` — Backend-for-Frontend pattern for SPAs\n\nDocs: https://docs.duendesoftware.com/identityserver/fundamentals\n\n---\n\n## Concept 1: The OAuth 2.0 / OIDC Mental Model\n\n### Roles\n\n| Role | OAuth 2.0 Term | OIDC Term | Example |\n|------|---------------|-----------|---------|\n| User | Resource Owner | End-User | A person logging in |\n| Browser/App | Client | Relying Party (RP) | ASP.NET Core web app |\n| Token Server | Authorization Server | OpenID Provider (OP) | Duende IdentityServer |\n| API | Resource Server | — | ASP.NET Core Web API |\n\n### Tokens\n\n| Token | Purpose | Who Consumes It | Format |\n|-------|---------|----------------|--------|\n| **ID Token** | Proves user identity | Client application | Always JWT |\n| **Access Token** | Authorizes API calls | Resource server (API) | JWT or reference |\n| **Refresh Token** | Obtains new access tokens | Client application | Opaque handle |\n\n> **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.\n\n---\n\n## Concept 2: Grant Types (Flows)\n\n### Authorization Code + PKCE (Recommended for All Interactive Scenarios)\n\nThe authorization code flow with PKCE is the recommended flow for all clients that involve a user. PKCE prevents authorization code interception attacks.\n\n**How it works:**\n\n1. Client generates a random `code_verifier` and its SHA256 hash `code_challenge`\n2. Client redirects user to the authorize endpoint with `code_challenge`\n3. User authenticates at IdentityServer and consents (if required)\n4. IdentityServer redirects back with an authorization `code`\n5. Client exchanges the `code` + `code_verifier` at the token endpoint\n6. IdentityServer verifies the verifier matches the original challenge\n7. IdentityServer returns ID token + access token (+ refresh token if `offline_access` scope)\n\n```\n┌──────┐          ┌──────────┐          ┌──────────────┐\n│Client│          │  Browser  │          │IdentityServer│\n└──┬───┘          └────┬─────┘          └──────┬───────┘\n   │  1. Generate PKCE │                       │\n   │  code_verifier    │                       │\n   │  code_challenge   │                       │\n   │                   │                       │\n   │  2. Redirect ───────────────────────────► │\n   │     /authorize?code_challenge=...         │\n   │                   │  3. User logs in      │\n   │                   │  ◄──────────────────► │\n   │                   │                       │\n   │  4. Redirect back ◄────────────────────── │\n   │     ?code=abc123  │                       │\n   │                   │                       │\n   │  5. POST /token ─────────────────────────►│\n   │     code=abc123&code_verifier=...         │\n   │                   │                       │\n   │  6. Tokens ◄──────────────────────────────│\n   │     { id_token, access_token,             │\n   │       refresh_token }                     │\n   └───────────────────┴───────────────────────┘\n```\n\n**When to use:** Web applications, native apps, SPAs (via BFF pattern).\n\n### Client Credentials\n\nFor machine-to-machine communication with no user involvement.\n\n```\n┌──────────┐                    ┌──────────────┐\n│  Service  │                    │IdentityServer│\n└────┬─────┘                    └──────┬───────┘\n     │  POST /token                    │\n     │  grant_type=client_credentials  │\n     │  client_id=...                  │\n     │  client_secret=...              │\n     │  scope=api1                     │\n     │  ───────────────────────────►   │\n     │                                 │\n     │  { access_token }               │\n     │  ◄───────────────────────────   │\n     └─────────────────────────────────┘\n```\n\n**When to use:** Background services, daemons, server-to-server API calls.\n\n**Key difference:** No user identity — the access token contains only client claims, not user claims.\n\n### Refresh Token Exchange\n\n```\n┌──────┐                         ┌──────────────┐\n│Client│                         │IdentityServer│\n└──┬───┘                         └──────┬───────┘\n   │  POST /token                       │\n   │  grant_type=refresh_token          │\n   │  refresh_token=old_rt              │\n   │  ─────────────────────────────►    │\n   │                                    │\n   │  { access_token,                   │\n   │    refresh_token: new_rt }         │\n   │  ◄─────────────────────────────    │\n   └────────────────────────────────────┘\n```\n\n> With `RefreshTokenUsage = OneTimeOnly`, each refresh returns a **new** refresh token. The old one is invalidated. This enables **refresh token rotation**, a key security measure. Note: the default changed to `ReUse` in IdentityServer v7.0 — set `OneTimeOnly` explicitly for rotation.\n\n### Deprecated / Discouraged Flows\n\n| Flow | Status | Why |\n|------|--------|-----|\n| Implicit (`token` / `id_token`) | **Deprecated** | Tokens in URL fragments; no PKCE protection |\n| Resource Owner Password (ROPC) | **Discouraged** | Client handles credentials directly; no MFA support |\n| Hybrid | **Replaced** | Use Authorization Code + PKCE instead |\n\n---\n\n## Concept 3: Discovery and JWKS\n\n### Discovery Document\n\nEvery OpenID Connect provider publishes a discovery document at `/.well-known/openid-configuration`. This JSON document advertises:\n\n- Endpoint URLs (authorize, token, userinfo, introspection, revocation, end\\_session)\n- Supported grant types, scopes, claims, and response types\n- Signing algorithms and JWKS URI\n- Token endpoint authentication methods\n\n```csharp\n// ✅ Use IdentityModel to fetch discovery programmatically\nusing var httpClient = new HttpClient();\nvar disco = await httpClient.GetDiscoveryDocumentAsync(\"https://identity.example.com\");\n\nif (disco.IsError) throw new Exception(disco.Error);\n\nvar tokenEndpoint = disco.TokenEndpoint;\nvar jwksUri = disco.JwksUri;\n```\n\n> **Best Practice:** Never hardcode endpoint URLs. Always resolve them from the discovery document. This ensures your application adapts to URL changes and load balancer configurations.\n\n### JWKS (JSON Web Key Set)\n\nThe JWKS endpoint (advertised via the `jwks_uri` field in the discovery document; in Duende IdentityServer this is `/.well-known/openid-configuration/jwks`) publishes the public keys used to verify token signatures. APIs and clients fetch this to validate JWTs.\n\n**Key rotation:** When IdentityServer rotates signing keys, the new key appears in JWKS during the propagation period before it becomes the active signing key. Client libraries cache JWKS for 24 hours by default.\n\n---\n\n## Concept 4: Token Anatomy\n\n### ID Token (JWT)\n\n```json\n{\n  \"iss\": \"https://identity.example.com\",\n  \"sub\": \"818727\",\n  \"aud\": \"web.app\",\n  \"exp\": 1311281970,\n  \"iat\": 1311280970,\n  \"nonce\": \"n-0S6_WzA2Mj\",\n  \"auth_time\": 1311280969,\n  \"at_hash\": \"77QmUPtjPfzWtF2AnpK9RQ\",\n  \"amr\": [\"pwd\", \"mfa\"],\n  \"name\": \"Alice Smith\",\n  \"email\": \"alice@example.com\"\n}\n```\n\n**Key claims:**\n- `iss` — Issuer (must match your IdentityServer URL)\n- `sub` — Subject (unique user identifier)\n- `aud` — Audience (must match the client ID)\n- `nonce` — Replay protection (sent in authorize request, echoed in token)\n- `at_hash` — Hash of the access token (binds the ID token to the access token)\n- `amr` — Authentication methods used\n\n### Access Token (JWT)\n\n```json\n{\n  \"iss\": \"https://identity.example.com\",\n  \"aud\": \"https://api.example.com\",\n  \"client_id\": \"web.app\",\n  \"sub\": \"818727\",\n  \"scope\": \"openid profile api1\",\n  \"exp\": 1311284570,\n  \"iat\": 1311280970,\n  \"jti\": \"unique-token-id\"\n}\n```\n\n**Key claims:**\n- `aud` — The API resource(s) this token is valid for\n- `client_id` — Which client requested this token\n- `scope` — Granted permissions\n- `jti` — Unique token identifier (for revocation tracking)\n\n### Reference Tokens\n\nReference tokens are **not** self-contained JWTs. Instead, the access token is an opaque identifier. The API must call the **introspection endpoint** to validate it:\n\n```\nPOST /connect/introspect\nContent-Type: application/x-www-form-urlencoded\n\ntoken=<reference_token>&token_type_hint=access_token\n```\n\n**When to use reference tokens:**\n- Tokens contain sensitive claims you don't want exposed to intermediaries\n- You need immediate token revocation (JWT lifetimes are not revocable until expiry)\n- Token size is a concern (reference tokens are small opaque strings)\n\n---\n\n## Concept 5: Token Introspection and Revocation\n\n### Introspection\n\nAPIs validate reference tokens by calling the introspection endpoint. The API authenticates itself with its own secret:\n\n```csharp\n// Using IdentityModel\nvar introspectionResponse = await httpClient.IntrospectTokenAsync(\n    new TokenIntrospectionRequest\n    {\n        Address = disco.IntrospectionEndpoint,\n        ClientId = \"api1\",\n        ClientSecret = \"api1-secret\",\n        Token = accessToken\n    });\n\nif (!introspectionResponse.IsActive)\n{\n    // Token is invalid, expired, or revoked\n}\n```\n\n### Revocation\n\nClients can revoke access tokens and refresh tokens:\n\n```csharp\nvar revocationResponse = await httpClient.RevokeTokenAsync(\n    new TokenRevocationRequest\n    {\n        Address = disco.RevocationEndpoint,\n        ClientId = \"web.app\",\n        ClientSecret = \"secret\",\n        Token = refreshToken,\n        TokenTypeHint = \"refresh_token\"\n    });\n```\n\n> **What can actually be revoked:** revocation (RFC 7009) only deactivates **reference access tokens and refresh tokens**, which are persisted server-side. A **JWT access token is stateless and cannot be revoked** — it stays valid until `exp`. Use reference tokens when you need immediate invalidation.\n\n### Client Authentication: `private_key_jwt`\n\nConfidential clients can authenticate with a signed JWT assertion instead of a shared secret. The assertion's `aud` MUST be the authorization server's **issuer identifier** (`disco.Issuer`), never the token endpoint URL — the latter enabled token-endpoint confusion attacks (CVE-2025-27370 / CVE-2025-27371). Set the JWT `typ` header to `client-authentication+jwt` to opt into strict audience validation (RFC 7523bis).\n\n---\n\n## Concept 6: Scopes and Claims Mapping\n\n### Scopes Control What's in Tokens\n\n| Scope requested | What it controls | Token affected |\n|----------------|-----------------|----------------|\n| `openid` | Returns `sub` claim | ID token |\n| `profile` | Returns name, family\\_name, etc. | ID token / userinfo |\n| `email` | Returns email, email\\_verified | ID token / userinfo |\n| `api1` | Grants access to API | Access token |\n| `offline_access` | Returns refresh token | Refresh token issued |\n\n### Claims Destinations\n\nBy default, IdentityServer emits identity claims to the ID token and the userinfo endpoint. Claims associated with API scopes go into the access token. The `IProfileService` controls claim emission:\n\n```csharp\npublic class ProfileService : IProfileService\n{\n    public Task GetProfileDataAsync(ProfileDataRequestContext context)\n    {\n        // Add claims based on the requested resources\n        var claims = GetClaimsForUser(context.Subject);\n        context.IssuedClaims.AddRange(\n            claims.Where(c => context.RequestedClaimTypes.Contains(c.Type)));\n        return Task.CompletedTask;\n    }\n\n    public Task IsActiveAsync(IsActiveContext context)\n    {\n        context.IsActive = true; // Check if user account is still active\n        return Task.CompletedTask;\n    }\n}\n```\n\n---\n\n## Concept 7: Security Extensions\n\n### Pushed Authorization Requests (PAR)\n\nPAR moves the authorization parameters from the query string to a backchannel POST, preventing parameter tampering and URL length issues:\n\n```\n1. Client POSTs parameters to /connect/par → gets a request_uri\n2. Client redirects user to /authorize?request_uri=...&client_id=...\n```\n\n### DPoP (Demonstrating Proof-of-Possession)\n\nDPoP binds access tokens to a client's cryptographic key, preventing token theft and replay:\n\n```\n1. Client generates a key pair\n2. Client creates a DPoP proof (signed JWT with the public key)\n3. Client sends the DPoP proof in the DPoP header with the token request\n4. IdentityServer binds the token to the key via a \"cnf\" claim\n5. API verifies the DPoP proof matches the token's \"cnf\" claim\n```\n\n### FAPI 2.0\n\nFinancial-grade API profile requires PAR, DPoP or mTLS, and stricter validation. Duende IdentityServer supports FAPI 2.0 compliance from v7.3+.\n\n---\n\n## Common Pitfalls\n\n### 1. Using Access Tokens for Authentication\n\n```csharp\n// ❌ WRONG — Access tokens are for authorization, not authentication\nvar userId = accessToken.Claims.First(c => c.Type == \"sub\").Value;\n// The access token's audience is the API, not your app\n\n// ✅ CORRECT — Use the ID token (via the authentication middleware)\nvar userId = User.FindFirst(\"sub\")?.Value;\n```\n\n### 2. Parsing Access Tokens in the Client\n\n```csharp\n// ❌ WRONG — Clients should treat access tokens as opaque\nvar handler = new JwtSecurityTokenHandler();\nvar jwt = handler.ReadJwtToken(accessToken);\n// This breaks when the server switches to reference tokens\n\n// ✅ CORRECT — Only the resource server (API) validates access tokens\n// The client just forwards the token in the Authorization header\nhttpClient.SetBearerToken(accessToken);\n```\n\n### 3. Missing PKCE\n\n```csharp\n// ❌ WRONG — No PKCE leaves authorization code flow vulnerable\n// Duende IdentityServer requires PKCE by default (RequirePkce = true)\n\n// ✅ The ASP.NET Core OIDC handler sends PKCE automatically since .NET 7\n// No extra configuration needed on the client side\n```\n\n### 4. Ignoring Token Expiration\n\n```csharp\n// ❌ WRONG — Using a token without checking expiration\nhttpClient.SetBearerToken(cachedAccessToken); // Might be expired\n\n// ✅ CORRECT — Use Duende.AccessTokenManagement for automatic refresh\n// See the `token-management` skill\nbuilder.Services.AddOpenIdConnectAccessTokenManagement();\n```\n\n### 5. Hardcoding Endpoint URLs\n\n```csharp\n// ❌ WRONG — Breaks when server URL changes\nvar tokenEndpoint = \"https://identity.example.com/connect/token\";\n\n// ✅ CORRECT — Resolve from discovery\nvar disco = await httpClient.GetDiscoveryDocumentAsync(authority);\nvar tokenEndpoint = disco.TokenEndpoint;\n```\n\n---\n\n## Protocol Debugging Checklist\n\nWhen a token exchange fails, check these in order:\n\n1. **Discovery document** — Is `/.well-known/openid-configuration` reachable? Does it return valid JSON?\n2. **Client ID** — Does the client ID in the request exactly match the server registration?\n3. **Redirect URI** — Exact string match including scheme, host, port, path, and trailing slash\n4. **Scopes** — Are all requested scopes registered in `AllowedScopes` on the client?\n5. **Grant type** — Is the grant type in the request allowed by the client's `AllowedGrantTypes`?\n6. **PKCE** — Is the client sending `code_challenge` and `code_verifier`? Duende IS requires PKCE by default.\n7. **Client secret** — Is the secret correct? Check for encoding issues (Sha256 hash, not plaintext).\n8. **Clock skew** — Is the server time within acceptable bounds for token validation? (default: 5 min)\n9. **HTTPS** — Is the authorize redirect using HTTPS? Mixed content blocks cause silent failures.\n10. **CORS** — If calling the token endpoint from a browser, is the origin in `AllowedCorsOrigins`?\n\n---\n\n## Resources\n\n- [OAuth 2.0 (RFC 6749)](https://tools.ietf.org/html/rfc6749)\n- [OAuth 2.0 for Browser-Based Apps (RFC draft)](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-browser-based-apps)\n- [PKCE (RFC 7636)](https://tools.ietf.org/html/rfc7636)\n- [OpenID Connect Core 1.0](https://openid.net/specs/openid-connect-core-1_0.html)\n- [OpenID Connect Discovery 1.0](https://openid.net/specs/openid-connect-discovery-1_0.html)\n- [JWT Access Tokens (RFC 9068)](https://datatracker.ietf.org/doc/html/rfc9068)\n- [Resource Indicators (RFC 8707)](https://tools.ietf.org/html/rfc8707)\n- [DPoP (RFC 9449)](https://datatracker.ietf.org/doc/html/rfc9449)\n- [PAR (RFC 9126)](https://datatracker.ietf.org/doc/html/rfc9126)\n- [Duende IdentityServer Specs — Duende Docs](https://docs.duendesoftware.com/identityserver/overview/specs/)\n"
}

SHA-256: dccccc96ed1941ea5ef3b63410ef3fba771f89c277d5b2564b9116017b3094aa