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)

  1. The issuer (e.g., AWS Cognito) creates a message:

    message = lmn.pqr
  2. 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))
  3. The full JWT becomes:

    lmn.pqr.x123


Signature Verification (on the Backend)

When your backend receives the JWT:

  1. Split the JWT into its parts:

    header = lmn
    payload = pqr
    signature = x123
  2. Reconstruct the message to verify:

    message = lmn.pqr
  3. Decode the header to read the algorithm:

    { "alg": "RS256" }
  4. 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.

  5. Verify the signature:

    • Compute the hash of the message:

      hash1 = SHA256(lmn.pqr)
    • Decrypt the provided signature using the public key:

      hash2 = decryptSignatureWithPublicKey(x123)
  6. 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

Popular posts from this blog

Database - Topics

02. Spring – Creating spring project clone it with GIT step by step.

01. Steps in SQL Query Execution (MySQL)