Choosing an API authentication method affects security, user experience, operations, and future migrations. This guide compares API keys, OAuth 2.0, and JWT-based designs, then provides scenario checklists and request examples you can use when designing or reviewing an API.
Overview
API keys, OAuth 2.0, and JWT are often discussed as competing options, but they solve different problems. An API key is a credential that identifies an application or integration. OAuth 2.0 is an authorization framework for obtaining limited access on behalf of a user or service. A JWT is a token format: it can carry claims such as an issuer, subject, audience, and expiration, but using JWT does not automatically provide a complete authentication architecture.
The right choice depends on who is calling the API, whether access is delegated, how quickly credentials must be revoked, and whether the server needs centralized control over sessions. Use the simplest design that satisfies those requirements rather than selecting a token format first.
| Method | Security model | Best use cases | Token handling | Revocation | Implementation complexity | Important risks |
|---|---|---|---|---|---|---|
| API key | Shared secret identifies an application, project, or integration | Simple server-to-server integrations, internal utilities, low-risk public data APIs | Send in a dedicated header; store and rotate as a secret | Usually immediate when the provider disables the key | Low to moderate | Leakage, broad permissions, accidental exposure in browser code or logs |
| OAuth 2.0 | Delegated authorization using access tokens and defined scopes | User-facing applications, third-party integrations, access to protected user resources | Obtain tokens through a supported flow; use short-lived access tokens where practical | Depends on provider, token lifetime, introspection, and refresh-token controls | Moderate to high | Incorrect flow selection, redirect vulnerabilities, excessive scopes, unsafe token storage |
| JWT | Self-contained signed claims are verified by the receiving service | Distributed services, stateless access checks, systems that need portable claims | Validate signature and claims on every request; avoid treating the payload as secret | More difficult before expiration unless using a denylist, key rotation, or an authorization check | Moderate | Weak validation, missing audience checks, long lifetimes, replay, and assuming signing means encryption |
A practical decision tree is:
- Is a user granting an application access to their resources? Use OAuth 2.0, following the provider's supported flow. For interactive browser or mobile applications, the authorization code flow with PKCE is generally the starting point to evaluate.
- Is one trusted backend calling another backend under a service identity? Consider a narrowly scoped API key, OAuth client credentials, or a signed service token. Choose based on the provider's capabilities and your revocation and audit requirements.
- Do multiple services need to verify claims without calling a central session store? A carefully designed JWT may be appropriate, but define expiration, key management, audience validation, and a response to compromise first.
- Is the API public or intended to be called directly from browser JavaScript? Do not place a privileged secret in frontend code. Use a public identifier only for limited purposes, or put privileged operations behind your own backend and enforce user authorization there.
Checklist by scenario
Browser applications
- Use HTTPS for the entire authentication and API path.
- Do not embed a private API key, client secret, or signing key in JavaScript shipped to users.
- For OAuth, confirm the redirect URI exactly and use a flow designed for public clients, such as authorization code with PKCE where supported.
- Decide deliberately where session state lives. If cookies are used, review Secure, HttpOnly, SameSite, domain, path, expiration, and cross-site request requirements.
- Protect state-changing requests against cross-site request forgery when the browser automatically sends credentials.
- Keep authorization checks on the server. A hidden button or frontend route is not an access control boundary.
Mobile applications
- Treat the application package as a public client; do not rely on a bundled secret.
- Use the platform's secure credential storage for refresh tokens or other sensitive session material.
- Register exact redirect mechanisms and verify that another application cannot claim the callback.
- Use short-lived access tokens and provide a controlled refresh and sign-out strategy.
- Plan for lost devices, account recovery, token theft, and application updates.
Server-to-server integrations
- Prefer a credential with the smallest practical scope and a clear owner.
- Store secrets in a managed secret store or protected runtime configuration, not source control.
- Send credentials only over TLS and avoid placing them in query strings.
- Use separate credentials per environment, service, and integration where practical.
- Record authentication failures and authorization decisions without logging the secret or complete token.
- Define rotation, expiration, emergency disablement, and ownership before production launch.
Public APIs
- Clarify whether “public” means publicly readable or merely available to registered developers.
- Use authentication for accountability when appropriate, but do not treat an exposed client-side key as confidential.
- Apply authorization, validation, quotas, rate limits, and abuse monitoring independently of authentication.
- Return consistent error responses without revealing whether internal credentials, users, or resources exist.
- Document required headers, scopes, expiration behavior, and rotation procedures.
Request examples
An API key should normally be sent in a dedicated header rather than a URL:
GET /v1/orders HTTP/1.1
Host: api.example.test
X-API-Key: <api-key>
A bearer access token obtained through OAuth or another token service is commonly sent this way:
GET /v1/profile HTTP/1.1
Host: api.example.test
Authorization: Bearer <access-token>
For a JWT, the receiving service must verify more than its presence. It should validate the signature using an approved algorithm and key, then check relevant claims such as issuer, audience, expiration, not-before time, and subject. A JWT decoder can help inspect a token during development, but decoding is not verification and sensitive production tokens should not be pasted into third-party tools. See the JWT Debugging Guide for a safer inspection workflow.
What to double-check
Before approving an authentication design, walk through these questions:
- Identity: What does the credential identify: a human, an application, a device, or a particular service?
- Authorization: Where are permissions enforced, and are scopes or roles checked for every sensitive operation?
- Audience: Is the credential accepted only by the intended API? This matters especially when several services share signing keys or token infrastructure.
- Lifetime: How long can a stolen credential be used, and what happens when it expires?
- Revocation: Can you disable access promptly after suspected compromise, account closure, or an employee or vendor change?
- Rotation: Can keys be replaced without downtime? Test the overlap period and rollback procedure.
- Storage: Are tokens absent from source code, client bundles, URLs, screenshots, analytics, error messages, and ordinary application logs?
- Transport: Are all credential-bearing requests protected in transit, including redirects, callbacks, internal hops, and development environments?
- Observability: Can operators identify the calling application and investigate failures without collecting unnecessary secret material?
- Failure behavior: Do unauthorized and forbidden responses remain useful to clients without disclosing internal details?
Keep authentication separate from payload correctness. A valid token does not make malformed JSON valid, and a correctly formatted request does not make an unauthorized caller legitimate. When troubleshooting request bodies, the JSON Formatting and Validation Guide can help isolate syntax problems from authentication failures.
Common mistakes
- Calling every JWT an OAuth implementation: OAuth is a framework and JWT is a token representation. A system can use OAuth with opaque tokens, JWTs without OAuth, or neither.
- Putting secrets in frontend code: Anything delivered to a browser or mobile package should be considered obtainable by its user.
- Using a long-lived bearer token for convenience: A stolen bearer token may be usable by whoever possesses it. Shorter lifetimes and controlled renewal reduce exposure, but they do not replace authorization.
- Trusting decoded claims: Base64-decoding a JWT reveals its contents but proves nothing about who issued it. Verification must use an approved trust configuration.
- Skipping audience and issuer checks: A validly signed token intended for one service should not automatically work at another.
- Assuming revocation is automatic: Stateless validation can continue accepting a token until expiration unless the design includes another control.
- Logging complete credentials: Request logs, traces, crash reports, and support exports often have broader access than the application itself.
- Using one credential everywhere: Shared credentials make attribution, rotation, and incident response harder.
When to revisit
Revisit the authentication design before launching a new client, adding a third-party integration, exposing a new sensitive endpoint, changing identity providers, or moving services across trust boundaries. Also review it after a suspected credential leak, a major framework or library change, or a change in compliance and operational requirements.
For a recurring review, confirm that the selected method still matches the scenario: API keys for limited application identification, OAuth 2.0 for delegated access, and JWTs only when their claim model and operational trade-offs are understood. Recheck browser and mobile storage behavior, redirect configuration, signing-key rotation, token lifetimes, scopes, audit coverage, and emergency revocation. Record the date, reviewer, assumptions, and open risks so the next review starts with evidence rather than memory.
Finally, test the failure paths, not only the successful login: expired tokens, wrong audiences, revoked keys, missing scopes, replayed requests, malformed credentials, and unavailable authorization services. Authentication is ready for production when those cases are predictable, observable, and safely denied.