Browse cheat sheets · APIs

Technology: APIsCategory: SecurityDifficulty: IntermediateUpdated

API Authentication Patterns

Choose and implement API authentication safely by understanding API keys, Basic auth, Bearer tokens, OAuth 2.0, JWTs, service identities, mTLS, token lifetimes, and common production failure modes.

On this page
  1. Problem
  2. Quick answer
  3. Code / commands
  4. 1. API key in a request header
  5. 2. Prefer headers over query-string API keys
  6. 3. Basic authentication
  7. 4. Do not embed Basic credentials in URLs
  8. 5. Bearer access token
  9. 6. Do not log Bearer tokens
  10. 7. OAuth 2.0 client credentials
  11. 8. Prefer workload identity over stored client secrets when available
  12. 9. OAuth authorization code flow
  13. 10. PKCE protects authorization-code flows for public clients
  14. 11. Refresh token pattern
  15. 12. Rotate refresh tokens when the provider supports it
  16. 13. JWT Bearer token example
  17. 14. Decode JWT metadata without treating it as validated
  18. 15. Validate JWT signature
  19. 16. Validate issuer
  20. 17. Validate audience
  21. 18. Validate token expiry
  22. 19. Validate nbf
  23. 20. Validate authorization after authentication
  24. 21. Scope-based authorization
  25. 22. Role-based authorization
  26. 23. Resource-level authorization
  27. 24. Tenant isolation belongs in authorization logic
  28. 25. Service-to-service token example
  29. 26. Do not request broader scopes than required
  30. 27. Short-lived access tokens are preferable
  31. 28. Cache access tokens responsibly
  32. 29. Refresh before expiry with a safety margin
  33. 30. Prevent token-refresh stampedes
  34. 31. mTLS client authentication
  35. 32. mTLS can coexist with application-layer tokens
  36. 33. Protect private keys
  37. 34. HMAC request signing
  38. 35. Signed-request replay protection
  39. 36. API gateway authentication
  40. 37. Backend should know which identity is trusted
  41. 38. Do not trust identity headers from arbitrary clients
  42. 39. Use 401 vs 403 correctly
  43. 40. Return WWW-Authenticate where appropriate
  44. 41. Do not return sensitive authentication details
  45. 42. Keep authentication errors observable server-side
  46. 43. Use correlation IDs
  47. 44. Test an expired token deliberately in non-production
  48. 45. Test wrong-audience tokens
  49. 46. Test wrong-tenant access
  50. 47. Do not use authentication as a substitute for authorization
  51. 48. Prefer standards over custom authentication
  52. 49. OpenID Connect is for identity on top of OAuth 2.0
  53. 50. Access token vs ID token
  54. 51. Do not use a refresh token as an API token
  55. 52. Token introspection
  56. 53. JWT validation is usually local
  57. 54. Cache signing keys carefully
  58. 55. Reject unexpected signing algorithms
  59. 56. Never accept unsigned JWTs
  60. 57. Store secrets outside source control
  61. 58. Rotate credentials
  62. 59. Support overlapping rotation where possible
  63. 60. Avoid one shared credential across many clients
  64. 61. Rate-limit by stable identity
  65. 62. Authentication data should not be used as arbitrary business input
  66. 63. Treat token claims as security input
  67. 64. Avoid accepting tokens from multiple issuers accidentally
  68. 65. Use HTTPS everywhere for credential-bearing requests
  69. 66. Be careful with redirects and Authorization headers
  70. 67. Do not put tokens in frontend source code
  71. 68. Backend-for-frontend pattern
  72. 69. Cookie-based API sessions need CSRF protection
  73. 70. Cookies need secure attributes
  74. 71. Authentication and CORS are different
  75. 72. Authentication and encryption are different
  76. 73. Authentication and request signing are different
  77. 74. Authentication failures should fail closed
  78. 75. Avoid custom fallback credentials
  79. 76. Use health checks carefully
  80. 77. Document the API authentication contract
  81. 78. Build a troubleshooting matrix
  82. What the result means
  83. What to look for
  84. 401 Unauthorized
  85. 403 Forbidden
  86. Works until approximately token expiry
  87. Works locally but fails in the deployed service
  88. Valid JWT is rejected
  89. Valid token accesses another tenant’s data
  90. Production notes
  91. Authentication secrets are production credentials
  92. Prefer short-lived credentials
  93. Authentication libraries are security dependencies
  94. Authorization belongs close to the protected resource
  95. Multi-tenant APIs need explicit tenant checks
  96. Credential rotation should be tested before an incident
  97. Common mistakes
  98. 1. Treating JWT decoding as validation
  99. 2. Sending an ID token to an API
  100. 3. Logging raw tokens
  101. 4. Sharing one API key across many clients
  102. 5. Putting secrets in query strings
  103. 6. Using long-lived Bearer tokens because refresh is inconvenient
  104. 7. Validating authentication but not tenant/resource access
  105. 8. Accepting any JWT signed by a known provider
  106. 9. Storing client secrets in frontend code
  107. 10. Building custom authentication instead of using established standards
  108. Next step
  109. Related deep dives

Problem

An API needs to know who or what is calling it before allowing access.

The difficult part is not adding an Authorization header. The real engineering questions are:

  • Is the caller a user, service, script, device, or partner?
  • Does the API need authentication only, or also delegated authorization?
  • How long should credentials live?
  • How are credentials rotated or revoked?
  • Where are secrets stored?
  • Is the caller inside a trusted platform or crossing organizational boundaries?
  • Does the API need strong client identity such as mTLS?
  • Are tokens validated locally or through an authorization server?

The goal is to choose the simplest authentication pattern that matches the trust model without creating long-lived secrets or fragile custom security.

Quick answer

Use this decision model:

Simple server-to-server integration with low complexity
→ API key, if the platform supports it securely

Legacy/simple HTTP authentication
→ Basic auth over TLS only

User or service token presented to an API
→ Bearer access token

User delegates access to an application
→ OAuth 2.0 authorization flow

Service-to-service without a user
→ OAuth 2.0 client credentials or platform-managed workload identity

Need cryptographically strong client identity at the TLS layer
→ mTLS

JWT
→ token format, not an authentication protocol by itself

Typical Bearer token request:

curl \
  --header "Authorization: Bearer $ACCESS_TOKEN" \
  "https://api.example.com/v1/reports"

Do not invent your own token format or send long-lived secrets in query strings.

Code / commands

1. API key in a request header

curl \
  --header "X-API-Key: $API_KEY" \
  "https://api.example.com/v1/data"

Use when the API intentionally supports API-key authentication.

Good fit:

  • internal service integrations
  • simple partner integrations
  • low-complexity machine access

Limitations:

  • usually represents the application, not an end user
  • often long-lived
  • revocation/rotation must be managed explicitly
  • coarse-grained unless combined with server-side policy

2. Prefer headers over query-string API keys

Avoid:

curl \
  "https://api.example.com/v1/data?api_key=$API_KEY"

Query-string secrets can leak into:

  • access logs
  • browser history
  • monitoring tools
  • reverse proxies
  • referrer data

Use an authentication header whenever the API supports one.


3. Basic authentication

curl \
  --user "$API_USER:$API_PASSWORD" \
  "https://api.example.com/v1/admin"

This sends credentials using HTTP Basic authentication.

Use only over HTTPS.

Basic authentication does not encrypt credentials by itself; TLS provides the transport protection.


4. Do not embed Basic credentials in URLs

Avoid:

https://user:password@api.example.com

Credentials can leak through logs, history, tooling, or diagnostics.

Use the HTTP authorization mechanism instead.


5. Bearer access token

curl \
  --header "Authorization: Bearer $ACCESS_TOKEN" \
  "https://api.example.com/v1/reports"

A Bearer token means:

whoever possesses the token can use it

Protect it like a password.


6. Do not log Bearer tokens

Bad:

print(headers)

if headers contains:

Authorization: Bearer ...

Instead log safe metadata:

token present: yes
token issuer: expected issuer
token audience: expected API
token expiry: 2026-10-04T22:00:00Z

Do not log the token itself.


7. OAuth 2.0 client credentials

Use for machine-to-machine calls without a user.

Token request pattern:

curl \
  --request POST \
  --url "https://auth.example.com/oauth2/token" \
  --header "Content-Type: application/x-www-form-urlencoded" \
  --data-urlencode "grant_type=client_credentials" \
  --data-urlencode "client_id=$CLIENT_ID" \
  --data-urlencode "client_secret=$CLIENT_SECRET" \
  --data-urlencode "scope=reports.read"

Typical response:

{
  "access_token": "...",
  "token_type": "Bearer",
  "expires_in": 3600
}

Then call the API with the returned access token.


8. Prefer workload identity over stored client secrets when available

In cloud environments, a managed/workload identity can often obtain tokens without storing a static client secret.

Conceptually:

workload identity
→ authorization server / cloud identity platform
→ short-lived access token
→ API

Prefer this over distributing long-lived secrets across applications.


9. OAuth authorization code flow

Use when an application needs access on behalf of a user.

Conceptually:

User
→ authorization server login/consent
→ authorization code
→ application exchanges code
→ access token
→ API

Modern public clients should use PKCE.

Do not expose the authorization code exchange secret to browser/mobile code when the client cannot protect a secret.


10. PKCE protects authorization-code flows for public clients

PKCE uses:

code_verifier
code_challenge

to bind the authorization request to the client that later redeems the code.

Use the authorization server’s supported SDK/library instead of implementing PKCE manually unless necessary.


11. Refresh token pattern

Typical lifecycle:

access token
→ short-lived

refresh token
→ longer-lived credential used to obtain new access tokens

Refresh tokens should normally stay with the trusted application/backend that owns the session.

Do not expose them broadly to downstream services.


12. Rotate refresh tokens when the provider supports it

Refresh-token rotation can reduce replay risk.

A rotated token is replaced with a new one during refresh.

If an old token is reused, the provider may be able to detect suspicious replay.

Implementation behavior is provider-specific.


13. JWT Bearer token example

A JWT often looks like:

xxxxx.yyyyy.zzzzz

with three Base64URL-encoded sections:

header.payload.signature

Common claims include:

iss
sub
aud
exp
nbf
iat
scope
roles

A JWT is a token format.

It is not automatically trustworthy because it can be decoded.


14. Decode JWT metadata without treating it as validated

You may decode a JWT payload for troubleshooting, but:

decode
!=
validate

Validation must check the signature and required claims.

Do not authorize requests based only on decoded token content.


15. Validate JWT signature

Server-side validation should use trusted keys from the identity provider.

Typical validation checks:

signature
issuer
audience
expiration
not-before
allowed signing algorithm
required scopes/roles

Use a maintained security library.

Do not implement JWT cryptography manually.


16. Validate issuer

Conceptually:

iss == expected authorization server

Reject tokens from unexpected issuers.

Do not accept any correctly signed token unless it comes from a trusted issuer.


17. Validate audience

Conceptually:

aud contains this API

A token intended for another API should not be accepted.

Audience validation prevents token reuse across unrelated services.


18. Validate token expiry

Check:

exp

and reject expired tokens.

Small clock-skew allowances may be appropriate, but they should be deliberate and limited.


19. Validate nbf

If the token contains:

nbf

do not accept it before that time.

This protects against early use of future-valid tokens.


20. Validate authorization after authentication

Authentication answers:

Who is calling?

Authorization answers:

What is that caller allowed to do?

Example:

authenticated user
+
scope: reports.read
→ GET /reports allowed

same user
without reports.write
→ POST /reports denied

Do not stop at token validation.


21. Scope-based authorization

Example token scope:

reports.read reports.write

Server logic:

GET /reports
→ require reports.read

POST /reports
→ require reports.write

Keep scopes aligned with API capabilities, not arbitrary UI screens.


22. Role-based authorization

Example:

role = ReportAdmin

Roles can be useful for coarse application permissions.

Avoid creating a role for every individual endpoint.


23. Resource-level authorization

Even with a valid token and correct scope, verify the caller can access the requested resource.

Example:

token tenant_id = tenant-a
requested report belongs to tenant-b
→ deny

This is critical in multi-tenant APIs.


24. Tenant isolation belongs in authorization logic

Do not trust:

tenantId

from a query string or request body by itself.

Derive or validate tenant identity from a trusted authentication context.


25. Service-to-service token example

Request token:

TOKEN="$(
  curl \
    --silent \
    --request POST \
    --url "https://auth.example.com/oauth2/token" \
    --header "Content-Type: application/x-www-form-urlencoded" \
    --data-urlencode "grant_type=client_credentials" \
    --data-urlencode "client_id=$CLIENT_ID" \
    --data-urlencode "client_secret=$CLIENT_SECRET" \
    --data-urlencode "scope=reports.read" \
  | jq -r '.access_token'
)"

Use token:

curl \
  --header "Authorization: Bearer $TOKEN" \
  "https://api.example.com/v1/reports"

In production code, use the platform’s supported OAuth library rather than shell parsing when possible.


26. Do not request broader scopes than required

Bad:

scope=*

Better:

scope=reports.read

Least privilege reduces blast radius if a token is compromised.


27. Short-lived access tokens are preferable

Short token lifetime reduces exposure if a token leaks.

Do not compensate for operational inconvenience by issuing extremely long-lived Bearer tokens unless the security model explicitly requires it.

Use refresh or workload-identity mechanisms instead.


28. Cache access tokens responsibly

A service does not need to request a new token for every API call.

Typical pattern:

obtain token
→ cache until near expiration
→ refresh/acquire new token

Avoid both:

  • requesting a token on every request
  • reusing an expired token indefinitely

29. Refresh before expiry with a safety margin

Conceptually:

if token.expires_at <= now + refresh_margin:
    token = acquire_new_token()

Use a modest operational margin.

Do not invent large arbitrary margins that effectively shorten token lifetime unnecessarily.


30. Prevent token-refresh stampedes

In high-concurrency services, many workers may notice expiration simultaneously.

Use:

  • shared token cache
  • synchronization/locking
  • single-flight refresh logic

to avoid a burst of token requests.


31. mTLS client authentication

Example:

curl \
  --cert client-cert.pem \
  --key client-key.pem \
  "https://api.example.com/v1/data"

The server authenticates the client certificate during TLS negotiation.

Use when the trust model requires strong machine identity.


32. mTLS can coexist with application-layer tokens

Example:

mTLS
→ authenticates calling machine/client certificate

Bearer token
→ conveys application/user identity and permissions

This layered pattern is common in higher-trust integrations.


33. Protect private keys

Private keys should not be:

  • committed to source control
  • embedded in container images
  • stored in plain text config
  • copied into tickets/chat

Use a secure secret store or certificate/key management system.


34. HMAC request signing

Some APIs authenticate requests by signing request components with a shared secret.

Conceptually:

canonical request
→ HMAC(secret, canonical request)
→ signature header

This can protect request integrity and prove possession of the secret.

Exact canonicalization rules are API-specific.

Do not invent your own HMAC protocol for a public API when standard authentication mechanisms are available.


35. Signed-request replay protection

Signed protocols often include:

timestamp
nonce
request body hash

The server should reject stale/replayed requests according to the protocol.

Do not rely on signatures alone if the same signed request can be replayed indefinitely.


36. API gateway authentication

A gateway may validate:

  • API keys
  • JWTs
  • OAuth tokens
  • mTLS certificates

before traffic reaches the backend.

Still design backend authorization carefully.

Do not assume network placement alone makes every backend request trustworthy.


37. Backend should know which identity is trusted

If a gateway forwards identity headers such as:

X-User-ID
X-Tenant-ID

the backend must ensure clients cannot bypass the gateway and forge those headers.

Typical controls include:

  • private backend network
  • gateway-only access
  • header stripping/rewriting
  • backend token validation

38. Do not trust identity headers from arbitrary clients

Bad:

X-User-ID: admin

from the public internet.

Identity headers are only trustworthy if inserted by a trusted intermediary and protected from spoofing.


39. Use 401 vs 403 correctly

Typical meaning:

401 Unauthorized
→ authentication is missing or invalid

403 Forbidden
→ caller is authenticated but not allowed

Some systems intentionally vary behavior for security/privacy reasons, but this is the normal distinction.


40. Return WWW-Authenticate where appropriate

For Bearer-token APIs, a 401 response can include authentication challenge metadata.

Exact behavior depends on the API/security framework.

Use framework-standard behavior rather than inventing proprietary error semantics.


41. Do not return sensitive authentication details

Avoid responses like:

Token signed correctly but user account 12345 is disabled in tenant X

Prefer enough detail for the client to act without exposing internal security state.


42. Keep authentication errors observable server-side

Log safe fields such as:

request_id
client/application ID
issuer
audience
scope result
token expiry result
auth outcome

Do not log:

raw access token
client secret
password
private key
refresh token

43. Use correlation IDs

Example request:

curl \
  --header "X-Correlation-ID: auth-test-123" \
  --header "Authorization: Bearer $ACCESS_TOKEN" \
  "https://api.example.com/v1/reports"

This helps correlate:

client request
gateway logs
auth logs
API logs

44. Test an expired token deliberately in non-production

Useful authentication tests include:

missing token
malformed token
expired token
wrong audience
wrong issuer
valid token, missing scope
valid token, wrong tenant

This verifies the API fails safely.


45. Test wrong-audience tokens

A token that is valid for:

API A

should not automatically work against:

API B

Audience validation is essential in distributed systems.


46. Test wrong-tenant access

For multi-tenant APIs:

token tenant = A
resource tenant = B

should be denied even if the token is otherwise valid.

This is an authorization test, not merely an authentication test.


47. Do not use authentication as a substitute for authorization

Bad assumption:

token is valid
→ allow every endpoint

Correct model:

validate identity
→ validate permission
→ validate resource ownership/tenant

48. Prefer standards over custom authentication

Good choices:

  • OAuth 2.0
  • OpenID Connect where identity login is needed
  • standard Bearer tokens
  • mTLS
  • managed cloud/workload identity

Avoid:

custom encrypted username header
home-grown JWT signing
proprietary password exchange

unless there is a strong, reviewed requirement.


49. OpenID Connect is for identity on top of OAuth 2.0

OAuth 2.0 is primarily an authorization framework.

OpenID Connect adds user identity concepts such as:

ID token
user authentication
standard identity claims

Do not send an ID token to an API just because it is a JWT.

APIs usually expect an access token.


50. Access token vs ID token

Use:

access token
→ call an API

ID token
→ tell a client application about the authenticated user

Do not interchange them unless the identity provider explicitly documents that behavior.


51. Do not use a refresh token as an API token

Refresh tokens are intended for the authorization server.

The API should normally receive an access token.


52. Token introspection

Opaque-token systems may let the API or gateway call an authorization server to check token state.

Conceptually:

token
→ introspection endpoint
→ active / inactive + metadata

Useful when immediate revocation matters and tokens are not self-contained.

Tradeoff:

  • adds network dependency unless cached

53. JWT validation is usually local

Self-contained JWT access tokens can often be validated locally using trusted public keys.

Benefit:

  • no authorization-server call on every API request

Tradeoff:

  • revocation is less immediate unless additional mechanisms exist

54. Cache signing keys carefully

JWT validators often cache identity-provider public keys/JWKS.

Handle key rotation correctly.

Do not hardcode one signing certificate forever.

Use the security framework/provider’s standard key-discovery mechanism.


55. Reject unexpected signing algorithms

Do not accept arbitrary algorithms declared by the token.

Configure the validation library with the algorithms the API actually trusts.


56. Never accept unsigned JWTs

Reject tokens using:

alg = none

for protected APIs.

Use mature JWT libraries with secure defaults.


57. Store secrets outside source control

Prefer:

  • managed secret stores
  • workload identity
  • protected CI/CD secret variables
  • secure runtime configuration

Do not commit:

API keys
client secrets
private keys
refresh tokens
passwords

58. Rotate credentials

A production credential lifecycle should answer:

Who owns it?
Where is it stored?
When does it expire?
How is it rotated?
How is it revoked?
What breaks when it changes?

If those answers are unknown, the authentication design is incomplete.


59. Support overlapping rotation where possible

Safer rotation:

old credential valid
+
new credential deployed
→ clients migrate
→ old credential revoked

This reduces outage risk compared with changing every dependency at exactly the same moment.


60. Avoid one shared credential across many clients

If 50 services share the same API key:

you cannot easily identify
which service made which request

Prefer per-client identity when operationally possible.

This improves:

  • auditability
  • revocation
  • rate limiting
  • incident response

61. Rate-limit by stable identity

Useful dimensions include:

client_id
API key identity
tenant
user
service principal

Do not rely only on source IP when callers can share NAT/proxies.


62. Authentication data should not be used as arbitrary business input

Example:

sub = authenticated subject

is an identity claim.

Do not reuse unvalidated client request fields to override that trusted identity.


63. Treat token claims as security input

Even signed claims require:

  • issuer validation
  • audience validation
  • expected schema
  • authorization policy

Do not trust a claim merely because it exists.


64. Avoid accepting tokens from multiple issuers accidentally

If multiple issuers are supported, configure them explicitly.

Do not broaden trust to “any token signed by a reachable key endpoint.”


65. Use HTTPS everywhere for credential-bearing requests

API keys, Basic credentials, and Bearer tokens should not travel over plaintext HTTP.

Redirecting from HTTP to HTTPS is not equivalent to never sending the credential over HTTP.

Call the HTTPS endpoint directly.


66. Be careful with redirects and Authorization headers

If an authenticated URL redirects to another host, understand whether credentials will be forwarded.

Do not manually force authorization headers onto unrelated redirect targets.


67. Do not put tokens in frontend source code

A secret embedded in:

JavaScript bundle
mobile binary
desktop app

must be assumed discoverable by the client/user.

Public clients cannot safely hold long-lived confidential client secrets.


68. Backend-for-frontend pattern

For browser applications, a backend-for-frontend can keep sensitive tokens/server credentials out of browser JavaScript.

Conceptually:

browser
→ BFF session
→ backend
→ downstream API tokens

Use when the architecture and identity platform support it.


If authentication is automatically attached by the browser through cookies, state-changing requests may need CSRF defenses.

Bearer tokens in explicit Authorization headers have a different browser threat model.

Do not assume “authenticated” means “protected from CSRF.”


70. Cookies need secure attributes

For session cookies, consider:

Secure
HttpOnly
SameSite

based on the application’s cross-site requirements.

Do not put session tokens in JavaScript-readable cookies unless the design explicitly requires it and the risk is understood.


71. Authentication and CORS are different

CORS controls browser cross-origin access.

It does not authenticate the caller.

A cURL request can call an API regardless of browser CORS policy.


72. Authentication and encryption are different

Authentication answers:

who are you?

TLS provides:

transport confidentiality/integrity

Use both.


73. Authentication and request signing are different

Bearer token:

proves possession of token

Signed request:

can bind authentication to request components

Choose based on threat model and provider standards.


74. Authentication failures should fail closed

If the token validator, key lookup, or identity dependency fails unexpectedly, do not silently allow the request.

Security-sensitive failures should deny access unless the system’s explicitly reviewed design says otherwise.


75. Avoid custom fallback credentials

Bad pattern:

OAuth token fails
→ try hidden shared admin API key

Fallback authentication paths are easy to forget and difficult to audit.

Keep authentication paths explicit.


76. Use health checks carefully

A public health endpoint may not require authentication.

A diagnostic/admin health endpoint may contain sensitive details and should be protected.

Decide intentionally which information is exposed anonymously.


77. Document the API authentication contract

Every API should make clear:

authentication method
token issuer
audience
required scopes/roles
credential lifetime
refresh mechanism
tenant rules
error behavior

This reduces integration mistakes.


78. Build a troubleshooting matrix

For a failed authenticated request:

No Authorization header
→ client/config issue

401 + token expired
→ refresh/acquire new access token

401 + wrong issuer/audience
→ wrong token/API configuration

403 + valid token
→ authorization/scope/tenant issue

works locally, fails in deployed service
→ secret/workload identity/environment configuration

intermittent failures near expiry
→ token cache/refresh race

What the result means

Pattern Best fit Main concern
API key Simple machine access Rotation, coarse identity
Basic auth Legacy/simple integrations Long-lived password-like secret
Bearer token API access token Token theft/replay
OAuth client credentials Service-to-service Client identity and secret/workload identity
OAuth auth code + PKCE User-delegated access Redirect/session/token handling
JWT Self-contained token format Correct signature/claim validation
Opaque token Centrally checked token Introspection availability/latency
mTLS Strong machine/client identity Certificate lifecycle
HMAC signed request Signed partner/API protocols Canonicalization and replay protection
Workload identity Cloud/server workloads Platform/IAM configuration

The key design principle is:

authenticate identity
→ authorize capability
→ authorize resource

What to look for

401 Unauthorized

Check:

  • missing Authorization header
  • malformed token
  • expired token
  • wrong issuer
  • wrong audience
  • invalid signature
  • certificate/API-key failure

403 Forbidden

Authentication may have succeeded.

Check:

  • scope
  • role
  • resource ownership
  • tenant
  • policy
  • IP/network restrictions

Works until approximately token expiry

Check token caching and refresh logic.

The client may be reusing an expired token or multiple workers may race during refresh.

Works locally but fails in the deployed service

Check:

  • environment-specific credentials
  • managed identity/workload identity
  • secret availability
  • outbound network access
  • expected audience/scope

Valid JWT is rejected

“Valid JWT syntax” is not enough.

Check:

  • issuer
  • audience
  • signing key
  • algorithm
  • exp
  • nbf
  • required scope/role

Valid token accesses another tenant’s data

This is an authorization/isolation defect.

Authentication succeeded, but resource-level authorization is missing or wrong.

Production notes

Authentication secrets are production credentials

Treat them with the same care as passwords.

Do not expose them in:

  • logs
  • screenshots
  • tickets
  • source control
  • shell history
  • client-side bundles

Prefer short-lived credentials

Short-lived access tokens and workload identity reduce the impact of credential theft.

Long-lived static secrets increase rotation and incident-response burden.

Authentication libraries are security dependencies

Use maintained platform/framework libraries.

Keep them patched and avoid hand-written crypto/token parsing.

Authorization belongs close to the protected resource

Gateway validation is useful, but the service should still enforce the permissions that matter to its data and business rules.

Multi-tenant APIs need explicit tenant checks

Never assume a valid token is allowed to access every tenant represented by request parameters.

Credential rotation should be tested before an incident

If a key cannot be rotated without downtime, the authentication design is operationally fragile.

Common mistakes

1. Treating JWT decoding as validation

Anyone can decode a JWT payload.

Trust requires signature and claim validation.

2. Sending an ID token to an API

Use the access token intended for that API.

3. Logging raw tokens

Logs often have broad retention and access.

4. Sharing one API key across many clients

This harms auditability and revocation.

5. Putting secrets in query strings

They leak easily.

6. Using long-lived Bearer tokens because refresh is inconvenient

This increases compromise impact.

7. Validating authentication but not tenant/resource access

This causes cross-tenant/security defects.

8. Accepting any JWT signed by a known provider

Issuer and audience must still match the API’s trust policy.

9. Storing client secrets in frontend code

Public clients cannot keep secrets confidential.

10. Building custom authentication instead of using established standards

Security edge cases accumulate quickly.

Next step

Use the caller type and failure mode to choose the next action.

  • Simple machine integration → consider an API key only if rotation and identity granularity are acceptable.
  • Service-to-service in a modern identity platform → prefer OAuth client credentials or workload identity.
  • User-delegated API access → use authorization code flow with PKCE where appropriate.
  • API receives JWTs → validate signature, issuer, audience, time claims, then scopes/roles.
  • Valid token gets 403 → inspect authorization policy, scope, tenant, and resource ownership.
  • Tokens expire intermittently → inspect cache/refresh behavior and concurrency.
  • Need strong machine identity → evaluate mTLS.
  • Secrets are hard to rotate → redesign credential lifecycle before scaling the integration.
  • Need to reproduce auth behavior manually → use cURL Quick Reference.
  • Authentication succeeds but API still fails → move to Troubleshoot API Requests.

← All cheat sheets