1.1.1 Authentication
Authentication answers one question:
lightbulbWho are you?
The API does not yet decide what you may do. That is authorization. First it must attach the request to an identity: a user, a service, or an anonymous client.
You will see this next to rate limiting. Rate limiting caps how often someone can call you. Authentication says who that someone is. You usually do both: identify the caller, then apply a limit on that identity.
Common ways to authenticate
JWT
OAuth
Session
API key
Session
The server stores “user 42 is logged in” and gives the browser a cookie. Each request sends the cookie. The server looks up the session.
- Simple to revoke: delete the session row
- Needs a shared store (Redis or the database) if you have more than one app instance
- Natural fit for server-rendered sites
API key
A long random string the client sends in a header, for example Authorization: Bearer sk_live_... or X-API-Key.
- Good for server-to-server and partner integrations
- Hash the key at rest; show the plaintext only once
- Treat a leaked key like a password — rotate it
JWT
A signed JSON token. The API verifies the signature and reads sub, exp, and roles from the payload without a session lookup.
- Scales horizontally
- Harder to revoke until expiry — keep access tokens short
- Full walkthrough: JWT and OAuth
OAuth
The user grants your app limited access through another provider (“Sign in with Google”) or a consent screen. You receive tokens. You do not store the user’s Google password.
- Standard for delegated access and social login
- Combine with JWT or opaque tokens on your API
- Details: JWT and OAuth
Authorization
Authorization answers:
lightbulbWhat are you allowed to do?
Example:
Admin → can delete users
Teacher → cannot delete users
Authenticate first, then check roles or permissions. A valid login is not permission to delete the database.
How it is used
- Require HTTPS. Tokens on plain HTTP are stolen credentials.
- Prefer header-based credentials for APIs (
Authorization), not tokens in query strings. - After you know the identity, apply rate limiting per user or API key — not only per IP.
- Never log raw passwords, cookies, or access tokens.