ASP.NET Core › Authentication
How do you implement API key authentication as a custom authentication scheme for machine-to-machine API access?
AdvancedAnswer
Since API key authentication isn't a built-in ASP.NET Core scheme, you implement a custom AuthenticationHandler<TOptions> that extracts the key from a header or query parameter, validates it against a store (database, configuration, or cache), and constructs a ClaimsPrincipal representing the calling service/application if valid -- registered like any other scheme via AddScheme<TOptions, THandler>().
public class ApiKeyAuthHandler : AuthenticationHandler<ApiKeyAuthOptions> {
protected override async Task<AuthenticateResult> HandleAuthenticateAsync() {
if (!Request.Headers.TryGetValue("X-Api-Key", out var key))
return AuthenticateResult.Fail("Missing API key");
var client = await _keyStore.ValidateAsync(key);
if (client is null) return AuthenticateResult.Fail("Invalid API key");
var identity = new ClaimsIdentity(new[] { new Claim("client", client.Name) }, Scheme.Name);
return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name));
}
}Real-world example A B2B integration platform issues each partner a unique API key validated by a custom authentication handler, letting partner-specific rate limits and permissions be enforced based on the resolved ClaimsPrincipal's client identity claim.