Summary: Every API needs an answer to two questions: who is calling? and what are they allowed to do? API keys, JWTs, and OAuth 2.0 are the three names you will hear most often, but they are not three versions of the same thing. They solve different problems at different layers. This article untangles them, shows how each works, compares them honestly, and gives you a practical framework for choosing and securing them.
Table of Contents
- Why API Authentication Is Hard
- Authentication vs. Authorization
- API Keys
- JSON Web Tokens (JWT)
- OAuth 2.0
- OpenID Connect: The Missing Identity Layer
- Head-to-Head Comparison
- How They Work Together
- Other Approaches Worth Knowing
- Common Vulnerabilities and Mistakes
- Best Practices Checklist
- Choosing the Right Approach
- Conclusion
- Glossary
1. Why API Authentication Is Hard
A website has a human sitting behind a browser. An API has a program on the other end, which might be a mobile app, a server in another company, a script on a laptop, or an attacker running thousands of requests a minute.
APIs are also attractive targets. They expose data and actions directly, often with less friction than a user interface. A single weak endpoint can leak an entire database. Security teams consistently list broken authentication and broken authorization among the most common causes of API breaches.
The difficulty is made worse by confusing vocabulary. Developers often ask, "Should I use OAuth or JWT?" as though they were alternatives. They are not. By the end of this article, that question will make more sense, and you will see why the honest answer is often "both, for different jobs."
2. Authentication vs. Authorization
Two terms must be kept apart:
| Concept | Question it answers | Example |
|---|---|---|
| Authentication (AuthN) | Who are you? | Logging in with a password and a second factor |
| Authorization (AuthZ) | What are you allowed to do? | This user may read invoices but not delete them |
Many authentication problems in APIs are really authorization problems. A system can correctly identify a caller and still let them access another customer's data. This flaw is so common it has its own name: Broken Object Level Authorization (BOLA), consistently at the top of the OWASP API Security list.
Keep this distinction in mind as we look at each technique:
- API keys mostly identify the calling application.
- JWTs are a token format that can carry identity and permission claims.
- OAuth 2.0 is an authorization framework for delegating limited access.
3. API Keys
3.1 What They Are
An API key is a long, random string issued to a developer or application. The client includes it with each request, and the server looks it up.
GET /v1/weather?city=Pokhara HTTP/1.1
Host: api.example.com
X-API-Key: sk_live_9fA3b7c1d2E4f6a8B0c2D4e6F8a0b2C4
You can think of it as a shared password for a program, with no user involved.
3.2 How They Work
- A developer registers on the provider's portal.
- The provider generates a random key and stores a hash of it (like a password).
- The developer places the key in their application.
- On each request, the server hashes the supplied key and looks for a match.
- The server applies rules attached to that key, such as rate limits, plan tier, or allowed endpoints.
3.3 Strengths
- Simple: Easy to implement, easy to explain, easy to test with a single
curlcommand. - Low friction: No login flow or token exchange.
- Good for usage tracking: Per-key analytics, quotas, and billing are straightforward.
- Easy to revoke: Delete one key without affecting others.
3.4 Weaknesses
- They identify applications, not users. If a key is used, you know which app called, but not which person is behind it.
- They are bearer secrets. Anyone who has the key is the client. There is no second factor.
- Long-lived by default. Keys often live for years, increasing the damage window if they leak.
- Frequently leaked. Keys end up in public GitHub repositories, mobile app binaries, browser JavaScript, logs, and screenshots.
- Coarse permissions. Fine-grained, per-user scopes are hard to express.
3.5 When API Keys Make Sense
- Server-to-server integrations where one backend calls another
- Public or semi-public data APIs (weather, maps, currency rates)
- Developer-facing products where usage metering matters
- As a first layer alongside stronger authentication
3.6 When They Don't
- In frontend code. Anything shipped to a browser or mobile app can be extracted. Do not embed powerful keys in client-side code.
- For user-specific data. If the API returns "my account" information, you need user-level authentication.
- For high-risk operations like payments or account changes without additional safeguards.
3.7 Doing API Keys Properly
import secrets, hashlib
def create_api_key():
# 32 bytes of cryptographically secure randomness
raw_key = "sk_live_" + secrets.token_urlsafe(32)
# Store ONLY the hash; show raw_key to the user once
key_hash = hashlib.sha256(raw_key.encode()).hexdigest()
return raw_key, key_hash
Good practice includes:
- Generating keys with a cryptographically secure random source
- Storing only hashed keys (SHA-256 is acceptable for high-entropy random keys)
- Showing the full key only once, at creation
- Adding a recognizable prefix (such as
sk_live_) so secret scanners can detect leaks - Scoping keys to specific permissions, IP ranges, or environments
- Supporting rotation, expiry, and instant revocation
- Always sending keys in a header, never in the URL, since URLs end up in logs and browser history
4. JSON Web Tokens (JWT)
4.1 What They Are
A JSON Web Token (pronounced "jot") is a compact, self-contained, signed token that carries information, called claims, between parties. It is defined by the RFC 7519 standard.
The most important point: a JWT is a format, not a protocol. It tells you how to package and sign data. It does not tell you how to log in, how to obtain a token, or how to delegate access. That is where OAuth 2.0 comes in.
4.2 Anatomy of a JWT
A JWT has three Base64URL-encoded parts separated by dots:
xxxxx.yyyyy.zzzzz
Header.Payload.Signature
Header: states the signing algorithm and token type.
{ "alg": "RS256", "typ": "JWT", "kid": "key-2026-10" }
Payload: carries the claims.
{
"iss": "https://auth.example.com",
"sub": "user_8421",
"aud": "https://api.example.com",
"exp": 1791300000,
"iat": 1791296400,
"scope": "invoices:read profile:read"
}
Signature: created by signing the header and payload with a secret or private key. It lets the receiver verify the token was not altered.
Important: The payload is only encoded, not encrypted. Anyone who holds a JWT can read its contents. Never put passwords, secrets, or sensitive personal data in a standard (signed) JWT.
4.3 Standard Claims
| Claim | Name | Purpose |
|---|---|---|
iss | Issuer | Who created the token |
sub | Subject | Who the token is about (usually a user ID) |
aud | Audience | Which service the token is intended for |
exp | Expiration | When the token stops being valid |
nbf | Not Before | Token invalid before this time |
iat | Issued At | When the token was created |
jti | JWT ID | Unique identifier, useful for revocation and replay prevention |
4.4 Signing Algorithms
- HS256 (HMAC + SHA-256): Symmetric. The same secret signs and verifies. Simple, but every service that verifies tokens must hold the secret, which also lets them forge tokens.
- RS256 (RSA + SHA-256): Asymmetric. The issuer signs with a private key; anyone can verify with the public key. Better for distributed systems.
- ES256 (ECDSA P-256): Asymmetric with smaller keys and signatures.
- EdDSA (Ed25519): Modern, fast, and compact. For systems with multiple services, asymmetric signing is usually preferred, because only the identity provider holds the private key. Verifiers can fetch public keys from a JWKS (JSON Web Key Set) endpoint.
4.5 How a JWT Is Used
GET /v1/invoices HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOi...
The API verifies the token without calling any database:
- Parse the token and check the algorithm is on your allowlist.
- Verify the signature using the correct key.
- Check
exp,nbf,iss, andaud. - Read claims such as
subandscope. - Authorize the request based on those claims.
4.6 Strengths
- Stateless verification: No session lookup needed; scales easily across servers.
- Portable: Works across services, domains, and languages.
- Carries context: Identity and permissions travel with the request.
- Standardized and widely supported.
4.7 Weaknesses
- Hard to revoke. A signed token stays valid until it expires. Revoking one early requires extra machinery such as a denylist, which undermines the "stateless" benefit.
- Bearer tokens. Whoever steals the token can use it.
- Size. JWTs can be large, adding overhead to every request.
- Easy to misconfigure. Many real-world attacks stem from poor validation rather than broken cryptography.
- Stale claims. Permissions embedded at issue time may be outdated by the time the token is used.
- Misused as session storage. Putting too much into tokens or using them for long-lived sessions often creates problems.
4.8 Verifying a JWT Safely
import jwt # PyJWT
def verify_token(token, public_key):
return jwt.decode(
token,
public_key,
algorithms=["RS256"], # explicit allowlist, never trust the header
audience="https://api.example.com",
issuer="https://auth.example.com",
options={"require": ["exp", "iss", "aud", "sub"]},
)
Never accept whichever algorithm the token header claims. Fixing the allowed algorithms server-side is essential.
4.9 Access Tokens and Refresh Tokens
A secure pattern uses two tokens:
- Access token: Short-lived (for example, 5 to 15 minutes). Sent on every API call.
- Refresh token: Longer-lived. Used only to obtain new access tokens from the authorization server, and stored more carefully. This limits the damage from a stolen access token while avoiding constant re-login. Good systems use refresh token rotation, where each refresh issues a new refresh token and invalidates the old one, so reuse of a stolen token can be detected.
5. OAuth 2.0
5.1 The Problem OAuth Solves
Imagine you want a photo-printing app to access your pictures stored on a cloud service. In the bad old days, you would hand the printing app your cloud username and password. That meant the app could do anything with your account, and revoking its access meant changing your password for everything.
OAuth 2.0 (RFC 6749) solves this with delegated authorization: you grant the app limited access to specific resources, for a limited time, without sharing your password.
OAuth 2.0 is about authorization, not authentication. It answers "what may this app do on my behalf?" rather than "who is this user?"
5.2 The Four Roles
| Role | Description | Example |
|---|---|---|
| Resource Owner | The user who owns the data | You |
| Client | The app requesting access | The photo-printing app |
| Authorization Server | Authenticates the user and issues tokens | The cloud provider's login server |
| Resource Server | The API that holds the data | The photo storage API |
5.3 Key Concepts
- Scopes: Named permissions, such as
photos:readorcalendar:write, that limit what a token can do. - Access token: The credential the client presents to the API.
- Refresh token: Used to get new access tokens without re-prompting the user.
- Redirect URI: Where the authorization server sends the user back after consent. It must be strictly validated.
- Client types:
- Confidential clients can keep a secret (server-side apps).
- Public clients cannot (single-page apps, mobile apps, desktop apps).
5.4 The Main Grant Types (Flows)
Authorization Code Flow with PKCE (recommended for most apps)
The user is redirected to the authorization server, logs in, consents, and is sent back with a short-lived authorization code. The client exchanges that code for tokens. PKCE (Proof Key for Code Exchange) adds a one-time secret that prevents stolen authorization codes from being redeemed by attackers.
User/Browser Client App Auth Server API
| | | |
|-- Click "Login" ->| | |
| |-- code_challenge ->| |
|<------------ Redirect to login/consent ---------------|
|-- Log in & approve ------------------->| |
|<-- Redirect back with authorization code --------------|
|-- code ---------->| | |
| |-- code + code_verifier ----------->|
| |<-- access_token (+ refresh) -------|
| |-- Bearer access_token ------------>|
| |<-- protected data -----------------|
Client Credentials Flow
For machine-to-machine communication with no user involved. The client authenticates with its own credentials and receives a token for its own account.
POST /oauth/token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
&client_id=billing-service
&client_secret=********
&scope=invoices:read
Device Authorization Flow
For input-constrained devices such as smart TVs. The device shows a code; the user approves it on a phone or computer.
Refresh Token Flow
Exchanges a refresh token for a new access token.
Deprecated flows to avoid:
- Implicit flow: Returned tokens directly in the URL fragment. Insecure and no longer recommended.
- Resource Owner Password Credentials flow: The app collects the user's password directly, defeating OAuth's whole purpose. The OAuth 2.1 effort consolidates best practices: it requires PKCE for the code flow and removes the implicit and password flows.
5.5 Strengths
- Delegated, scoped access: Users grant only what is needed.
- No password sharing: Third-party apps never see credentials.
- Revocable: Users or administrators can cut off one app without affecting others.
- Industry standard: Broad ecosystem, tooling, and provider support.
- Flexible: Supports web apps, mobile apps, servers, and devices.
5.6 Weaknesses
- Complex: Multiple flows, parameters, and roles make it easy to implement incorrectly.
- Not an authentication protocol on its own. Using OAuth alone to log users in has led to real vulnerabilities (see OpenID Connect below).
- Depends on correct configuration: Redirect URI validation, state handling, and scope design all matter.
- Overkill for simple cases. A small internal API may not need a full authorization server.
5.7 Token Formats in OAuth
OAuth 2.0 does not specify what an access token looks like. Two common approaches:
- Opaque tokens: Random strings with no readable content. The API validates them by asking the authorization server (token introspection, RFC 7662). Easy to revoke, but requires a network call.
- JWT access tokens: Self-contained and verifiable locally (RFC 9068 defines a profile). Fast, but harder to revoke. This is exactly where OAuth and JWT meet: OAuth is the process; a JWT is one possible packaging of the token it produces.
6. OpenID Connect: The Missing Identity Layer
Since OAuth 2.0 does not tell the client who the user is, OpenID Connect (OIDC) was built on top of it to add standardized authentication.
OIDC adds:
- An ID token, which is always a JWT, containing claims about the authenticated user (
sub,name,email,auth_time, and more). - A standard UserInfo endpoint for retrieving profile data.
- Standard scopes such as
openid,profile, andemail. - A discovery document (
/.well-known/openid-configuration) that describes the provider's endpoints and keys. A simple rule to remember:
| Token | Meant for | Question answered |
|---|---|---|
| ID token | The client application | Who just logged in? |
| Access token | The API (resource server) | What may the caller do? |
A common mistake is sending an ID token to an API as though it were an access token. They have different audiences and purposes.
7. Head-to-Head Comparison
| Feature | API Keys | JWT | OAuth 2.0 |
|---|---|---|---|
| What it is | A shared secret string | A signed token format | An authorization framework |
| Primary purpose | Identify an application | Carry verifiable claims | Delegate limited access |
| Identifies users? | No (apps only) | Yes, if issued for a user | Yes, via tokens and OIDC |
| Granular permissions | Limited | Yes, through claims | Yes, through scopes |
| Expiry built in | Usually no | Yes (exp) | Yes (token lifetimes) |
| Easy revocation | Yes | Difficult | Yes (especially with opaque tokens) |
| Stateless | No (lookup needed) | Yes | Depends on token type |
| Implementation effort | Low | Medium | High |
| Third-party delegation | No | Not by itself | Yes, its core purpose |
| Typical risk | Leaked or hard-coded keys | Weak validation, theft | Misconfigured flows |
| Best for | Simple server-to-server, metering | Stateless service-to-service auth | User-delegated or multi-party access |
The key insight is that these are not competing options on the same axis:
- API keys are a credential type.
- JWT is a token format.
- OAuth 2.0 is a protocol for obtaining tokens.
8. How They Work Together
Real systems layer these tools. Here are common patterns.
Pattern A: Public Data API
API key only. The provider wants to track and rate-limit developers. No private user data is involved.
Pattern B: Internal Microservices
OAuth 2.0 Client Credentials flow issuing short-lived JWT access tokens. Each service authenticates to the authorization server, receives a token with limited scopes, and presents it to other services, which verify the signature locally.
Pattern C: User-Facing Application with Third-Party Access
OAuth 2.0 Authorization Code + PKCE, with OIDC for login, and JWT or opaque access tokens for API calls. Users sign in once, grant scoped permissions, and can revoke them later.
Pattern D: SaaS Platform with Developer Integrations
API keys for developer onboarding and simple integrations, plus OAuth 2.0 for apps that act on behalf of end users. This is how many large platforms operate.
Pattern E: Sensitive Operations
Any of the above plus additional protections: mutual TLS, request signing, step-up authentication, IP allowlists, and strict rate limits.
9. Other Approaches Worth Knowing
- HTTP Basic Authentication: Sends a username and password (Base64-encoded, not encrypted) on every request. Acceptable only over HTTPS and for simple cases; generally discouraged for modern APIs.
- Session cookies: Common for browser-based apps with a same-origin backend. Cookie flags (
HttpOnly,Secure,SameSite) and CSRF protection matter. - Mutual TLS (mTLS): Both client and server present certificates. Very strong for service-to-service communication in high-security environments.
- HMAC request signing: The client signs each request with a secret, as in AWS Signature V4. Protects against tampering and replay, since the secret itself never travels.
- Proof-of-possession tokens (DPoP, mTLS-bound tokens): Bind a token to a client key so that a stolen token cannot be used by someone else. This directly addresses the "bearer token" weakness.
- Passkeys (WebAuthn/FIDO2): Phishing-resistant user authentication, typically used at the login step that precedes token issuance.
10. Common Vulnerabilities and Mistakes
10.1 API Key Mistakes
- Committing keys to source control. Bots scan public repositories within minutes.
- Embedding keys in mobile or web clients.
- Sending keys in query strings, which end up in logs and referrer headers.
- Never rotating keys or having no way to do so.
- One all-powerful key instead of scoped, per-environment keys.
10.2 JWT Mistakes
- Accepting
alg: none. Some early libraries treated unsigned tokens as valid. - Algorithm confusion. An attacker changes
RS256toHS256and signs the token using the public key as the HMAC secret. Libraries that trust the header are vulnerable. Always enforce an algorithm allowlist. - Not validating
audandiss. A token meant for service A gets accepted by service B. - Skipping expiry checks or issuing very long-lived tokens.
- Storing sensitive data in the payload, forgetting it is readable.
- Weak HMAC secrets that can be brute-forced offline.
- Storing tokens in
localStorage, where any cross-site scripting (XSS) bug can steal them. PreferHttpOnly,Secure,SameSitecookies or a backend-for-frontend pattern for browser apps. - Trusting the
kidheader blindly, which can lead to injection or key-confusion attacks.
10.3 OAuth 2.0 Mistakes
- Loose redirect URI validation, allowing attackers to capture authorization codes. Use exact-match registration.
- Missing or unchecked
stateparameter, enabling CSRF on the login flow. - Skipping PKCE on public clients.
- Using the implicit or password grant.
- Over-broad scopes granted by default.
- Treating OAuth as login, without OIDC or correct ID token validation.
- Leaking tokens in URLs, logs, or analytics.
- Not rotating refresh tokens or storing them insecurely.
- Consent phishing: Malicious apps trick users into granting broad scopes. Providers should review and restrict risky scope requests.
10.4 Authorization Mistakes (Regardless of Method)
- BOLA/IDOR: Checking that a user is logged in but not that they own the resource requested. Always verify authorization on every object access.
- Broken function-level authorization: Admin endpoints reachable by ordinary users.
- Excessive data exposure: Returning entire objects and relying on the client to hide fields.
- No rate limiting, enabling credential stuffing and enumeration.
- Trusting client-supplied roles or IDs in request bodies.
Remember: the strongest authentication scheme is worthless if authorization checks are missing.
11. Best Practices Checklist
Transport
- HTTPS everywhere, with modern TLS
- HSTS enabled on browser-facing endpoints
- Credentials sent in headers, never in URLs Credentials and tokens
- Access tokens are short-lived (minutes, not days)
- Refresh tokens are rotated and bound to a client
- Secrets and API keys generated with a CSPRNG
- Only hashes of API keys stored server-side
- Key prefixes used to enable secret scanning
- Rotation and revocation are tested, not just designed JWT validation
- Algorithm allowlist enforced server-side
-
exp,nbf,iss,audverified every time - Asymmetric signing for multi-service systems
- Keys published via JWKS and rotated regularly
- No sensitive data in payloads OAuth 2.0
- Authorization Code flow with PKCE for user-facing clients
- Exact redirect URI matching
-
state(andnoncefor OIDC) validated - Least-privilege scopes
- No implicit or password grants Authorization and defense in depth
- Object-level authorization checked on every request
- Rate limiting and anomaly detection in place
- Audit logging of authentication and authorization events
- Secrets stored in a vault, not in code or config files
- Monitoring and alerts for suspicious token use
12. Choosing the Right Approach
Use this decision guide as a starting point.
Question 1: Does the API need to know which user is acting?
- No, just which application: an API key (possibly with extra controls) may be enough.
- Yes: move to token-based authentication, usually OAuth 2.0 with OIDC. Question 2: Will third-party applications access user data?
- Yes: use OAuth 2.0. This is the scenario it was designed for.
- No, first-party only: a simpler session or token system might suffice, but OAuth/OIDC still brings standardization benefits. Question 3: Is this service-to-service traffic?
- Low sensitivity: API keys with strict scoping.
- Higher sensitivity or many services: OAuth 2.0 Client Credentials with short-lived tokens, or mTLS. Question 4: Do you need fast, distributed verification without a central lookup?
- Yes: signed JWT access tokens, with short lifetimes to offset the revocation problem.
- Need instant revocation: opaque tokens with introspection, or JWTs plus a denylist for high-risk cases. Question 5: How sensitive is the data and what is the threat model?
- High: add proof-of-possession tokens, mTLS, request signing, and step-up authentication.
Quick Recommendations
| Scenario | Suggested Approach |
|---|---|
| Public weather or maps API | API keys with rate limiting |
| Mobile app logging users in | OAuth 2.0 Authorization Code + PKCE with OIDC |
| Single-page app | Backend-for-frontend with secure cookies, or Code + PKCE |
| Internal microservices | OAuth Client Credentials with short-lived JWTs, or mTLS |
| Third-party integrations with user data | OAuth 2.0 with narrowly scoped permissions |
| Webhooks | HMAC signature verification |
| Banking or healthcare APIs | OAuth 2.0 (such as FAPI profiles), mTLS, and sender-constrained tokens |
13. Conclusion
The question "OAuth 2.0, JWT, or API keys?" is a little like asking "Should I use a passport, a laminated card, or border control?" They live at different layers:
- API keys are simple application credentials: fast to adopt, but blunt and risky if leaked.
- JWTs are a portable, signed way to carry claims: efficient and stateless, but easy to misuse and hard to revoke.
- OAuth 2.0 is the framework for granting limited, revocable access without sharing passwords, and it often uses JWTs as its tokens. The most secure systems are rarely built from a single mechanism. They combine short-lived tokens, least-privilege scopes, strong validation, careful key management, and rigorous authorization checks on every request.
Four takeaways to carry forward:
- Match the tool to the problem. Identify applications with keys, delegate access with OAuth, and package claims with JWTs when you need them.
- Keep tokens short-lived and narrowly scoped to limit the cost of theft.
- Validate everything: algorithm, signature, issuer, audience, expiry, redirect URI, and ownership of the requested object.
- Never confuse authentication with authorization. Knowing who is calling is only half the job.
14. Glossary
| Term | Definition |
|---|---|
| Access token | A credential presented to an API to access protected resources |
| API key | A secret string identifying an application to an API |
| Authorization server | The server that authenticates users and issues OAuth tokens |
| Bearer token | A token that grants access to whoever holds ("bears") it |
| BOLA / IDOR | Broken Object Level Authorization / Insecure Direct Object Reference |
| Claim | A statement about a subject inside a token (for example, sub, exp) |
| Client | The application requesting access in OAuth |
| ID token | An OIDC JWT proving a user's authentication to the client |
| Introspection | Asking the authorization server whether a token is valid |
| JWKS | JSON Web Key Set; a published set of public keys for verifying tokens |
| JWT | JSON Web Token; a compact, signed token format |
| mTLS | Mutual TLS; both parties authenticate with certificates |
| OAuth 2.0 | A framework for delegated authorization |
| OIDC | OpenID Connect; an identity layer on top of OAuth 2.0 |
| Opaque token | A random token with no readable content |
| PKCE | Proof Key for Code Exchange; protects the authorization code flow |
| Refresh token | A long-lived credential used to obtain new access tokens |
| Resource server | The API that hosts protected resources |
| Scope | A named permission limiting what a token may do |