📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

When is an API key an appropriate way to authenticate callers? Explain how you would store, scope and rotate API keys safely, and write a custom API-key authentication handler for ASP.NET Core.

API keys: appropriate uses, key format, hashing stored keys, scoping and rotation, constant-time comparison, and an ASP.NET Core AuthenticationHandler implementation.

Mid-Level Security Intermediate api-keys aspnet-core authentication authentication-handler key-rotation security

🎯 Key points

  • API keys identify a calling application, not a user: B2B partners, webhooks, simple integrations
  • Generate 256 bits with RandomNumberGenerator; prefix plus key id for lookup and secret scanning
  • Store only a hash: HMAC-SHA256 with a Key Vault pepper (or SHA-256); slow hashes aren't needed for 256-bit keys
  • Show the key once, never log it, compare with CryptographicOperations.FixedTimeEquals
  • Scope per key (permissions, environment), expiry, last-used tracking, auto-revoke unused keys
  • Rotation: two active keys per client, overlap window; emergency revocation flag + cache eviction + partner notification
  • AuthenticationHandler<T> returns NoResult without a key and only builds claims; policies decide
  • Header only (never query string); TLS; rate limit per key; prefer OAuth client credentials when possible

⏱ 30-second answer

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.

  • Generate 256 random bits with RandomNumberGenerator, add a prefix and key id (sk_live_<id>_<secret>) so you can look it up and secret scanners can spot it.
  • Store only a hash (SHA-256 is fine for high-entropy keys), show the key once, and compare with FixedTimeEquals.
  • Scope each key, set an expiry, allow two active keys for rotation, track last use.
  • Implement an 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 Partners table and compared with ==. I redesigned it: keys are 32 random bytes from RandomNumberGenerator, formatted as pk_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 with CryptographicOperations.FixedTimeEquals, then builds a ClaimsPrincipal with 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."


When to use what

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

Key design

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can implement API-key authentication securely and knows its limits compared with OAuth.

Green flags

  • Hashes stored keys and explains why a fast hash is fine for random keys
  • Uses a constant-time comparison
  • Designs scoping, expiry and overlapping rotation
  • Implements an AuthenticationHandler that only builds claims
  • Prefers client credentials when the partner can do it

Red flags

  • Keys in query strings or plain text
  • Uses API keys to authenticate end users in a SPA
  • No rotation plan

📚 Learn in depth

1. Why a hash, and why not bcrypt

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.

2. The request path

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

3. Timing attacks

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.

4. Rotation and revocation

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.

5. Secret scanning

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.

Try it yourself

  1. Implement the handler below and write an integration test with WebApplicationFactory for valid, wrong, expired and missing keys.
  2. Measure handler overhead with and without the cache using BenchmarkDotNet.
  3. Add a custom GitHub secret scanning pattern for your prefix in a test repo and commit a fake key.
  4. Partition the rate limiter by the client_id claim and confirm a noisy partner gets 429s while others don't.
  5. Write the rotation runbook as an ADR.

💻 Code

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)));
}

⚠ Common mistakes

  • Mistake: Accepting keys in the query string. Why it is wrong: URLs are logged by proxies, CDNs, browsers and Application Insights. Instead: a header only, and reject keys in URLs.
  • Mistake: Storing keys in plain text or encrypted. Why it is wrong: a database leak or a DBA can use them. Instead: store a SHA-256 (or HMAC with a pepper) hash and show the key once.
  • Mistake: Comparing with == or string.Equals. Why it is wrong: early-exit comparison leaks timing information. Instead: CryptographicOperations.FixedTimeEquals on fixed-length hashes.
  • Mistake: One key per partner with no expiry. Why it is wrong: rotation means downtime, so it never happens. Instead: multiple active keys per client and an expiry with reminders.
  • Mistake: Using API keys in SPAs or mobile apps. Why it is wrong: anything shipped to a client is public. Instead: user authentication with OIDC, or a BFF that holds the key.
  • Mistake: Doing authorisation inside the handler (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.
  • Mistake: Returning 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.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions rate limiting per partner Why: Checks they can partition the rate limiter by the authenticated client
    How to answer

    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.

  2. When: Candidate writes an authentication handler Why: Checks they understand schemes, NoResult vs Fail and where decisions belong
    How to answer

    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.

🛠 Real-world problems: how you handle them

Partner API keys found in plain text after a database backup leak
Situation
A B2B [logistics] API had [~40] partners, each with one API key stored in plain text in the `Partners` table and accepted in the `?key=` query string. A [misconfigured storage account] exposed a database backup for [several days].
Signals
Microsoft Defender for Cloud alert on anonymous access to the storage container; Application Insights showed one partner's key used from [a new IP range] at [unusual hours]; the CDN logs also contained full URLs with keys.
Investigation
Confirmed the exposure window from storage account logs; queried API logs for each key by client IP and user agent to find misuse; found that keys also appeared in CDN and Application Insights request URLs; reviewed whether the exposed backup contained personal information and assessed it with [the privacy officer] against the NDB scheme.
Resolution
Same day: locked the container, revoked every key, issued new keys to partners through [the partner portal] with a 48-hour overlap, and purged URLs from logs where possible. Over the next sprint: moved keys to the header only, stored SHA-256 hashes, added key ids, scopes, expiry and two active keys per partner, and offered OAuth client credentials to partners who could use it.
Prevention
Azure Policy denying public blob access; secret scanning with the key prefix; a middleware that rejects requests with keys in the query string; alerts on a key used from a new country or ASN; quarterly key-expiry report.

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.

↩ Usually asked after

More in Authentication

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me