API keys: appropriate uses, key format, hashing stored keys, scoping and rotation, constant-time comparison, and an ASP.NET Core AuthenticationHandler implementation.
An API key is a long random secret that identifies a calling application, not a user. It suits partner integrations, internal tools and webhooks where OAuth would be overkill, but it is a static bearer secret, so design for leaks.
RandomNumberGenerator, add a prefix and key id (sk_live_<id>_<secret>) so you can look it up and secret scanners can spot it.FixedTimeEquals.AuthenticationHandler that turns a valid key into claims; policies decide access.The trade-off: keys are simple for partners but never expire on their own; OAuth client credentials give short-lived tokens.
"An API key answers 'which application is calling?'. It's a good fit for server-to-server integrations with partners who can't or won't do OAuth, for webhooks, and for internal automation. It's a poor fit for anything acting as a user, or for browser and mobile apps, because a key shipped to a client is public. If the partner can do OAuth client credentials, I prefer that: tokens expire in an hour and the key material never travels on every request.
For example, at [company] we had partner keys stored in plain text in a
Partnerstable and compared with==. I redesigned it: keys are 32 random bytes fromRandomNumberGenerator, formatted aspk_live_{keyId}_{secret}; we store only the key id, a SHA-256 hash of the secret, its scopes, expiry and last-used time. Plain SHA-256 is fine here because the secret has 256 bits of entropy, unlike a password. The handler parses the header, looks up the key id, hashes the presented secret and compares withCryptographicOperations.FixedTimeEquals, then builds aClaimsPrincipalwith the partner id and scopes. Each partner can have two active keys so they rotate without downtime. [Result: we rotated all ~40 partner keys in two weeks with no failed calls, and a database leak would no longer expose usable keys.]The mistake I see is keys in query strings, where they end up in proxy logs, and one key per partner shared across environments forever. The senior line: assume every API key will leak eventually, and make that cheap: hashed at rest, scoped, expiring and easy to rotate."
| Mechanism | Identifies | Expires | Fits |
|---|---|---|---|
| API key | An application | Only if you build it | Partner B2B, webhooks, internal scripts |
| OAuth client credentials | An application | Token in minutes to an hour | Partners with an IdP-capable stack, service-to-service |
| Managed identity | An Azure workload | Automatically | Your own Azure services |
| mTLS client certificate | An application | Certificate validity | Banking, CDR, high-assurance B2B |
| User tokens (OIDC) | A user | Minutes | Anything acting for a person |
| Concern | Choice |
|---|---|
| Entropy | 32 bytes from RandomNumberGenerator, base64url |
| Format | pk_live_{keyId}_{secret}: prefix for scanning, id for lookup, environment visible |
| Storage | Key id + SHA-256(secret) + scopes + expiry + last used + created by |
| Comparison | FixedTimeEquals on hash bytes |
| Transport | X-Api-Key or Authorization: ApiKey ... header over TLS, never the URL |
| Rotation | Two active keys, overlap window, revoke on schedule or on leak |
After the redesign, the handler added [~0.3 ms] per request with a 60-second cache of key records, partner keys moved from never-expiring to [12-month] expiry with reminder emails at [30 and 7] days, and GitHub secret scanning flagged [one] leaked key in a partner's public repo within minutes thanks to the prefix.
Checks whether the candidate can implement API-key authentication securely and knows its limits compared with OAuth.
Green flags
AuthenticationHandler that only builds claimsRed flags
Passwords are low-entropy, so we use slow hashes to make guessing expensive. A 256-bit random key can't be guessed, so a fast hash such as SHA-256 is enough to make a stolen table useless, and it keeps per-request verification cheap. HMAC-SHA256 with a server-side pepper from Key Vault adds protection if the database leaks without the app secrets.
X-Api-Key: pk_live_7Q2k_9f8s...
-> parse prefix, keyId, secret
-> load key record by keyId (cache 60 s)
-> FixedTimeEquals(SHA256(secret), record.Hash)
-> check expiry, revoked flag, environment
-> ClaimsPrincipal { client_id, scope... }
-> authorisation policies use scopes
-> rate limiter partitions by client_id
A normal string comparison stops at the first different character, so response times leak how much of the value matched. Comparing hashes already makes this hard to exploit, but CryptographicOperations.FixedTimeEquals removes the question entirely.
Store keys as rows, not as one column on the partner. Rotation is: issue key B, partner deploys it, monitor last-used on key A, revoke A. Emergency revocation sets RevokedAt and evicts the cache entry. Track LastUsedUtc asynchronously (batch updates) to avoid a write per request.
A distinctive prefix lets GitHub secret scanning (via its partner programme or custom patterns) and tools like Gitleaks find leaked keys. GitHub, Stripe and others use this approach for exactly that reason.
WebApplicationFactory for valid, wrong, expired and missing keys.client_id claim and confirm a noisy partner gets 429s while others don't.Vulnerable: plain-text keys in the query string, compared with ==.
// Exploit in one line: anyone with access to proxy or CDN logs replays ?key=... from the URL.
app.MapGet("/orders", (string key, PartnerDb db) =>
db.Partners.Any(p => p.ApiKey == key) ? Results.Ok() : Results.Unauthorized());
Fixed: an authentication handler with hashed, scoped, expiring keys.
// ApiKeyAuthenticationHandler.cs (.NET 10)
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
namespace Partners.Api.Security;
public sealed record ApiKeyRecord(string KeyId, byte[] SecretHash, string ClientId, string[] Scopes,
DateTimeOffset ExpiresAt, DateTimeOffset? RevokedAt);
public interface IApiKeyStore
{
Task<ApiKeyRecord?> FindAsync(string keyId, CancellationToken ct);
}
public sealed class ApiKeyAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
IApiKeyStore store,
TimeProvider clock)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
public const string SchemeName = "ApiKey";
private const string HeaderName = "X-Api-Key";
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!Request.Headers.TryGetValue(HeaderName, out var values))
return AuthenticateResult.NoResult(); // let other schemes or [AllowAnonymous] work
// Format: pk_live_{keyId}_{secret}
var parts = values.ToString().Split('_', 4);
if (parts is not ["pk", "live", var keyId, var secret])
return AuthenticateResult.Fail("Malformed API key");
var record = await store.FindAsync(keyId, Context.RequestAborted);
if (record is null || record.RevokedAt is not null || record.ExpiresAt <= clock.GetUtcNow())
return AuthenticateResult.Fail("Unknown, revoked or expired API key");
var presented = SHA256.HashData(Encoding.UTF8.GetBytes(secret));
if (!CryptographicOperations.FixedTimeEquals(presented, record.SecretHash))
return AuthenticateResult.Fail("Invalid API key");
var claims = new List<Claim> { new("client_id", record.ClientId) };
claims.AddRange(record.Scopes.Select(s => new Claim("scope", s)));
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, SchemeName));
return AuthenticateResult.Success(new AuthenticationTicket(principal, SchemeName));
}
}
// Program.cs
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddScoped<IApiKeyStore, SqlApiKeyStore>(); // cached lookup by key id
builder.Services.AddAuthentication(ApiKeyAuthenticationHandler.SchemeName)
.AddScheme<AuthenticationSchemeOptions, ApiKeyAuthenticationHandler>(ApiKeyAuthenticationHandler.SchemeName, null);
builder.Services.AddAuthorizationBuilder()
.AddPolicy("orders.read", p => p.RequireClaim("scope", "orders.read"));
app.MapGet("/orders", () => Results.Ok()).RequireAuthorization("orders.read");
// Issuing a key: show it once, store only the hash.
static (string Key, byte[] Hash) CreateKey(string keyId)
{
var secret = Base64UrlEncoder.Encode(RandomNumberGenerator.GetBytes(32)); // Microsoft.IdentityModel.Tokens
return ($"pk_live_{keyId}_{secret}", SHA256.HashData(Encoding.UTF8.GetBytes(secret)));
}
== or string.Equals. Why it is wrong: early-exit comparison leaks timing information. Instead: CryptographicOperations.FixedTimeEquals on fixed-length hashes.if (path.StartsWith("/admin"))). Why it is wrong: it bypasses policies and is easy to get wrong. Instead: the handler emits scopes; policies check them.Fail when the header is missing. Why it is wrong: it logs noise and can break anonymous endpoints or other schemes. Instead: NoResult() when no key is present.API keys are a usability choice for partners, not a security upgrade. I accept them where the integrator's stack is simple, and compensate with hashing, scoping, expiry, per-key rate limits and good logging. For anything with regulatory weight, such as the Consumer Data Right in banking, the standard requires stronger mechanisms (mTLS and OAuth with FAPI profiles), so keys aren't an option.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Hashed, scoped API keys | Small partners, webhooks, internal automation | Key management UI and rotation process | User-level access, browsers, regulated data |
| OAuth client credentials | Partners who can run a token client | IdP setup, client onboarding | Partners with very simple tooling |
| mTLS + OAuth (FAPI) | Open banking / CDR, high assurance | Certificate lifecycle | Low-risk public data |
Measure per-key request rates, failure reasons and last-used dates; unused keys older than 90 days should be revoked automatically.
Register limiters with builder.Services.AddRateLimiter, add app.UseRateLimiter() after routing and authentication, then attach named policies to endpoints with RequireRateLimiting("name") or [EnableRateLimiting]. For fairness use RateLimitPartition.GetTokenBucketLimiter (or fixed/sliding window) keyed by the API key, user id or tenant so one client can't exhaust another's quota. Set RejectionStatusCode = 429 (the default is 503) and use OnRejected to copy the lease's RetryAfter metadata into the Retry-After header with a ProblemDetails body. The catch: the middleware keeps state in memory per process, so with several instances the effective limit multiplies; contractual limits belong in a shared store or the gateway.
Authentication answers who are you? and authorisation answers what are you allowed to do? In ASP.NET Core, authentication is built from schemes: a name plus an authentication handler (cookies, JwtBearer, OpenIdConnect, or your own). The handler reads a credential from the request, validates it and produces a ClaimsPrincipal, which the authentication middleware puts on HttpContext.User. The authorisation middleware then checks the endpoint's [Authorize] metadata against that principal: no identity means a challenge (401 or a login redirect), an identity without permission means forbid (403).
Order matters: UseAuthentication must run before UseAuthorization, and both after routing and CORS, or the user is anonymous when the decision is made. The trade-off is flexibility versus clarity: several schemes are powerful, but every extra scheme is another way to be authenticated by accident.
How to tell it (STAR)
**S:** A database backup with [~40] plain-text partner API keys was exposed through a [misconfigured storage account], and one key was already being used from an unfamiliar IP range. **T:** I owned the API side of the response and the redesign. **A:** I coordinated revoking and reissuing every key with a short overlap so partners could switch without an outage, scrubbed keys from logs, and then rebuilt key handling: hashed storage, scoped and expiring keys, header-only transport and a custom authentication handler with constant-time comparison. **R:** All partners were on new keys within [48 hours] with [no] failed integrations, misuse stopped immediately, and the redesign passed the next pen test with [no] findings on authentication.
Last updated 23 Nov 2026.