API Authentication Patterns
Methods for verifying the identity of API consumers, including API keys, OAuth 2.0 Bearer tokens, JWTs, and mutual TLS.
Description
API authentication ensures that the server knows who is making a request, and it serves as the foundation for authorization decisions. The most common patterns are API keys (simple shared secrets sent via header or query parameter), OAuth 2.0 Bearer tokens (JWTs or opaque tokens obtained through an authorization flow), and mutual TLS (mTLS) for service-to-service communication. Each pattern suits different use cases: API keys work well for server-to-server integrations with trusted partners, OAuth 2.0 is essential for user-delegated access, and mTLS provides strong identity for zero-trust service meshes.
JWT-based authentication is popular because the token itself carries identity claims (sub, email, roles) and can be verified without a database lookup using the token's signature. However, JWTs cannot be revoked individually before expiry without maintaining a blocklist, so short expiry times (15 minutes) combined with refresh tokens are the standard practice. API keys, while simpler, should be treated as secrets -- transmitted only over TLS, stored hashed in the database, and rotatable without downtime.
A production API typically combines multiple authentication methods: API keys for external integrations, OAuth 2.0 for user-facing applications, and mTLS or signed JWTs for internal service-to-service calls. The API should return 401 Unauthorized when credentials are missing or invalid and 403 Forbidden when credentials are valid but insufficient for the requested operation.
Prompt Snippet
Support Bearer token authentication via the Authorization header using short-lived JWTs (15-minute expiry) signed with RS256. Validate tokens by checking the signature against the JWKS endpoint, verifying iss, aud, and exp claims. For third-party integrations, issue scoped API keys prefixed with the environment (e.g., sk_live_, sk_test_), store them hashed with SHA-256, and support key rotation with a grace period where both old and new keys are valid. Use mTLS with SPIFFE IDs for internal service-to-service calls within the service mesh.
Tags
Related Terms
API Key Management
The lifecycle management of API keys including generation, secure storage, rotation, scoping, and revocation.
CORS Configuration
Browser-enforced HTTP headers that control which origins, methods, and headers are allowed to make cross-origin requests to an API.
Webhook Signature Verification
Cryptographic signing of webhook payloads using HMAC-SHA256 so consumers can verify authenticity and integrity of incoming events.