Skip to main content

JSON Web Token (JWT) Security Cheat Sheet

A practical guide to understanding JWT architecture, identifying common vulnerabilities, and implementing secure token-based authentication in production.

Updated 20 min readMarkdown
JSON Web Token (JWT) Security Cheat Sheet

1. Introduction

This cheat sheet covers common security vulnerabilities associated with JSON Web Tokens (JWTs) and practical recommendations to protect applications that use them.

JSON Web Tokens (JWTs) are compact tokens used to securely transmit information (claims) between parties. They are commonly used for authentication, authorization, identity management, and secure communication between services.

JWTs can provide:

  • Authenticity: Signed JWTs ensure that claims have not been tampered with.
  • Confidentiality: Encrypted JWTs protect claims from unauthorized disclosure.
  • Standardized claims: JWT defines standard fields for representing information about users, applications, and token validity.

1.1 Common Use Cases

JWTs are widely used in modern applications:

  1. OpenID Connect (OIDC): ID tokens represent the identity and attributes of authenticated users.
  2. OAuth 2.0: Access tokens can be represented as JWTs to access protected resources.
  3. Session Management: JWTs are sometimes used for stateless authentication sessions, although this approach introduces revocation challenges.
  4. DPoP: Proof JWTs demonstrate possession of a private key.
  5. SPIFFE: JWT-SVIDs provide workload identity authentication.

1.2 How JWT Authentication Works

A signed JWT is generated by an issuer and presented to a consuming application (audience).

The consuming application validates the token's signature and claims before trusting the information.

For example, an attacker must not be able to modify:

  • User identity.
  • User roles.
  • Permissions.
  • Token expiration.
  • Issuer or audience information.

A valid signature protects the token's header and payload against unauthorized modifications.

Important: A valid signature does not automatically mean that a token is authorized to access a particular resource. Applications must also validate the relevant claims and authorization rules.


2. JWT Token Structure

A signed JWT consists of three Base64URL-encoded components separated by periods.

HEADER.PAYLOAD.SIGNATURE

The general structure is:

base64url(json(header)).
base64url(json(claims)).
base64url(signature)

2.1 Protected Header

The header contains metadata describing the token and its cryptographic protection.

Example:

{
  "alg": "HS256",
  "typ": "JWT"
}
  • alg: Cryptographic algorithm used to sign the token.
  • typ: Token media type.

2.2 Payload (Claims)

The payload contains information about the subject and other token-related metadata.

Example:

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true,
  "iat": 1516239022
}

Common claims include:

  • sub: Subject identifier.
  • iss: Token issuer.
  • aud: Intended audience.
  • exp: Expiration timestamp.
  • iat: Issued-at timestamp.
  • nbf: Not-before timestamp.
  • jti: Unique token identifier.

2.3 Signature

The signature protects the integrity and authenticity of the header and payload.

For HMAC-SHA256:

base64url(
    HMACSHA256(
        "encoded_header.encoded_payload",
        secret_key
    )
)

For public-key algorithms, the issuer signs using a private key, and the consumer verifies using the corresponding public key.

2.4 Example JWT

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.KMUFsIDTnFmyG3nMiGM6H9FNFUROf3wh7SmqJp-QV30

Security consideration: Base64URL encoding is not encryption. Anyone possessing a normal signed JWT can decode its header and payload.


3. Considerations Before Using JWTs

3.1 Do You Actually Need JWTs?

JWTs are frequently suggested as a solution for stateless authentication. However, they are not always the best choice.

A traditional server-side session system offers several advantages:

  • Immediate session invalidation.
  • Centralized session management.
  • Easier logout implementation.
  • Better control over active sessions.
  • Reduced exposure of authentication claims to clients.

JWTs introduce additional complexity when implementing token revocation.

If your application requires immediate session invalidation, consider using traditional session management with secure, HTTP-only cookies.

If you choose JWT-based authentication, implement a suitable revocation strategy.

3.2 Public-Key Signatures vs. MAC

JWTs support two primary approaches for signature verification.

Feature Public-Key Signature MAC
Cryptography Asymmetric Symmetric
Signing key Private key Shared secret
Verification key Public key Same shared secret
Key distribution Easier More sensitive
Multiple audiences Easier to manage Separate secrets recommended
Key compromise Private key compromise Shared secret compromise

Public-key signatures

The issuer signs the JWT using its private key. Consumers verify it using the corresponding public key.

Advantages:

  • Consumers do not need access to the signing secret.
  • Public keys can be distributed through trusted JWKS endpoints.
  • Different audiences can verify tokens without gaining signing capabilities.
  • Key rotation and distribution are easier to manage.

MAC-based signatures

The issuer and consumer share the same secret.

The issuer uses the secret to generate the signature, and the consumer uses the same secret to verify it.

Security considerations:

  • Use a different secret for each issuer-audience pair.
  • Never expose shared secrets.
  • Implement secure secret distribution and rotation.
  • Never use passwords as signing secrets.

4. Secure JWT Algorithm Selection

Choosing the correct signing algorithm is essential for JWT security.

Algorithm JWT Identifier Recommendation
EdDSA EdDSA, Ed25519, Ed448 Recommended; implementation support varies
ECDSA ES256, ES384, ES512 Recommended
RSASSA-PSS PS256, PS384, PS512 Recommended
RSASSA-PKCS1-v1_5 RS256, RS384, RS512 Not recommended for new designs
ML-DSA ML-DSA-44, ML-DSA-65, ML-DSA-87 Post-quantum; limited JWT ecosystem support

Additional considerations:

  • Use deterministic ECDSA where appropriate, particularly when secure randomness cannot be guaranteed.
  • Avoid reusing signing keys for encryption.
  • Consider hybrid or post-quantum signatures only when your threat model and ecosystem support justify them.
  • Evaluate implementation and interoperability support before selecting an algorithm.
Algorithm JWT Identifier Recommendation
HMAC-SHA256 HS256 Recommended
HMAC-SHA384 HS384 Recommended
HMAC-SHA512 HS512 Recommended

4.3 Secure HMAC Secret Generation

Generate cryptographically secure random secrets.

Recommended implementation:

import secrets

# 256-bit secret for HS256
secret_for_hs256 = secrets.token_bytes(256 // 8)

# 512-bit secret for HS512
secret_for_hs512 = secrets.token_bytes(512 // 8)

Never use the following approaches:

import random
import secrets

# Weak: Password-based secret
bad_secret = b"MyProject2026"

# Weak: Hardcoded secret
bad_secret = b"hardcoded-secret"

# Weak: Non-cryptographic randomness
bad_secret = random.randbytes(256 // 8)

# Weak: Insufficient entropy for HS256
bad_secret = secrets.token_bytes(128 // 8)

Security checklist:

  • Generate secrets using a cryptographically secure random generator.
  • Use at least 256 bits for HS256.
  • Use at least 384 bits for HS384.
  • Use at least 512 bits for HS512.
  • Never reuse signing secrets across different issuers or audiences.
  • Never publish secrets in source code or public repositories.
  • Store secrets in a dedicated secrets manager or secure environment configuration.

5. JWT Header Security

JWT headers contain cryptographic and key-selection metadata.

Some important JOSE header parameters include:

Parameter Purpose Security Risk
alg Signature algorithm Algorithm confusion
typ Token media type Token type confusion
jku JWK Set URL SSRF and untrusted key usage
x5u X.509 certificate URL SSRF and untrusted key usage
jwk Embedded public key Untrusted key usage
kid Key identifier Injection and key-selection attacks
x5c X.509 certificate chain Untrusted certificate usage
x5t Certificate thumbprint Untrusted key selection
x5t#S256 SHA-256 certificate thumbprint Untrusted key selection

Best practices:

  1. Never blindly trust key material supplied by an incoming JWT.
  2. Maintain trusted verification keys independently of the token.
  3. Validate and sanitize kid before using it in database or filesystem lookups.
  4. Avoid arbitrary HTTP requests based on jku or x5u.
  5. Restrict verification keys to trusted issuers.
  6. Explicitly configure accepted algorithms.

6. JWT Claims Security

Claims contain identity, authorization, and token-validity information.

The following table highlights important claims and their security implications.

Claim Purpose Security Consideration
iss Issuer Validate trusted issuer
sub Subject Validate subject identity
aud Audience Prevent audience confusion
exp Expiration Enforce token expiration
nbf Not-before Prevent premature token use
iat Issued-at Audit and token-age policies
jti Token identifier Revocation and replay protection
scope OAuth permissions Enforce authorization
roles User roles Prevent privilege escalation
groups User groups Validate group membership
entitlements User entitlements Enforce access restrictions
client_id OAuth client Validate client identity
azp Authorized party Validate authorized client
auth_time Authentication time Enforce authentication freshness
acr Authentication context Enforce authentication strength
amr Authentication methods Verify authentication methods
cnf Confirmation key Sender-constrained tokens
act Acting party Validate delegated identity
may_act Authorized actor Validate delegation permissions
authorization_details Fine-grained permissions Enforce detailed authorization
status Token status reference Revocation and URL-fetching risks

6.1 Validate Standard Claims

Always validate claims according to your application's security requirements.

At minimum, consider validating:

  • exp: Reject expired tokens.
  • nbf: Reject tokens that are not yet valid.
  • iss: Accept only trusted issuers.
  • aud: Accept only tokens intended for your application.
  • sub: Ensure the subject is valid for the expected issuer.

Remember that some JWT claims are optional in the JWT specification. Your application must explicitly require the claims needed by its security profile.


7. Common JWT Vulnerabilities

7.1 Unsecured JWTs (alg: none)

Some older JWT implementations accepted unsigned tokens using:

{
  "alg": "none",
  "typ": "JWT"
}

In this scenario, the token does not have a cryptographic signature.

An attacker may create a token with arbitrary claims, potentially impersonating users or obtaining unauthorized privileges.

Mitigation:

  • Explicitly reject alg: none.
  • Use maintained JWT libraries.
  • Require cryptographic signature verification.
  • Never trust decoded claims before verification.

7.2 Algorithm Confusion (Key Type Confusion)

Algorithm confusion occurs when a JWT implementation incorrectly accepts a public key as a shared MAC secret.

For example, an application expects an ES256-signed token but also accepts HS256.

An attacker may exploit this behavior by using the public key as an HMAC secret.

Example of legitimate token issuance:

token = jwt.encode(
    claims,
    private_key_bytes,
    algorithm="ES256"
)

Potentially vulnerable validation:

decoded = jwt.decode(
    token,
    public_key_bytes,
    algorithms=jwt.algorithms.get_default_algorithms()
)

Mitigation:

Explicitly allow only the algorithm expected by the application.

decoded = jwt.decode(
    token,
    public_key_bytes,
    algorithms=["ES256"]
)

Additional recommendations:

  • Use maintained JWT libraries.
  • Keep asymmetric and symmetric algorithms separate.
  • Bind each verification key to its intended algorithm.
  • Never allow the token header to determine the application's trusted algorithm policy.

7.3 Trusting Key Material from JWT Headers

JWT headers can contain or reference verification keys through:

  • jwk
  • jku
  • x5u
  • x5c

Blindly trusting these values creates an opportunity for attackers to introduce their own signing keys.

Attack scenario:

  1. An attacker generates a private/public key pair.
  2. They create a forged JWT.
  3. They include their public key in the jwk header or reference a malicious JWKS URL through jku.
  4. The vulnerable application trusts the supplied key.
  5. The forged token passes signature verification.

Mitigation:

  • Maintain trusted keys independently of incoming tokens.
  • Use issuer-configured JWKS endpoints.
  • Validate certificate chains against trusted roots.
  • Never blindly fetch arbitrary URLs from token headers.
  • Validate kid before performing key lookups.
  • Apply SSRF protections to any key-fetching mechanism.

Important: kid should select a key from an already trusted key set. It must never establish trust by itself.

7.4 Issuer and Audience Confusion

Two important JWT claims are:

{
  "iss": "https://auth.example.com/",
  "aud": "https://api.example.com"
}
  • iss identifies who issued the token.
  • aud identifies who is allowed to consume the token.

Failure to validate these claims can lead to token substitution and cross-service access.

Audience confusion

An attacker presents a token intended for one service to another service that trusts the same issuer.

For example, a token issued for a low-privilege service might be accepted by an internal API if the audience is not checked.

Issuer confusion

An attacker presents a token from an unexpected issuer that the application also trusts.

A particularly dangerous implementation selects signing keys from a combined key set belonging to multiple issuers without binding the key selection to the validated issuer.

Mitigation:

  1. Validate iss using an exact, case-sensitive issuer identifier.
  2. Validate aud against the receiving application's identifier.
  3. Bind each issuer to its own trusted JWKS.
  4. Never search a combined key set across unrelated issuers.
  5. Require iss and aud where your token profile depends on them.
  6. Validate the subject according to the issuer's identity namespace.

Secure Python implementation using PyJWT:

import jwt

ISSUER = "https://auth.example.com/"
AUDIENCE = "https://api.example.com/v1/payments"

jwks_client = jwt.PyJWKClient(
    "https://auth.example.com/.well-known/jwks.json"
)

signing_key = jwks_client.get_signing_key_from_jwt(token)

decoded_payload = jwt.decode(
    token,
    signing_key,
    algorithms=["ES256"],
    issuer=ISSUER,
    audience=AUDIENCE,
    options={
        "require": ["exp", "iss", "aud"]
    }
)

Why this is safer:

  • Only ES256 is accepted.
  • The signing key comes from the expected issuer's JWKS.
  • The issuer is explicitly validated.
  • The audience is explicitly validated.
  • Required claims are enforced.

Note that PyJWKClient must be configured to use a trusted issuer's JWKS endpoint, with appropriate HTTPS and network protections.

7.5 Cross-JWT and Token Type Confusion

Token type confusion occurs when an application accepts one type of JWT in a context intended for another.

For example:

  • An ID token is accepted as an access token.
  • A password-reset token is accepted as an authentication token.
  • A logout token is accepted as an API access token.

Mitigation:

  1. Use explicit token typing through typ.
  2. Validate the expected token type.
  3. Use separate validation rules for different token purposes.
  4. Consider separate signing keys for different token types.
  5. Enforce appropriate issuer, audience, and required-claim checks.

Common token types include:

Token Type typ
OAuth 2.0 Access Token at+jwt
OIDC Back-Channel Logout Token logout+jwt
Custom Password Reset Token example-reset+jwt

Example using PyJWT:

import jwt

decoded = jwt.decode_complete(
    token,
    public_key,
    algorithms=["ES256"],
    audience="https://api.example.com",
    issuer="https://auth.example.com",
    options={
        "require": ["exp", "iss", "aud"]
    }
)

typ = str(
    decoded["header"].get("typ", "")
).lower()

if typ not in ["at+jwt", "application/at+jwt"]:
    raise jwt.InvalidTokenError(
        "Invalid token type"
    )

The example verifies the signature and claims before checking the token type.


8. JWT Revocation and Replay Protection

JWTs are often designed to be self-contained. However, this creates a challenge when a token needs to be invalidated before its expiration.

There are several approaches to address this problem.

8.1 Token Status Lists

Token Status Lists (TSL) provide a scalable mechanism for communicating token revocation status.

The general workflow is:

  1. The issuer creates a token status list.
  2. The JWT includes a status claim.
  3. The claim references the status list and identifies the token's position.
  4. The consumer retrieves the status list.
  5. The consumer checks whether the token has been revoked.

Example:

{
  "iss": "https://issuer.example/",
  "sub": "NsxuACbpJ9N7Ix96aWrYxHX-EZ4",
  "iat": 1783635268,
  "nbf": 1783635268,
  "exp": 1783653268,
  "status": {
    "status_list": {
      "idx": 6,
      "uri": "https://issuer.example/tsl/JAffke55FR5gtJQ_rtktWkSaTlI"
    }
  }
}

Security considerations:

  • Trust only configured status-list issuers.
  • Validate status-list signatures.
  • Protect status-list fetching against SSRF.
  • Define cache expiration and failure behavior.
  • Do not assume a token is valid merely because its status list cannot be retrieved.

8.2 JWT Denylist

A denylist stores revoked tokens or session identifiers.

A common implementation uses the combination of jti and iss.

Example:

def revoke_token(claims):
    jti = claims.get("jti")
    iss = claims.get("iss")
    exp = claims.get("exp")

    deny_list.insert(
        (jti, iss),
        exp
    )


def is_token_revoked(claims):
    jti = claims.get("jti")
    iss = claims.get("iss")

    return deny_list.contains(
        (jti, iss)
    )

Why use jti and iss?

  • jti uniquely identifies a token within its issuer's namespace.
  • iss prevents collisions between different issuers.
  • exp allows expired denylist entries to be cleaned up.

Important: Validate the JWT signature and claims before using their values in denylist operations.

8.3 Avoid Hashing the Raw JWT for Revocation

Using the raw JWT or its SHA-256 hash as the denylist key can introduce bypass opportunities.

This is because JWT representations and signatures may be malleable.

For example:

# Unsafe approach
import hashlib

def unsafe_revoke_token(token):
    token_hash = hashlib.sha256(
        token.encode("utf-8")
    ).digest()

    deny_list.insert(token_hash)

Prefer using validated claims such as iss and jti.

8.4 Additional Replay Protection Strategies

Consider the following controls:

  1. Short-lived access tokens: Reduce the time available for stolen tokens to be abused.
  2. Nonce-based protection: Bind tokens to a session or transaction using an unpredictable nonce where appropriate.
  3. DPoP-bound tokens: Require proof of possession of a corresponding private key.
  4. Mutual TLS-bound tokens: Bind access tokens to a client certificate.
  5. Server-side session tracking: Maintain session state where immediate revocation is required.

Remember that sender-constrained tokens reduce the usefulness of stolen tokens but do not prevent token disclosure itself.


9. JWT Confidentiality and JWE

9.1 Signed JWTs Are Not Confidential

A signed JWT provides integrity and authenticity, not confidentiality.

Its payload is Base64URL-encoded rather than encrypted.

Anyone who obtains a signed JWT can decode its header and payload.

For example:

{
  "sub": "user-123",
  "email": "user@example.com",
  "role": "admin"
}

If this information is included in a signed JWT, it is readable by anyone who possesses the token.

Security risks include:

  • Sensitive information exposure.
  • Accidental logging of personal information.
  • Browser storage exposure.
  • Disclosure through application monitoring.
  • Exposure to intermediaries that terminate TLS.

Mitigation:

  • Never include passwords or secrets in JWT claims.
  • Avoid storing sensitive personal information in JWT payloads.
  • Use opaque reference tokens when claims do not need to travel with the token.
  • Protect tokens during storage and transmission.
  • Use HTTPS for all token communication.

9.2 What Is JWE?

JSON Web Encryption (JWE) provides confidentiality for JWT claims.

Unlike JWS, which signs the token, JWE encrypts its contents.

JWE uses two primary algorithm parameters:

Parameter Purpose Examples
alg Key management algorithm RSA-OAEP-256, ECDH-ES+A256KW
enc Content encryption algorithm A256GCM
  • alg determines how the Content Encryption Key (CEK) is protected or established.
  • enc determines how the actual payload is encrypted.

9.3 Important JWE Security Considerations

JWE provides confidentiality and ciphertext integrity, but encryption alone does not establish who issued the claims.

For example, anyone possessing the recipient's public encryption key can potentially create a JWE that the recipient can decrypt.

Therefore, never make authorization decisions based only on successful JWE decryption.

Recommended approach: Nested JWT

When both authenticity and confidentiality are required:

  1. Create a JWT containing the claims.
  2. Sign the JWT using JWS.
  3. Encrypt the signed JWT using JWE.
  4. Set the outer JWE cty header to JWT.
  5. The consumer decrypts the outer JWE.
  6. The consumer verifies the inner JWS signature.
  7. The consumer validates all required claims before accepting the token.

Conceptually:

Claims
  |
  v
JWS Signing
  |
  v
Signed JWT
  |
  v
JWE Encryption
  |
  v
Encrypted JWT
  |
  v
Consumer
  |
  v
JWE Decryption
  |
  v
JWS Signature Verification
  |
  v
Claims Validation
  |
  v
Authorization

9.4 Additional JWE Best Practices

  • Allowlist supported alg and enc combinations.
  • Bind each key to its intended algorithm.
  • Never allow untrusted token headers to determine cryptographic policy.
  • Avoid compression using the zip header.
  • Verify the inner JWS signature when using nested JWTs.
  • Reject tokens if decryption or signature verification fails.
  • Validate issuer, audience, expiration, and other required claims after cryptographic verification.

10. JWT Security Implementation Checklist

Use this checklist when implementing JWT authentication in production.

Algorithm and Cryptography

  • Explicitly allowlist signing algorithms.
  • Reject alg: none.
  • Prevent algorithm and key type confusion.
  • Use secure cryptographic libraries.
  • Generate strong random signing secrets.
  • Never reuse secrets across different issuer-audience pairs.
  • Implement signing key rotation.
  • Never reuse signing keys for unrelated cryptographic purposes.

Token Validation

  • Verify the JWT signature before trusting claims.
  • Validate iss.
  • Validate aud.
  • Validate exp.
  • Validate nbf.
  • Require essential claims.
  • Validate typ for token profiles that require it.
  • Validate subject identity and authorization context.
  • Use mutually exclusive validation rules for different token types.

Key Management

  • Keep private keys and secrets outside source code.
  • Use trusted JWKS endpoints.
  • Never blindly trust jwk, jku, or x5u.
  • Validate kid before key lookup.
  • Protect key distribution and rotation.
  • Prevent SSRF through remote key retrieval.

Session and Revocation

  • Use short-lived access tokens.
  • Implement a token revocation strategy.
  • Use jti and iss for denylist entries where appropriate.
  • Consider Token Status Lists for scalable revocation.
  • Implement replay protection where required.
  • Consider DPoP or mutual TLS for sender-constrained tokens.

Confidentiality

  • Never store passwords or secrets in JWT payloads.
  • Remember that signed JWTs are readable.
  • Use HTTPS everywhere.
  • Avoid logging complete JWTs.
  • Use JWE when token claims genuinely require confidentiality.
  • Use nested JWS and JWE when both authenticity and confidentiality are required.

11. References

For deeper technical details and implementation guidance, refer to the following specifications:

  1. RFC 7519 – JSON Web Token (JWT)
  2. RFC 8725 – JSON Web Token Best Current Practices
  3. RFC 7516 – JSON Web Encryption (JWE)
  4. RFC 7517 – JSON Web Key (JWK)
  5. RFC 9068 – JWT Profile for OAuth 2.0 Access Tokens
  6. RFC 6979 – Deterministic Usage of DSA and ECDSA
  7. RFC 9449 – OAuth 2.0 Demonstrating Proof of Possession (DPoP)
  8. RFC 9671 – JWT Status List

Conclusion

JWTs are powerful building blocks for authentication and authorization in distributed systems, but using them securely requires more than simply signing and verifying tokens.

The most important principles are:

  • Never trust unverified claims.
  • Explicitly configure cryptographic algorithms.
  • Validate issuer, audience, expiration, and token type.
  • Protect signing keys and verification-key distribution.
  • Implement revocation and replay protection where necessary.
  • Understand that signing does not provide confidentiality.
  • Use JWE when encryption is genuinely required.

A JWT is only as secure as the validation, key management, and authorization controls surrounding it.

Build secure authentication systems by treating every incoming token as untrusted until all required cryptographic and application-level checks have passed.

1 view

About the author

No comments yet. Be the first to comment.