In ASP.NET Core, how would you let one app accept cookie sign-in for a parents' portal and an API key for a partner feed, using a custom handler and AddPolicyScheme?
answer
- AuthenticationHandler<TOptions>.HandleAuthenticateAsync
- NoResult vs Fail vs Success
- ForwardDefaultSelector picks per request
- policy scheme as DefaultScheme
- TimeProvider replaced ISystemClock
basics
~20 sWrite an AuthenticationHandler that turns a valid key into an AuthenticateResult.Success ticket, register it with AddScheme next to AddCookie, and make an AddPolicyScheme the default whose ForwardDefaultSelector sends partner requests to the key scheme and everything else to cookies.
solid answer
~40 sThe key scheme is a class deriving from `AuthenticationHandler<AuthenticationSchemeOptions>` that overrides `HandleAuthenticateAsync`: no header means `AuthenticateResult.NoResult()`, an unknown key means `AuthenticateResult.Fail(...)`, a good key means `Success(new AuthenticationTicket(principal, Scheme.Name))`. Register it with `AddScheme<AuthenticationSchemeOptions, PartnerKeyHandler>("PartnerKey", null)` beside `AddCookie()`. Then add `AddPolicyScheme("Smart", null, o => o.ForwardDefaultSelector = ctx => ctx.Request.Path.StartsWithSegments("/partner") ? "PartnerKey" : "Cookies")` and make `"Smart"` the `DefaultScheme`. The policy scheme has no behaviour of its own; it forwards authenticate, challenge, forbid, sign-in and sign-out, so partners get the key handler's 401 and parents get the login redirect. On .NET 8 and later the handler's constructor takes `IOptionsMonitor<T>`, `ILoggerFactory` and `UrlEncoder`; the overload with `ISystemClock` is obsolete.
code
csharp · 22 linespublic sealed class PartnerKeyHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
IPartnerDirectory partners)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!Request.Headers.TryGetValue("X-Api-Key", out var key))
return AuthenticateResult.NoResult();
var partner = await partners.FindByKeyAsync(key.ToString());
if (partner is null)
return AuthenticateResult.Fail("Unknown partner key.");
var identity = new ClaimsIdentity(
[new Claim(ClaimTypes.NameIdentifier, partner.Id)], Scheme.Name);
return AuthenticateResult.Success(
new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name));
}
}go deeper
Recall that each way of proving identity is a scheme, and that one app can register several, such as cookies for people and a key for a partner system.
Explain HandleAuthenticateAsync's NoResult, Fail and Success results, and how AddScheme registers a custom handler beside AddCookie.
Choose between naming schemes per endpoint and a policy scheme as default, and handle the selector's null case, its cost and the risk of steering by an attacker-controlled header.
Judge when a hand-written key scheme should give way to issued tokens from an identity provider, weighing key rotation, auditing and partner onboarding.
## Two callers, two schemes The parents' portal uses the cookie scheme: a browser, a login page, redirects. The partner feed is called by a server that sends a key in an `X-Api-Key` header and must get a plain 401 on failure, never a login page. ASP.NET Core models each as a **scheme**, and the question is how a request ends up at the right one. ## Writing the key handler A custom scheme is a class deriving from `AuthenticationHandler<TOptions>`, where `TOptions` is `AuthenticationSchemeOptions` or a subclass carrying your settings. The only method you must override is `HandleAuthenticateAsync`, and its three results mean different things: | Result | Meaning | Effect | |---|---|---| | `AuthenticateResult.NoResult()` | this scheme does not apply (no header) | anonymous; authorization decides | | `AuthenticateResult.Fail("...")` | the scheme applies and the credential is bad | anonymous, failure logged; authorization decides | | `AuthenticateResult.Success(ticket)` | the credential is good | the ticket's principal is used | Returning `Fail` for a missing header is a common mistake: it fills logs with failures for every browser request that never meant to use the key. The base class's default `HandleChallengeAsync` sets 401 and `HandleForbiddenAsync` sets 403, which is exactly what a partner client expects. Compare keys with a fixed-time comparison and look them up hashed, the way you would a password. Since ASP.NET Core 8 the base constructor that also takes `ISystemClock` is obsolete; use the `(IOptionsMonitor<TOptions>, ILoggerFactory, UrlEncoder)` overload and the `TimeProvider` on the options when the handler needs the time. With C# 12 primary constructors the handler is a few lines. ## Routing requests to a scheme There are two common designs: 1. **Name the scheme on the endpoints.** Keep cookies as `DefaultScheme` and give the partner endpoints a policy with `AddAuthenticationSchemes("PartnerKey")`. Simple, explicit, but every partner endpoint must remember it, and middleware that runs before authorization only sees the cookie principal. 2. **A policy scheme in front.** `AddPolicyScheme(name, displayName, configure)` registers a `PolicySchemeHandler` whose only job is forwarding. Make it the `DefaultScheme`, and set `ForwardDefaultSelector` to a `Func<HttpContext, string?>` that inspects the request. With design 2, every action is forwarded: - `AuthenticateAsync` goes to the selected scheme, so `HttpContext.User` is filled correctly for both callers; - a challenge goes to the selected scheme too, so a partner request gets the key handler's 401 while a parent gets the cookie handler's redirect; - sign-in and sign-out are forwarded as well, so `SignInAsync` without a scheme name still reaches cookies when the selector picks them. ## Forwarding rules and traps `AuthenticationSchemeOptions` resolves a forward target in this order: an action-specific setting (`ForwardAuthenticate`, `ForwardChallenge`, `ForwardForbid`, `ForwardSignIn`, `ForwardSignOut`), then `ForwardDefaultSelector`, then `ForwardDefault`. Points interviewers press: - If the selector returns `null` and `ForwardDefault` is not set, the policy scheme's own handler methods run, and they throw `NotImplementedException`. Always return a scheme or set `ForwardDefault`. - The selector runs on every request, so keep it to cheap header or path checks; no database calls. - Any scheme, not only a policy scheme, can forward. Setting `ForwardChallenge` on a cookie scheme is a way to send its challenges elsewhere. - Do not select by a header an attacker can add to steer a request away from a stronger scheme; selecting by path (`/partner`) is often safer than by header presence. ## Putting it together The code below registers both schemes and the policy scheme; the partner endpoints then need only `RequireAuthorization()`. Checklist for the design review: - every selector branch returns a registered scheme name; - the key handler returns `NoResult` for requests without a key; - the key scheme never calls `SignInAsync`, because a key is presented on every call rather than remembered; - partner principals carry a claim that identifies the partner, so authorization and logging can tell partners apart; - keys are stored hashed and can be rotated without redeploying.
- Why should the key handler return NoResult rather than Fail when the X-Api-Key header is missing?`NoResult` says the scheme does not apply, which is true for every browser request. `Fail` says a credential was presented and was wrong; it is logged as a failure and can mislead auditing. Either way authorization makes the final decision, so `Fail` buys nothing for a missing header.
- The policy scheme's selector returns null for some requests and those requests throw. What is happening?With no selected scheme and no `ForwardDefault`, `PolicySchemeHandler` handles the call itself, and all its handler methods throw `NotImplementedException`. Return a scheme for every branch or set `ForwardDefault` as the fallback.
- A missing API key header should return AuthenticateResult.Fail from the handler.
- AddPolicyScheme authenticates the request itself by trying each scheme in turn.
- The custom handler must override HandleChallengeAsync or partners receive a login redirect.
- Inject ISystemClock into the handler constructor to read the current time.
- With two schemes registered, the authentication middleware runs both on every request.
Assumes ASP.NET Core 10; since ASP.NET Core 8 the AuthenticationHandler constructor that takes ISystemClock is obsolete in favour of TimeProvider on AuthenticationSchemeOptions.