Implementing JWT Tampering Defense: Practical JWS & JWE Tutorial
JSON Web Tokens (JWTs) are the standard bearer credential for stateless APIs and microservices—yet improper implementation turns them into severe authentication bypass vectors. Because a standard JWT (RFC 7519) is merely Base64URL-encoded JSON, anyone who intercepts a token can decode and read its claims, and weak verification logic allows attackers to forge administrative tokens via alg: none bypasses, HMAC/RSA key confusion, or forged JWK headers.
Securing stateless tokens in production requires combining JSON Web Signature (JWS) for cryptographic integrity with JSON Web Encryption (JWE) when tokens carry sensitive PII or internal authorization metadata—paired with strict, allowlisted claim validation.
JWS vs. JWE: Choosing the Right Token Defense
Understanding how JWS and JWE protect tokens at different layers prevents both tampering and sensitive data leakage:
| Security Dimension | Unsecured JWT (alg: none) | JWS (JSON Web Signature) | JWE (JSON Web Encryption) |
|---|---|---|---|
| RFC Specification | RFC 7519 (Insecure) | RFC 7515 | RFC 7516 |
| Token Structure | 2 segments (Header.Payload.) | 3 segments (Header.Payload.Signature) | 5 segments (Header.EncryptedKey.IV.Ciphertext.Tag) |
| Tampering Protection | None — arbitrary modification succeeds | Cryptographic Integrity (HMAC, RSA, ECDSA, EdDSA) | Authenticated Encryption (AEAD integrity + confidentiality) |
| Payload Confidentiality | Plaintext (Base64URL-decoded by anyone) | Plaintext (Base64URL-decoded by anyone) | Encrypted (Opaque ciphertext; unreadable without private key) |
| Recommended Algorithms | Never use in production | EdDSA (Ed25519), ES256, RS256 | RSA-OAEP-256 / ECDH-ES + A256GCM |
| Primary Production Use | None | Public/non-sensitive claims (sub, iss, exp, scope) | Tokens carrying PII, internal roles, or downstream API secrets |
+-----------------------------------------------------------------------------------+
| END-TO-END JWT TAMPERING DEFENSE PIPELINE |
+-----------------------------------------------------------------------------------+
| |
| 1. TOKEN ISSUANCE (Auth Server / Identity Provider) |
| +-------------------+ Sign (Private Key) +------------------------+ |
| | JWT Claims | --------------------------> | JWS (Signed Token) | |
| | {sub, roles, exp} | RS256 / EdDSA | Header.Payload.Sig | |
| +-------------------+ +------------------------+ |
| | |
| Encrypt (Recipient Public Key) |
| RSA-OAEP-256 + A256GCM |
| v |
| +------------------------+ |
| | JWE (Nested Encrypted) | |
| | Hdr.Key.IV.Cipher.Tag | |
| +------------------------+ |
| | |
| 2. TOKEN VERIFICATION (Resource API Gateway) v |
| +--------------------------------------------------------------------------+ |
| | Step A: Decrypt JWE using Resource Server Private Key (Verify AEAD Tag) | |
| | Step B: Enforce Explicit Algorithm Allowlist (Reject 'none' & 'HS256') | |
| | Step C: Verify JWS Signature against Pinned Issuer Public Key / JWKS | |
| | Step D: Validate 'iss', 'aud', 'exp', 'nbf' (+ Clock Skew <= 30s) | |
| +--------------------------------------------------------------------------+ |
+-----------------------------------------------------------------------------------+
Common JWT Tampering Attacks & Defenses
Before writing verification code, review the four primary exploitation techniques targeting misconfigured JWT libraries:
- Algorithm Confusion (
RS256$\rightarrow$HS256): If a server verifies tokens using a singlekeyvariable and trusts the incoming token header'salgfield, an attacker can changealgfromRS256toHS256and sign a forged payload using the server's public RSA certificate as an HMAC secret. Defense: Hardcode an explicit algorithm allowlist (e.g.,algorithms=["RS256"]) during verification and strictly separate public verification keys from symmetric secrets. - Embedded JWK /
jkuHeader Injection: Attackers inject their own public key inside the token header'sjwkfield or pointjku(JWK Set URL) to an attacker-controlled domain (https://evil.example/jwks.json). Defense: Never dynamically fetchjkuURLs or trust inlinejwkheaders. Pin a local public key or fetch from a hardcoded, HTTPS-enforced issuer JWKS endpoint. - Signature Stripping (
alg: none): Setting"alg": "none"and stripping the signature segment bypasses authentication on older or misconfigured JWT parsers. Defense: Reject any token whose headeralgisnoneor missing from your allowlist. - Sensitive Claim Exposure in JWS: Teams frequently store user emails, SSNs, internal database IDs, or feature flags in standard JWS payloads, exposing them in browser
localStorage, proxy logs, and referrer headers. Defense: Wrap sensitive claims inside a JWE (or nested JWS-inside-JWE) so intermediate proxies and clients cannot inspect the payload.
Step 1: Generating Asymmetric Signing & Encryption Keys
For production microservices, separate your signing key pair (used by the Identity Provider to sign JWS tokens) from your encryption key pair (used by the Resource API to decrypt JWE tokens):
# 1. Generate RSA-2048 key pair for JWS signing (Identity Provider)
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out jws_signing_private.pem
openssl rsa -pubout -in jws_signing_private.pem -out jws_signing_public.pem
# 2. Generate RSA-2048 key pair for JWE decryption (Resource Server)
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out jwe_decrypt_private.pem
openssl rsa -pubout -in jwe_decrypt_private.pem -out jwe_decrypt_public.pem
# Restrict private key file permissions
chmod 0600 jws_signing_private.pem jwe_decrypt_private.pem
Step 2: Implementing Tamper-Proof JWS Issuance & Verification (jws_defense.py)
Using PyJWT (pip install pyjwt[crypto]), enforce strict algorithm pinning, explicit iss (issuer) and aud (audience) matching, and mandatory expiration claims (require=["exp", "iat", "iss", "aud", "sub"]):
from datetime import datetime, timedelta, timezone
from pathlib import Path
import uuid
import jwt
from jwt.exceptions import InvalidTokenError
ISSUER = "https://auth.codecrown.in"
AUDIENCE = "billing-api-v1"
ALLOWED_SIGNING_ALG = "RS256"
def issue_hardened_jws(private_key_pem: str, user_id: str, scopes: list[str]) -> str:
now = datetime.now(timezone.utc)
claims = {
"iss": ISSUER,
"aud": AUDIENCE,
"sub": user_id,
"jti": str(uuid.uuid4()),
"iat": now,
"nbf": now,
"exp": now + timedelta(minutes=15),
"scope": " ".join(scopes),
}
return jwt.encode(
payload=claims,
key=private_key_pem,
algorithm=ALLOWED_SIGNING_ALG,
headers={"kid": "auth-key-2026-01"},
)
def verify_hardened_jws(public_key_pem: str, token: str) -> dict:
# Defense against alg:none, HS256 key confusion, and missing expiration claims
return jwt.decode(
jwt=token,
key=public_key_pem,
algorithms=[ALLOWED_SIGNING_ALG],
audience=AUDIENCE,
issuer=ISSUER,
leeway=timedelta(seconds=30),
options={
"require": ["exp", "iat", "nbf", "iss", "aud", "sub", "jti"],
"verify_signature": True,
"verify_exp": True,
"verify_nbf": True,
"verify_iat": True,
"verify_aud": True,
"verify_iss": True,
},
)
if __name__ == "__main__":
priv_key = Path("jws_signing_private.pem").read_text(encoding="utf-8")
pub_key = Path("jws_signing_public.pem").read_text(encoding="utf-8")
valid_token = issue_hardened_jws(priv_key, "usr_98412", ["invoices:read", "payments:write"])
verified_claims = verify_hardened_jws(pub_key, valid_token)
print(f"[PASS] Verified JWS Subject: {verified_claims['sub']} | Scopes: {verified_claims['scope']}")
# Simulate payload tampering (modifying Base64URL payload segment without valid signature)
header_b64, _, sig_b64 = valid_token.split(".")
tampered_payload_b64 = "eyJzdWIiOiJhZG1pbiIsInNjb3BlIjoiYWRtaW46YWxsIn0"
tampered_token = f"{header_b64}.{tampered_payload_b64}.{sig_b64}"
try:
verify_hardened_jws(pub_key, tampered_token)
except InvalidTokenError as exc:
print(f"[BLOCKED] Tampered token rejected: {exc}")
Step 3: Encrypting Sensitive Claims with Nested JWS + JWE (jwe_nested_token.py)
When a token carries sensitive attributes (such as email, tenant_tier, or pii_hash) or traverses untrusted client storage, sign first (JWS) and encrypt second (JWE) using jwcrypto (pip install jwcrypto). Signing before encrypting guarantees both non-repudiation from the issuer and confidentiality against payload inspection:
import json
from datetime import datetime, timedelta, timezone
from pathlib import Path
from jwcrypto import jwe, jwk, jwt
def create_nested_jws_jwe(
signing_priv_pem: bytes,
encryption_pub_pem: bytes,
claims: dict,
) -> str:
signing_key = jwk.JWK.from_pem(signing_priv_pem)
encryption_key = jwk.JWK.from_pem(encryption_pub_pem)
# 1. Create inner signed JWS (guarantees authenticity & integrity)
inner_jws = jwt.JWT(
header={"alg": "RS256", "typ": "JWT"},
claims=claims,
)
inner_jws.make_signed_token(signing_key)
signed_compact = inner_jws.serialize()
# 2. Wrap inner JWS inside an outer JWE using RSA-OAEP-256 + AES-256-GCM
outer_jwe = jwe.JWE(
plaintext=signed_compact.encode("utf-8"),
recipient=encryption_key,
protected=json.dumps({
"alg": "RSA-OAEP-256",
"enc": "A256GCM",
"cty": "JWT", # Signals nested JWT per RFC 7519 Section 5.2
}),
)
return outer_jwe.serialize(compact=True)
def decrypt_and_verify_nested_token(
encryption_priv_pem: bytes,
signing_pub_pem: bytes,
encrypted_token: str,
) -> dict:
decryption_key = jwk.JWK.from_pem(encryption_priv_pem)
verification_key = jwk.JWK.from_pem(signing_pub_pem)
# 1. Decrypt outer JWE and verify AES-GCM authentication tag
jwe_token = jwe.JWE()
jwe_token.deserialize(encrypted_token, key=decryption_key)
inner_signed_jwt = jwe_token.payload.decode("utf-8")
# 2. Verify inner JWS signature and standard temporal claims
verified_jwt = jwt.JWT(
jwt=inner_signed_jwt,
key=verification_key,
algs=["RS256"],
check_claims={"iss": "https://auth.codecrown.in", "aud": "billing-api-v1"},
)
return json.loads(verified_jwt.claims)
if __name__ == "__main__":
sign_priv = Path("jws_signing_private.pem").read_bytes()
sign_pub = Path("jws_signing_public.pem").read_bytes()
enc_priv = Path("jwe_decrypt_private.pem").read_bytes()
enc_pub = Path("jwe_decrypt_public.pem").read_bytes()
now = int(datetime.now(timezone.utc).timestamp())
sensitive_claims = {
"iss": "https://auth.codecrown.in",
"aud": "billing-api-v1",
"sub": "usr_98412",
"email": "alice.engineer@enterprise.internal",
"tax_region": "IN-KL",
"iat": now,
"exp": now + 900,
}
nested_token = create_nested_jws_jwe(sign_priv, enc_pub, sensitive_claims)
print(f"Nested JWE Token (5 segments): {nested_token[:72]}...\n")
recovered = decrypt_and_verify_nested_token(enc_priv, sign_pub, nested_token)
print(f"[PASS] Decrypted & Verified Claims: {recovered}")
Automated Security Testing & CI/CD Verification Checklist
Before deploying JWT authentication middleware to production, verify that your verification endpoint rejects all malformed and adversarial tokens:
- Reject
alg: noneTokens: Strip the signature segment, set{"alg": "none"}, and confirm the API returns HTTP401 Unauthorized. - Reject Algorithm Confusion (
HS256): Sign a token using the server's public PEM string as an HMAC secret and confirm the verifier rejects it due to strictalgorithms=["RS256"]allowlisting. - Reject Cross-Service Replay (
audMismatch): Send a valid token issued foranalytics-apitobilling-apiand confirm audience validation blocks lateral token replay. - Enforce Short TTLs & Revocation (
jti): Keep access token lifetimes between 5 and 15 minutes, and check high-privilege tokenjtiIDs against a Redis denylist upon logout or password reset.
Common Mistakes
- Assuming Base64URL encoding hides token data: Standard JWS tokens (
eyJhbGci...) are readable by any browser extension, CDN log, or proxy. Never place passwords, API keys, or unmasked PII inside a JWS without JWE encryption. - Using weak symmetric HMAC secrets (
HS256): Short secrets like"secret123"can be cracked offline in seconds usinghashcatagainst a single captured JWT. If using symmetric HMAC, generate at least $256\text{ bits}$ ($32\text{ random bytes}$) of cryptographic entropy, or prefer asymmetricEdDSA/RS256. - Omitting
aud(Audience) validation in microservices: Without strictaudenforcement, a compromised low-privilege microservice can replay a user's valid JWT against high-privilege internal services.
Summary
Defending JWTs against tampering and exposure requires pinning explicit asymmetric signing algorithms (RS256 or EdDSA), validating all temporal and routing claims (iss, aud, exp, nbf), and wrapping sensitive payloads in nested JWS + JWE (RSA-OAEP-256 + A256GCM) envelopes so tokens remain both unforgeable and confidential in transit.