JWT Signature Verification Flow (RS256)
JWT Signature Verification Flow (RS256)
This document explains how JWT (JSON Web Token) signature verification works using asymmetric encryption (e.g., RS256
), where the issuer signs with a private key and the verifier checks it using a public key.
Example Input
JWT Header (before encoding):
{
"alg": "RS256",
"typ": "JWT"
}
JWT Payload (before encoding):
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}
After Base64URL encoding:
-
Header:
lmn
-
Payload:
pqr
Signature Generation:
Signature = signWithPrivateKey("lmn.pqr") = x123
Final JWT:
JWT = lmn.pqr.x123
Signature Generation (by Token Issuer — e.g., AWS Cognito)
-
The issuer (e.g., AWS Cognito) creates a message:
message = lmn.pqr
-
The message is signed using the private RSA key and the algorithm specified in the JWT header:
-
RS256 = RSA with SHA-256 hashing.
-
Signature is generated as:
x123 = signWithPrivateKey(SHA256(message))
-
-
The full JWT becomes:
lmn.pqr.x123
Signature Verification (on the Backend)
When your backend receives the JWT:
-
Split the JWT into its parts:
header = lmn
payload = pqr
signature = x123 -
Reconstruct the message to verify:
message = lmn.pqr
-
Decode the header to read the algorithm:
{ "alg": "RS256" }
-
Fetch the public key (from a trusted JWKS endpoint like AWS Cognito):
-
On the first request, fetch the public key.
-
Cache the key to avoid fetching on every request.
-
-
Verify the signature:
-
Compute the hash of the message:
hash1 = SHA256(lmn.pqr)
-
Decrypt the provided signature using the public key:
hash2 = decryptSignatureWithPublicKey(x123)
-
-
Compare the hashes:
if (hash1 == hash2) → Token is valid else → Token is invalid or tampered
Important Notes
-
The
alg
field in the JWT header tells the verifier what algorithm to use (e.g.,RS256
). -
The issuer signs with a private key, and the receiver verifies using the matching public key.
-
The JWT payload is not encrypted — it is just Base64URL encoded, so its content is readable.
-
Do not store sensitive data in the payload unless encrypted or properly protected.
-
-
Always validate:
-
Signature
-
Expiration (
exp
claim) -
Issuer (
iss
) -
Audience (
aud
)
Comments
Post a Comment