In an ASP.NET Core 10 WebApplicationFactory test, how do you make calls to the job-board API's [Authorize] endpoints run as a chosen signed-in user?
answer
- a scheme only the tests register
- AddScheme<AuthenticationSchemeOptions, TestAuthHandler>
- DefaultAuthenticateScheme and DefaultChallengeScheme
- AuthenticateResult.Success with a ticket
- "Scheme already exists" on name reuse
basics
~10 sRegister a test AuthenticationHandler under its own scheme name in ConfigureTestServices, make it the default authenticate and challenge scheme, and have it return AuthenticateResult.Success with a ticket carrying the claims the test needs.
solid answer
~40 sIn `ConfigureTestServices`, call `services.AddAuthentication(o => { o.DefaultAuthenticateScheme = "Test"; o.DefaultChallengeScheme = "Test"; }).AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("Test", _ => { })`. Those option callbacks run after the app's own `AddAuthentication(JwtBearerDefaults.AuthenticationScheme)`, and the specific defaults beat `DefaultScheme`, so `UseAuthentication` now builds `HttpContext.User` from the test handler while the real authorization policies still run. The handler's `HandleAuthenticateAsync` builds a `ClaimsPrincipal` from, say, a user id in the `Authorization` header and returns `AuthenticateResult.Success(new AuthenticationTicket(principal, "Test"))`, or `AuthenticateResult.NoResult()` when the header is absent so anonymous tests still behave anonymously. Two traps: registering the handler under the existing name `Bearer` throws `InvalidOperationException` ("Scheme already exists: Bearer"), and an endpoint whose `[Authorize]` names `AuthenticationSchemes = "Bearer"` ignores the defaults and keeps answering 401.
code
csharp · 22 linespublic sealed class TestAuthHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
public const string Scheme = "Test";
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var header = Request.Headers.Authorization.ToString();
if (!header.StartsWith("Test ", StringComparison.Ordinal))
return Task.FromResult(AuthenticateResult.NoResult());
var identity = new ClaimsIdentity(
[new Claim(ClaimTypes.NameIdentifier, header["Test ".Length..]),
new Claim(ClaimTypes.Role, "Recruiter")],
Scheme);
var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}go deeper
Know that tests fake the user with a separate authentication scheme registered only in the test host, rather than by fetching real tokens.
Walk through the handler, AddScheme, the default authenticate and challenge schemes, and why Success needs an identity with an authentication type.
Name the traps that make such tests lie: duplicate scheme names, endpoints pinned to Bearer, and over-privileged test principals hiding missing-claim bugs.
Decide how much of the real token path gets its own tests versus being replaced, so the suite stays fast without leaving JWT validation entirely unexercised.
## The goal The job-board API protects `GET /me/applications` and `POST /jobs` with `[Authorize]` (or `RequireAuthorization()` on the Minimal API group) and validates JWTs from an identity provider. An in-memory test cannot easily obtain a real token, and it should not depend on one. The standard approach is a **test authentication scheme**: a handler that only the test host registers and that produces whatever principal the test asks for. Authorization (policies, roles, resource checks) keeps running for real against that principal. ## The pieces 1. **A handler.** Derive from `AuthenticationHandler<AuthenticationSchemeOptions>` and implement `HandleAuthenticateAsync`. Use the constructor taking `IOptionsMonitor<TOptions>`, `ILoggerFactory` and `UrlEncoder`; the overload that also takes `ISystemClock` is obsolete. 2. **A scheme name** that the app does not already use, such as `"Test"`. 3. **Registration in the test host**, inside `ConfigureTestServices`, through `AddAuthentication(...)` and `AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("Test", _ => { })`. 4. **A way to pick the user per request**, commonly a value in the `Authorization` header that the handler turns into claims. ## Why the defaults take over `AddAuthentication(Action<AuthenticationOptions>)` registers one more configuration callback for `AuthenticationOptions`. Callbacks run in registration order, and the factory's run after `Program.cs`'s, so the test's values are applied last. The authentication middleware calls the **default authenticate scheme** to populate `HttpContext.User`; the lookup order is: | Operation | First choice | Fallback | |---|---|---| | authenticate | `DefaultAuthenticateScheme` | `DefaultScheme` | | challenge (401) | `DefaultChallengeScheme` | `DefaultScheme` | | forbid (403) | `DefaultForbidScheme` | the challenge scheme | The app's `AddAuthentication("Bearer")` set only `DefaultScheme`, so setting the authenticate and challenge defaults to `"Test"` routes both operations to the test handler, and forbid follows the challenge scheme. ## What the handler returns - **`AuthenticateResult.Success(ticket)`** with an `AuthenticationTicket(principal, "Test")`. The principal's `ClaimsIdentity` must be constructed with an authentication type (the scheme name works), or `IsAuthenticated` is false and `[Authorize]` still rejects it. - **`AuthenticateResult.NoResult()`** when the request carries no test credentials, so the request stays anonymous: `[Authorize]` endpoints challenge with 401 and `[AllowAnonymous]` endpoints work. - **`AuthenticateResult.Fail(...)`** only when a test wants to model a bad credential. Authentication middleware never rejects a request by itself; the 401 comes from the authorization step challenging the scheme. ## Traps - **Reusing the app's name.** `AddScheme("Bearer", ...)` when `AddJwtBearer()` already registered `Bearer` throws `InvalidOperationException: Scheme already exists: Bearer`. Use a new name. - **Endpoints that name a scheme.** `[Authorize(AuthenticationSchemes = "Bearer")]` or a policy built with `AddAuthenticationSchemes("Bearer")` authenticates only with that scheme, bypassing the defaults, so the test user never reaches it. Prefer the default scheme in the app; an endpoint that must pin a scheme needs that scheme's real credentials in its tests. - **Too-generous principals.** Giving every test user every role hides missing-claim bugs. Build the claims each test needs. - **Shared factories.** Register the scheme in the factory every protected test uses, and choose the user per request through the header, so one booted host serves many users. ## Matching the claims the app reads The test principal must carry the claim types the application code actually reads, or the endpoint behaves as if the user were missing: - JWT bearer's `MapInboundClaims` defaults to `true`, so a token's `sub` arrives as `ClaimTypes.NameIdentifier`. App code that calls `User.FindFirstValue(ClaimTypes.NameIdentifier)` therefore works in production, and the test handler should emit that same type. - If the app sets `MapInboundClaims = false` and reads `sub` directly, the handler must emit `sub` instead. - Role checks use the identity's role claim type, which defaults to `ClaimTypes.Role` for a `ClaimsIdentity` built as in the example. A mismatch here produces tests that pass authentication and then fail on a null user id, which looks like an endpoint bug rather than a fixture bug. ## Picking the user per request A handler that reads `Authorization: Test recruiter-17`, puts `recruiter-17` into `ClaimTypes.NameIdentifier` and adds a role claim lets tests switch identities simply by setting `client.DefaultRequestHeaders.Authorization`, with no new factory per user. Keep the header parsing strict so a malformed value fails visibly rather than signing in an unexpected user.
- How do you check the 403 path with the same test scheme?Sign in a user whose claims fail the endpoint's policy, for example a candidate without the `Recruiter` role. Authentication succeeds, authorization fails, and the forbid call falls back to the default challenge scheme, `Test`, whose base handler answers 403.
- Why is the principal not authenticated even though the handler returns Success?A `ClaimsIdentity` created without an authentication type reports `IsAuthenticated == false`, and `[Authorize]`'s requirement checks exactly that. Pass the scheme name as the identity's authentication type.
- Register the test handler under the app's Bearer name to replace JWT validation.
- A test authentication scheme also bypasses authorization policies and role checks.
- DefaultAuthenticateScheme also changes endpoints that name their scheme in [Authorize].
- Authentication middleware rejects anonymous requests itself, so the handler must always succeed.
- AddAuthentication in ConfigureTestServices is ignored because the app already called it.