Test an ASP.NET Core API with real access tokens

Use WebApplicationFactory and Playwright for .NET to test the API’s JWT bearer handler with real access and ID tokens from test users.

Verified with .NET 10.0, .NET SDK 10.0.404, ASP.NET Core JwtBearer 10.0.13, Playwright for .NET 1.65.1.

The problem

Replacing authentication with a test handler can exercise an authorization policy, but it leaves the API’s issuer, signature, audience and claim handling untested.

Why HeyIdentity fits

A Generic configuration issues tokens for two predictable users. The fixture runs one browser sign-in per role, checks the callback state and exchanges each code with S256 PKCE. The API uses its real JWT bearer handler in WebApplicationFactory.

Prerequisites

Install .NET SDK 10.0.404, Node.js 22.12 or later, and Git. The SDK can be installed alongside other versions. If the checkout reports that a compatible .NET SDK was not found, install 10.0.404 and check dotnet --version at the checkout root. You also need PowerShell 7 (pwsh) on Windows, Linux or macOS to install the Playwright browser.

Clone the verified example

Start in the directory where you keep your repositories. These commands open the revision used for this guide. Browse the runnable example on GitHub.

git clone https://github.com/heyidentity/examples.git heyidentity-examples
cd heyidentity-examples
git checkout --detach 391c07e010699fff660fa3b4c9f4ce86cd6fa234

Set up HeyIdentity

Reuse an active configuration if it uses the Generic profile and the issuer, client and registered URLs match this example and the configured API audience matches. Register http://localhost:5173/callback for sign-in. This fixture uses the registered callback with the port in APP_PORT. It runs without a callback listener.

For a different profile, incompatible settings or an expired configuration, start from a separate checkout so the old .env and agent token remain available. Temporary setup asks you to accept the Terms of Use. An unclaimed configuration expires after seven days. Claim or recover a setup.

Use a temporary configuration

From the checkout root, provision a public client and set the dedicated access-token audience in .env.

node setup/provision.mjs --temporary --api-audience https://api.example.test/orders

Use a configuration you own

Copy .env.example to .env at the checkout root. Under Connect your app, copy the issuer to OIDC_AUTHORITY. It has the shape https://app.heyidentity.dev/t/{tenantRouteId}/c/{configurationId}. Copy the public client ID from Clients to OIDC_CLIENT_ID. Register the exact callback URL above. Set a separate access-token audience on the client, such as https://api.example.test/orders, and copy that value to API_AUDIENCE. It must differ from OIDC_CLIENT_ID so the bearer handler rejects an ID token. Set ADMIN_USER_KEY and READER_USER_KEY to the keys of two test users with roles of ["admin"] and ["reader"] respectively.

Sign in and reuse the tokens

The sign-in fixture validates the exact callback and returned state before exchanging the code. It holds the tokens in memory for the run and fails if it counted anything but one picker sign-in per test user.

        (AdminAccessToken, AdminIdToken) = await SignInAsync(browser, authorization, token, clientId, redirect, adminKey);
        (ReaderAccessToken, _) = await SignInAsync(browser, authorization, token, clientId, redirect, readerKey);
        // One sign-in per test user for the whole run. Report only the count, never a URL, code or token.
        if (authorizeNavigations != 2)
            throw new InvalidOperationException($"Expected 2 picker sign-ins for the run, counted {authorizeNavigations}.");
        Console.WriteLine("Obtained tokens from two picker sign-ins.");

Configure API authentication

The bearer handler validates issuer, signature and lifetime. It matches the API audience exactly, including any trailing slash, and reads the roles claim as issued.

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.Authority = issuer;
    options.Audience = audience;
    options.RequireHttpsMetadata = authority.Scheme == Uri.UriSchemeHttps;
    options.MapInboundClaims = false;
    options.TokenValidationParameters.IgnoreTrailingSlashWhenValidatingAudience = false;
    options.TokenValidationParameters.RoleClaimType = "roles";
    options.TokenValidationParameters.ValidateIssuer = true;
    options.TokenValidationParameters.ValidateIssuerSigningKey = true;
    options.TokenValidationParameters.ValidateLifetime = true;
});

Host the real API in the test process

public sealed class AdminTests(SignInFixture tokens, WebApplicationFactory<Program> factory)
    : IClassFixture<SignInFixture>, IClassFixture<WebApplicationFactory<Program>>
{
    [Theory]
    [InlineData("admin", HttpStatusCode.OK)]
    [InlineData("reader", HttpStatusCode.Forbidden)]
    [InlineData("id-token", HttpStatusCode.Unauthorized)]
    [InlineData("anonymous", HttpStatusCode.Unauthorized)]
    public async Task Checks_real_bearer_tokens(string caller, HttpStatusCode expected)
    {
        using var client = factory.CreateClient();

Run and verify

From the checkout root, enter the API example directory, build the test project, install its browser and run the tests.

cd integration/aspnetcore
dotnet restore --locked-mode
dotnet build --no-restore
pwsh Api.Tests/bin/Debug/net10.0/playwright.ps1 install chromium
dotnet test --no-build

Expect HTTP 200 for the admin, 403 for the reader, and 401 for a missing token or the admin ID token. A fifth test expects 401 when the API audience differs only by a trailing slash.

Keep CI sign-ins within the limits

Reuse one sign-in per test user for the whole run, as the sign-in fixture does. Nothing retries a rejected sign-in automatically: a fixture that gets a 429 fails the run. The CI limits FAQ gives the plan guidance for each way of getting tokens.

Token reuse and the plan it fits
How tests get tokensFits
One sign-in per test user, reused for the whole run (for example Playwright storage state, or a cached token)Free
One sign-in per test class or fixturePro, within its burst of 600
A fresh sign-in or token request per testNot recommended on any plan. From one runner it is stopped by the per-source limits, which no plan raises.

Cache tokens per test user, as the fixture does, instead of fetching a token per test. For a suite spread over several runners that needs more than Pro, see how to ask for higher limits.

Limitations

The API is in-memory. The browser still needs network access to HeyIdentity for sign-in, discovery and token exchange. The example covers bearer authentication and role checks. HeyIdentity is for development and testing.

Set up your own test configuration

Sign up

Explore the Playwright journey in the demo