API authentication: API keys vs JWT vs OAuth2
API key authentication, JWT structure, OAuth2 flows, bearer tokens, token expiry, refresh tokens, stateless vs stateful auth
API authentication: API keys vs JWT vs OAuth2
Three Mechanisms, Three Use Cases
Authentication is who you are. Authorization is what you can do. Start with the right mechanism for your use case.
API Keys
Best for server-to-server communication. Simple to implement. The key is sent in a header:
GET /data
Authorization: Bearer sk_live_abc123xyzNo expiry built in — you manage rotation. Store keys hashed with SHA-256, never in plaintext.
JWT (JSON Web Token)
Self-contained token carrying claims. Three parts: header, payload, signature. The server validates the signature — no database lookup needed, making it stateless and fast.
# Decoded payload
{
"sub": "user_42",
"role": "admin",
"exp": 1718000000
}Short expiry (15 minutes) plus a refresh token is the standard pattern. If a JWT is stolen, you cannot revoke it before expiry unless you maintain a token blocklist — which breaks the stateless advantage.
OAuth2
A delegation protocol. The user authorizes a third-party app to access resources on their behalf. Use Authorization Code flow for web apps and Client Credentials flow for machine-to-machine. OAuth2 is complex — use a library or identity provider such as Auth0 or Keycloak rather than implementing it yourself.
