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

  1. Why API Authentication Is Hard
  2. Authentication vs. Authorization
  3. API Keys
  4. JSON Web Tokens (JWT)
  5. OAuth 2.0
  6. OpenID Connect: The Missing Identity Layer
  7. Head-to-Head Comparison
  8. How They Work Together
  9. Other Approaches Worth Knowing
  10. Common Vulnerabilities and Mistakes
  11. Best Practices Checklist
  12. Choosing the Right Approach
  13. Conclusion
  14. 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:

ConceptQuestion it answersExample
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.

HTTP
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

  1. A developer registers on the provider's portal.
  2. The provider generates a random key and stores a hash of it (like a password).
  3. The developer places the key in their application.
  4. On each request, the server hashes the supplied key and looks for a match.
  5. 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 curl command.
  • 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

PYTHON
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:

PLAINTEXT
xxxxx.yyyyy.zzzzz
Header.Payload.Signature

Header: states the signing algorithm and token type.

JSON
{ "alg": "RS256", "typ": "JWT", "kid": "key-2026-10" }

Payload: carries the claims.

JSON
{
  "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

ClaimNamePurpose
issIssuerWho created the token
subSubjectWho the token is about (usually a user ID)
audAudienceWhich service the token is intended for
expExpirationWhen the token stops being valid
nbfNot BeforeToken invalid before this time
iatIssued AtWhen the token was created
jtiJWT IDUnique 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

HTTP
GET /v1/invoices HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOi...

The API verifies the token without calling any database:

  1. Parse the token and check the algorithm is on your allowlist.
  2. Verify the signature using the correct key.
  3. Check exp, nbf, iss, and aud.
  4. Read claims such as sub and scope.
  5. 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

PYTHON
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

RoleDescriptionExample
Resource OwnerThe user who owns the dataYou
ClientThe app requesting accessThe photo-printing app
Authorization ServerAuthenticates the user and issues tokensThe cloud provider's login server
Resource ServerThe API that holds the dataThe photo storage API

5.3 Key Concepts

  • Scopes: Named permissions, such as photos:read or calendar: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.

PLAINTEXT
 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.

HTTP
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, and email.
  • A discovery document (/.well-known/openid-configuration) that describes the provider's endpoints and keys. A simple rule to remember:
TokenMeant forQuestion answered
ID tokenThe client applicationWho just logged in?
Access tokenThe 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

FeatureAPI KeysJWTOAuth 2.0
What it isA shared secret stringA signed token formatAn authorization framework
Primary purposeIdentify an applicationCarry verifiable claimsDelegate limited access
Identifies users?No (apps only)Yes, if issued for a userYes, via tokens and OIDC
Granular permissionsLimitedYes, through claimsYes, through scopes
Expiry built inUsually noYes (exp)Yes (token lifetimes)
Easy revocationYesDifficultYes (especially with opaque tokens)
StatelessNo (lookup needed)YesDepends on token type
Implementation effortLowMediumHigh
Third-party delegationNoNot by itselfYes, its core purpose
Typical riskLeaked or hard-coded keysWeak validation, theftMisconfigured flows
Best forSimple server-to-server, meteringStateless service-to-service authUser-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

  1. Committing keys to source control. Bots scan public repositories within minutes.
  2. Embedding keys in mobile or web clients.
  3. Sending keys in query strings, which end up in logs and referrer headers.
  4. Never rotating keys or having no way to do so.
  5. One all-powerful key instead of scoped, per-environment keys.

10.2 JWT Mistakes

  1. Accepting alg: none. Some early libraries treated unsigned tokens as valid.
  2. Algorithm confusion. An attacker changes RS256 to HS256 and signs the token using the public key as the HMAC secret. Libraries that trust the header are vulnerable. Always enforce an algorithm allowlist.
  3. Not validating aud and iss. A token meant for service A gets accepted by service B.
  4. Skipping expiry checks or issuing very long-lived tokens.
  5. Storing sensitive data in the payload, forgetting it is readable.
  6. Weak HMAC secrets that can be brute-forced offline.
  7. Storing tokens in localStorage, where any cross-site scripting (XSS) bug can steal them. Prefer HttpOnly, Secure, SameSite cookies or a backend-for-frontend pattern for browser apps.
  8. Trusting the kid header blindly, which can lead to injection or key-confusion attacks.

10.3 OAuth 2.0 Mistakes

  1. Loose redirect URI validation, allowing attackers to capture authorization codes. Use exact-match registration.
  2. Missing or unchecked state parameter, enabling CSRF on the login flow.
  3. Skipping PKCE on public clients.
  4. Using the implicit or password grant.
  5. Over-broad scopes granted by default.
  6. Treating OAuth as login, without OIDC or correct ID token validation.
  7. Leaking tokens in URLs, logs, or analytics.
  8. Not rotating refresh tokens or storing them insecurely.
  9. 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)

  1. BOLA/IDOR: Checking that a user is logged in but not that they own the resource requested. Always verify authorization on every object access.
  2. Broken function-level authorization: Admin endpoints reachable by ordinary users.
  3. Excessive data exposure: Returning entire objects and relying on the client to hide fields.
  4. No rate limiting, enabling credential stuffing and enumeration.
  5. 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, aud verified 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 (and nonce for 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

ScenarioSuggested Approach
Public weather or maps APIAPI keys with rate limiting
Mobile app logging users inOAuth 2.0 Authorization Code + PKCE with OIDC
Single-page appBackend-for-frontend with secure cookies, or Code + PKCE
Internal microservicesOAuth Client Credentials with short-lived JWTs, or mTLS
Third-party integrations with user dataOAuth 2.0 with narrowly scoped permissions
WebhooksHMAC signature verification
Banking or healthcare APIsOAuth 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:

  1. Match the tool to the problem. Identify applications with keys, delegate access with OAuth, and package claims with JWTs when you need them.
  2. Keep tokens short-lived and narrowly scoped to limit the cost of theft.
  3. Validate everything: algorithm, signature, issuer, audience, expiry, redirect URI, and ownership of the requested object.
  4. Never confuse authentication with authorization. Knowing who is calling is only half the job.

14. Glossary

TermDefinition
Access tokenA credential presented to an API to access protected resources
API keyA secret string identifying an application to an API
Authorization serverThe server that authenticates users and issues OAuth tokens
Bearer tokenA token that grants access to whoever holds ("bears") it
BOLA / IDORBroken Object Level Authorization / Insecure Direct Object Reference
ClaimA statement about a subject inside a token (for example, sub, exp)
ClientThe application requesting access in OAuth
ID tokenAn OIDC JWT proving a user's authentication to the client
IntrospectionAsking the authorization server whether a token is valid
JWKSJSON Web Key Set; a published set of public keys for verifying tokens
JWTJSON Web Token; a compact, signed token format
mTLSMutual TLS; both parties authenticate with certificates
OAuth 2.0A framework for delegated authorization
OIDCOpenID Connect; an identity layer on top of OAuth 2.0
Opaque tokenA random token with no readable content
PKCEProof Key for Code Exchange; protects the authorization code flow
Refresh tokenA long-lived credential used to obtain new access tokens
Resource serverThe API that hosts protected resources
ScopeA named permission limiting what a token may do