Free — no signup required

Authentication Patterns for APIs: Tokens and Keys

2 min read

Why Cookies Don't Work Well for APIs

Traditional web apps use session cookies: the server stores session state, and the browser automatically sends the cookie with every request. This works for browsers but breaks down for mobile apps, third-party integrations, and microservices — they don't have a cookie jar, and they communicate across domains.

APIs use two primary authentication mechanisms: API Keys and JWT (JSON Web Tokens).

API Keys

An API key is a long, random string that identifies a caller. Think of it as a password for a service account.

GET /api/data
Authorization: Bearer sk_live_4xKj9mN2pQ8rT1vW

API keys are simple and effective for server-to-server communication where the key can be stored securely. They have one major weakness: they don't expire automatically and don't carry identity information. If a key is leaked, it's valid until manually revoked.

Best practices for API keys:
- Transmit only over HTTPS — never in URLs (they appear in server logs)
- Scope keys to minimum permissions (a read-only key can't write)
- Rotate keys regularly and support immediate revocation
- Store keys hashed on the server, just like passwords

JWT (JSON Web Token)

A JWT is a self-contained token that carries claims (assertions) about the user, signed by the server. It has three Base64-encoded parts separated by dots: header.payload.signature.

eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiIxMDAxIiwicm9sZSI6InVzZXIiLCJleHAiOjE3MDAwMDAwMDB9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Decoded payload:

{
  "userId": "1001",
  "role": "user",
  "exp": 1700000000
}

The server signs the token with a secret key. When the client sends the token back, the server verifies the signature — if valid, it trusts the claims without a database lookup. This makes JWTs stateless: the server doesn't need to store session data.

Critical JWT security rules:
- Always validate the exp (expiration) claim — reject expired tokens
- Use strong signing algorithms: RS256 (asymmetric) for production, never none
- Keep access token lifetimes short (15 minutes); use refresh tokens for longer sessions
- Never store JWTs in localStorage — use httpOnly cookies or secure memory to prevent XSS theft

This is one of 18 chapters

Every chapter is free — Kubernetes, Terraform, SRE, distributed systems, and more — with fast daily review built in.

Sign up free