duendesoftware/duende-skills/identity-testing-patterns

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.

Testing patterns for IdentityServer-based systems including integration testing with WebApplicationFactory, mock token issuance, test authority configuration, protocol response validation, and end-to-end authentication flow testing.

Install

npx vskill@latest install duendesoftware/duende-skills/identity-testing-patterns

SKILL.md

The same SKILL.md was published earlier as duendesoftware/duende-skills/identity-testing-patterns.

Identity Testing Patterns

When to Use This Skill

Use this skill when:

  • Writing integration tests for applications that issue or validate tokens using Duende IdentityServer
  • Hosting IdentityServer in-memory with WebApplicationFactory<T> to test grant flows end-to-end
  • Creating mock JWT tokens for testing protected APIs without a live authority
  • Testing custom IProfileService implementations or claim transformation logic
  • Verifying IAuthorizationHandler and policy-based authorization against specific claim sets
  • Testing BFF endpoints that rely on cookie-based sessions and proxied API calls
  • Scaffolding an integration-test project from the duende-is-inmem template to test IdentityServer itself
  • Running a post-deployment login-flow smoke test without a headless browser

Core Principles

  1. Integration over unit — Test token issuance, claim mapping, and policy enforcement against a real (in-process) IdentityServer instance. Avoid mocking the token pipeline itself; mock only external I/O (databases, downstream services).
  2. In-process authority — Use WebApplicationFactory<T> to host IdentityServer inside the test process. This avoids network round-trips, eliminates certificate trust issues, and makes tests deterministic.
  3. Predictable signing keys — Override key management in tests with a static development signing key so token signatures are verifiable without key rotation logic.
  4. Minimal test clients — Register only the clients, scopes, and resources each test needs. Over-broad test configurations mask permission bugs.
  5. Test auth handler for API tests — When testing protected APIs in isolation (without a live token endpoint), replace JWT Bearer authentication with a TestAuthHandler that accepts a fake scheme. Never disable authorization wholesale.
  6. Builder pattern for test data — Use fluent builders for Client, ApiScope, ApiResource, and test users to keep test setup readable and reduce duplication.

Related Skills

  • identityserver-configuration — Production client and resource registration patterns
  • aspnetcore-authentication — OIDC and JWT Bearer handler configuration
  • aspnetcore-authorization — Policy definitions and requirement handlers
  • claims-authorization — IProfileService and claim pipeline internals
  • duende-bff — BFF session and proxy architecture being tested

Docs: https://docs.duendesoftware.com/identityserver/fundamentals


Sub-Documents

DocumentDescriptionWhen to Load
docs/bff-testing.mdBFF endpoint testing with cookie simulation, antiforgery headers, and OIDC redirect bypassBFF testing, CookieContainer, x-csrf header, BffFactory, session simulation
docs/aspire-testing.mdFull-stack Aspire testing with identity server health checks and token endpoint wiringAspire testing, DistributedApplicationTestingBuilder, WaitForResourceHealthyAsync, end-to-end

Testing Strategy Overview

What to testRecommended approach
Token issuance (client credentials, code flow)In-process WebApplicationFactory hitting /connect/token
Claim mapping / IProfileServiceUnit test with DefaultProfileService + mock context, or integration test
Authorization policy requirementsIAuthorizationService + TestAuthHandler in integration test
IAuthorizationHandler logicDirect unit test with AuthorizationHandlerContext
Protected API access controlWebApplicationFactory with TestAuthHandler and constructed ClaimsPrincipal
BFF endpoints (login/logout/user)WebApplicationFactory with cookie simulation
EF Core store implementationsIn-memory EF provider or isolated SQL container
Deployed login flow (smoke test)Cookie-aware HttpClient + AngleSharp HTML parsing (Pattern 10)

Pattern 1: WebApplicationFactory for IdentityServer

Host a complete IdentityServer in-memory. Override configuration to inject test clients, resources, and a static signing key.

Required NuGet Packages
xml
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="*" />
<PackageReference Include="xunit" Version="*" />
<PackageReference Include="xunit.runner.visualstudio" Version="*" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="*" />
<PackageReference Include="IdentityModel" Version="*" />
</ItemGroup>
IdentityServer WebApplicationFactory
csharp
// ✅ Factory that runs a real IdentityServer in-process
public sealed class IdentityServerFactory : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Testing");
builder.ConfigureTestServices(services =>
{
// Remove any existing IdentityServer registration to replace it cleanly
var descriptor = services.SingleOrDefault(
d => d.ServiceType == typeof(IConfigureOptions<IdentityServerOptions>));
if (descriptor is not null)
services.Remove(descriptor);
services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseFailureEvents = true;
// Disable automatic key management — use a static key for predictability
options.KeyManagement.Enabled = false;
})
.AddInMemoryClients(TestConfig.Clients)
.AddInMemoryApiScopes(TestConfig.ApiScopes)
.AddInMemoryApiResources(TestConfig.ApiResources)
.AddInMemoryIdentityResources(TestConfig.IdentityResources)
.AddTestUsers(TestConfig.Users)
// Static development signing key — never use this in production
.AddDeveloperSigningCredential(persistKey: false);
});
}
}
Requesting a Token in a Test
csharp
[Collection("IdentityServer")]
public class TokenEndpointTests : IClassFixture<IdentityServerFactory>
{
private readonly HttpClient _client;
public TokenEndpointTests(IdentityServerFactory factory)
{
_client = factory.CreateClient();
}
[Fact]
public async Task ClientCredentials_ShouldReturnAccessToken()
{
var response = await _client.RequestClientCredentialsTokenAsync(
new ClientCredentialsTokenRequest
{
Address = "https://localhost/connect/token",
ClientId = "test.service",
ClientSecret = "test-secret",
Scope = "api1"
});
Assert.False(response.IsError, response.Error);
Assert.NotEmpty(response.AccessToken);
Assert.Equal("Bearer", response.TokenType);
}
[Fact]
public async Task ClientCredentials_InvalidScope_ShouldReturnError()
{
var response = await _client.RequestClientCredentialsTokenAsync(
new ClientCredentialsTokenRequest
{
Address = "https://localhost/connect/token",
ClientId = "test.service",
ClientSecret = "test-secret",
Scope = "not.allowed" // ❌ scope not granted to this client
});
Assert.True(response.IsError);
Assert.Equal("invalid_scope", response.Error);
}
}
Testing IdentityServer Itself from the duende-is-inmem Template

The fastest way to get a real, in-process IdentityServer under test is to scaffold from the in-memory template duende-is-inmem (from the `Duende.Templates` NuGet package) and add a test project that references the host. Unlike the TestAuthHandler/TestTokenFactory patterns below — which mock auth in a downstream API — this exercises IdentityServer's real endpoints and token issuance (no auth mocking).

Test project setup:

  1. The test project must use the Web SDK so ASP.NET Core testing APIs resolve. Change the top of the .csproj:
xml
<!-- ❌ Default test project SDK -->
<Project Sdk="Microsoft.NET.Sdk">
<!-- ✅ Web SDK — required for WebApplicationFactory<T> against a web host -->
<Project Sdk="Microsoft.NET.Sdk.Web">
  1. Add packages to the test project:
xml
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="*" /> <!-- WebApplicationFactory<T> -->
<PackageReference Include="Duende.IdentityModel" Version="*" /> <!-- OIDC/OAuth client helpers -->
  1. Reference the IdentityServer host project (<ProjectReference Include="..\IdentityServerHost\IdentityServerHost.csproj" />).
  1. Make the template's static Config collections mutable so tests can add/clear clients and scopes:
csharp
// Config.cs — expose List<> instead of IEnumerable<> so tests can mutate
public static List<Client> Clients = [ /* ... */ ];
public static List<ApiScope> ApiScopes = [ /* ... */ ];
public static List<IdentityResource> IdentityResources = [ /* ... */ ];
Caution: With xUnit's parallel test execution, mutating shared static Config collections causes cross-test interference. Prefer per-test collections (or a fresh factory per test) over mutating shared statics.

Test class using the primary-constructor `IClassFixture`:

csharp
public class IdentityServerTests(WebApplicationFactory<Program> factory)
: IClassFixture<WebApplicationFactory<Program>>
{
// factory.CreateClient() serves the host over https on localhost
private readonly HttpClient _client = factory.CreateClient();
[Fact]
public async Task Discovery_document_is_available()
{
var disco = await _client.GetDiscoveryDocumentAsync();
Assert.False(disco.IsError);
}
[Fact]
public async Task Can_request_client_credentials_token()
{
var token = await _client.RequestClientCredentialsTokenAsync(new()
{
Address = "connect/token",
ClientId = "m2m.client",
ClientSecret = "secret",
Scope = "api1"
});
Assert.False(token.IsError);
Assert.NotNull(token.AccessToken);
}
[Fact]
public void Can_resolve_in_process_services()
{
// Reach into the running host's DI container
using var scope = factory.Services.CreateScope();
var profileService = scope.ServiceProvider.GetRequiredService<IProfileService>();
Assert.NotNull(profileService);
}
}
The discovery/token helpers (GetDiscoveryDocumentAsync, RequestClientCredentialsTokenAsync) come from `Duende.IdentityModel`. Accessing factory.Services lets you assert on real in-process services such as IProfileService, stores, or options.

Pattern 2: Test Configuration Builders

Use static builders — not scattered inline literals — so every test builds from a consistent baseline.

csharp
public static class TestConfig
{
public static IEnumerable<Client> Clients =>
[
ClientBuilder.ClientCredentials("test.service", "test-secret")
.WithScopes("api1", "api2.read")
.Build(),
ClientBuilder.AuthorizationCode("test.webapp", "webapp-secret")
.WithRedirectUri("https://testapp/signin-oidc")
.WithScopes("openid", "profile", "api1")
.Build()
];
public static IEnumerable<ApiScope> ApiScopes =>
[
new ApiScope("api1", "Primary API"),
new ApiScope("api2.read", "Read from API 2")
];
public static IEnumerable<ApiResource> ApiResources =>
[
new ApiResource("api1-resource", "API 1 Resource")
{
Scopes = { "api1" }
}
];
public static IEnumerable<IdentityResource> IdentityResources =>
[
new IdentityResources.OpenId(),
new IdentityResources.Profile()
];

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

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