Skip to lesson

JWT structure: header, payload, signature

ShopLite's API must trust a customer on every request without asking for the password again. The server needs a small proof that it wrote itself and that the client cannot edit.

Three Base64URL parts separated by dots

A JWT (JSON Web Token) is a signed text in three parts joined by dots: header.payload.signature. The header and the payload are small JSON objects with facts about a user, and the signature proves that the server wrote them.

With HTTP Basic the password travels on every request, and with sessions the server must remember every signed-in user. Below, a real ShopLite token is split at the dots and decoded in plain Java.

A JWT is three parts joined by dots. The header says which signing method was used, here HS256. The payload holds the facts, such as the user id, the roles and the expiry time. The signature is an HMAC of the header and the payload made with the server's secret key.

Example 1 · Decoding a real ShopLite token by hand

JwtPartsDemo.javaJava
import java.nio.charset.StandardCharsets;import java.util.Base64;
public class JwtPartsDemo {
    public static void main(String[] args) {        // A real access token from the ShopLite login endpoint (Asha's, long expired)        String token = "eyJraWQiOiJVVWFwcy1CaDlCTXlranQzb0o2ZHVRdGVmQlYzS3ZwN21zb0lWamxoTjFJIiwiYWxnIjoiSFMyNTYifQ"                + ".eyJpc3MiOiJzaG9wbGl0ZS1hcGkiLCJjdXN0b21lcklkIjoxLCJzdWIiOiIyIiwiZXhwIjoxNzkyMTM4Mzg5LCJpYXQiOjE3OTIxMzc0ODksInJvbGVzIjpbIkNVU1RPTUVSIl19"                + ".5EABULF1g4H_3ihX18b6o5ShcOS-JyYwl9CInsF-prM";
        String[] parts = token.split("\\.");        System.out.println("Parts: " + parts.length);
        Base64.Decoder base64Url = Base64.getUrlDecoder();     // Base64URL: - and _ instead of + and /        String header = new String(base64Url.decode(parts[0]), StandardCharsets.UTF_8);        String payload = new String(base64Url.decode(parts[1]), StandardCharsets.UTF_8);        byte[] signature = base64Url.decode(parts[2]);
        System.out.println("Header:    " + header);        System.out.println("Payload:   " + payload);        System.out.println("Signature: " + signature.length + " bytes (HMAC-SHA256 always gives 32)");    }}
Output
Parts: 3
Header:    {"kid":"UUaps-Bh9BMykjt3oJ6duQtefBV3Kvp7msoIVjlhN1I","alg":"HS256"}
Payload:   {"iss":"shoplite-api","customerId":1,"sub":"2","exp":1792138389,"iat":1792137489,"roles":["CUSTOMER"]}
Signature: 32 bytes (HMAC-SHA256 always gives 32)

What this code does

  • split("\\.") needs the backslashes because split takes a regular expression, and a plain . there means "any character".
  • Base64.getUrlDecoder() reads the URL-safe alphabet; the normal getDecoder() would fail on the - and _ in this signature.
  • The header has alg and a kid (key id) that Spring Security added. No key was needed to read any of it.

Each part is written in Base64URL, a version of Base64 that uses - and _ instead of + and / and drops the = padding, so the token is safe inside a URL or an HTTP header. The server writes the facts once at login and checks them on each request with a key, without a lookup.

Base64URL is an encoding, not encryption: anyone who has the token can turn the first two parts back into JSON with one line of Java, as the program above does.

Tokens almost always start with eyJ. That is simply {" in Base64, the start of the header JSON.

Standard claims and custom claims

A claim is one field in a JWT payload: a statement about the user or the token, such as sub for who the token is about or exp for when it ends. Standard claims have short names defined in RFC 7519; any other name is a custom claim.

Facts in a token need agreed names, so any library can read them. The program below reads ShopLite's claims and turns the time claims into India time.

Example 2 · Reading the claims and the times

ClaimsDemo.javaJava
import java.time.Duration;import java.time.Instant;import java.time.ZoneId;import java.util.regex.Matcher;import java.util.regex.Pattern;
public class ClaimsDemo {
    /** Reads one claim from the payload JSON. A real app uses a JSON library; this is enough to look. */    static String claim(String payload, String name) {        Matcher m = Pattern.compile("\"" + name + "\":(\"[^\"]*\"|\\[[^\\]]*\\]|[0-9]+)").matcher(payload);        return m.find() ? m.group(1) : "(missing)";    }
    public static void main(String[] args) {        // The payload of the ShopLite token from Example 1, already decoded        String payload = "{\"iss\":\"shoplite-api\",\"customerId\":1,\"sub\":\"2\","                + "\"exp\":1792138389,\"iat\":1792137489,\"roles\":[\"CUSTOMER\"]}";
        ZoneId india = ZoneId.of("Asia/Kolkata");        Instant iat = Instant.ofEpochSecond(Long.parseLong(claim(payload, "iat")));        Instant exp = Instant.ofEpochSecond(Long.parseLong(claim(payload, "exp")));
        System.out.println("iss (issuer):      " + claim(payload, "iss"));        System.out.println("sub (subject):     " + claim(payload, "sub") + "  <- the user id");        System.out.println("iat (issued at):   " + iat.atZone(india).toLocalDateTime());        System.out.println("exp (expires at):  " + exp.atZone(india).toLocalDateTime());        System.out.println("lifetime:          " + Duration.between(iat, exp).toMinutes() + " minutes");        System.out.println("roles (custom):    " + claim(payload, "roles"));        System.out.println("customerId:        " + claim(payload, "customerId"));        System.out.println("aud (audience):    " + claim(payload, "aud"));    }}
Output
iss (issuer):      "shoplite-api"
sub (subject):     "2"  <- the user id
iat (issued at):   2026-10-16T13:28:09
exp (expires at):  2026-10-16T13:43:09
lifetime:          15 minutes
roles (custom):    ["CUSTOMER"]
customerId:        1
aud (audience):    (missing)

What this code does

  • iat and exp are plain numbers of seconds since 1970 (UTC). Instant.ofEpochSecond turns them into a time, shown here in Asia/Kolkata.
  • The token lives exactly 15 minutes: ShopLite's access-token lifetime.
  • The regular expression is only for looking inside a token in a lab; the real app never parses claims by hand.

The standard names:

  • sub (subject): who the token is about. ShopLite puts the user id here, "2".
  • iat (issued at) and exp (expiry): times as seconds since 1 January 1970 UTC.
  • iss (issuer): who made the token, here "shoplite-api".
  • aud (audience): which API the token is for (ShopLite does not use it yet).

Any other name is a custom claim. ShopLite adds roles (for access rules) and customerId (for the customer's own orders).

If exp is missing, a careless server would accept the token forever. Spring Security rejects expired tokens by default, and ShopLite always sets exp.

The signature: HS256 vs RS256

HS256 is a signing method that computes an HMAC with SHA-256 from one shared secret key. The same key signs the token and checks it, so the key must stay on the server.

The signature is computed from header.payload with a key. Change one letter of the payload and the signature no longer matches, so the server rejects the token.

Text
HS256: signature = HMAC-SHA256(secret, base64url(header) + "." + base64url(payload))       same secret signs and checks -> keep it only on the API serverRS256: signature = RSA-sign(privateKey, base64url(header) + "." + base64url(payload))       private key signs (login server), public key checks (any service)

Example 3 · What HS256 does (lab code)

Hs256Demo.javaJava
import java.nio.charset.StandardCharsets;import java.security.MessageDigest;import java.util.Base64;
import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;
/** What HS256 does, step by step. Lab code only: ShopLite signs with Spring Security's NimbusJwtEncoder. */public class Hs256Demo {
    static final Base64.Encoder B64URL = Base64.getUrlEncoder().withoutPadding();
    static String part(String json) {        return B64URL.encodeToString(json.getBytes(StandardCharsets.UTF_8));    }
    static String sign(String headerDotPayload, byte[] key) throws Exception {        Mac mac = Mac.getInstance("HmacSHA256");        mac.init(new SecretKeySpec(key, "HmacSHA256"));        return B64URL.encodeToString(mac.doFinal(headerDotPayload.getBytes(StandardCharsets.UTF_8)));    }
    /** Recompute the signature with our key and compare in constant time. */    static boolean verify(String token, byte[] key) throws Exception {        int lastDot = token.lastIndexOf('.');        String expected = sign(token.substring(0, lastDot), key);        return MessageDigest.isEqual(expected.getBytes(StandardCharsets.US_ASCII),                token.substring(lastDot + 1).getBytes(StandardCharsets.US_ASCII));    }
    public static void main(String[] args) throws Exception {        byte[] serverKey = "lab-key-for-hs256-demo-32-bytes!".getBytes(StandardCharsets.UTF_8);   // 32 bytes
        String header = part("{\"alg\":\"HS256\"}");        String payload = part("{\"sub\":\"2\",\"roles\":[\"CUSTOMER\"],\"exp\":1792138389}");        String token = header + "." + payload + "." + sign(header + "." + payload, serverKey);        System.out.println("Token:          " + token);        System.out.println("Valid?          " + verify(token, serverKey));
        // An attacker edits the payload to become ADMIN but cannot recompute the signature        String evilPayload = part("{\"sub\":\"2\",\"roles\":[\"ADMIN\"],\"exp\":1792138389}");        String tampered = header + "." + evilPayload + token.substring(token.lastIndexOf('.'));        System.out.println("Tampered valid? " + verify(tampered, serverKey));
        // Signed with a different key: also rejected        byte[] otherKey = "someone-elses-32-byte-secret-key".getBytes(StandardCharsets.UTF_8);        String foreign = header + "." + evilPayload + "." + sign(header + "." + evilPayload, otherKey);        System.out.println("Other key?      " + verify(foreign, serverKey));    }}
Output
Token:          eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIyIiwicm9sZXMiOlsiQ1VTVE9NRVIiXSwiZXhwIjoxNzkyMTM4Mzg5fQ.0Me1U3xQnAuF2x5qUyHxTiflAMXjzVR8KO-evP8NRBk
Valid?          true
Tampered valid? false
Other key?      false

What this code does

  • The signature is HMAC-SHA256 of the text header.payload, with the server's 32-byte key.
  • Changing CUSTOMER to ADMIN keeps the old signature, which no longer matches, so the check fails. Signing with a different key fails too.
  • MessageDigest.isEqual compares in constant time, so the time taken does not leak how many characters matched.

The header's alg names the method. HS256 fits ShopLite, where one API both issues and checks its own tokens; the cost is that every service that can check tokens can also create them. RS256 uses a key pair instead: a private key signs (only the login server has it) and a public key checks (any service may have it). Big systems with a separate login server, such as Google sign-in, use RS256 or its elliptic-curve cousin ES256.

The program above computes an HS256 signature with the JDK's Mac class only to show the idea. ShopLite never signs by hand: Spring Security's NimbusJwtEncoder and NimbusJwtDecoder do it, tested by thousands of projects.

Signed is not encrypted

A signed token still shows its payload to everyone. The program below reads a careless token's password and phone number without any key.

Example 4 · Anyone can read a payload

CarelessPayloadDemo.javaJava
import java.nio.charset.StandardCharsets;import java.util.Base64;
public class CarelessPayloadDemo {
    public static void main(String[] args) {        // A badly designed token copied from a shared screenshot. The attacker has no key at all.        String token = "eyJhbGciOiJIUzI1NiJ9"                + ".eyJzdWIiOiJyYXZpLmt1bWFyQGV4YW1wbGUuY29tIiwicGFzc3dvcmQiOiJyYXZpQDEyMyIs"                + "InBob25lIjoiOTg3NjU0MzIwMiIsImFhZGhhYXIiOiIxMjM0IDU2NzggOTAxMiJ9"                + ".c2lnbmF0dXJlLWlzLW5vdC1uZWVkZWQtdG8tcmVhZA";
        String payload = new String(Base64.getUrlDecoder().decode(token.split("\\.")[1]), StandardCharsets.UTF_8);        System.out.println("Anyone can read: " + payload);
        // What a safe ShopLite payload carries instead: ids and roles, nothing private        String safe = "{\"iss\":\"shoplite-api\",\"sub\":\"3\",\"roles\":[\"CUSTOMER\"],\"exp\":1792138389}";        System.out.println("Safe payload:    " + safe);    }}
Output
Anyone can read: {"sub":"ravi.kumar@example.com","password":"ravi@123","phone":"9876543202","aadhaar":"1234 5678 9012"}
Safe payload:    {"iss":"shoplite-api","sub":"3","roles":["CUSTOMER"],"exp":1792138389}

What this code does

  • The program has no key and ignores the signature, yet it prints the password, phone and Aadhaar number in the careless token.
  • A token is often copied into logs, bug reports and screenshots, so every claim in it should be safe to show.
  • The safe payload carries only the issuer, the user id, the roles and the expiry.

Signed means nobody can change the token without being caught; it does not mean nobody can read it. Browser extensions, proxies, log files and screenshots all show every claim.

So a token must never carry a password, an OTP, a card number or an Aadhaar number, and it should not carry an e-mail address or a phone number either. Put ids and roles in it and load anything else from the database; that is why ShopLite's sub is the user id "2", not asha.rao@example.com. A standard for encrypted tokens (JWE) exists, but most APIs keep the payload boring instead.

Find the bug

Find the unsafe claim

Select the line that is wrong.

This payload is meant for a customer's phone app.

Round 1 of 3

The alg none attack

The alg none attack forges a token whose header says {"alg":"none"} and whose signature is empty. A server that lets the token choose its own algorithm accepts it, and the attacker writes any claims they like.

Early JWT libraries believed the alg field inside the token. The program below forges an ADMIN token and tests it against a naive and a strict checker.

Example 5 · The alg none attack (lab code)

AlgNoneDemo.javaJava
import java.nio.charset.StandardCharsets;import java.security.MessageDigest;import java.util.Base64;
import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;
/** Why the server, not the token, must decide the algorithm. Lab code only. */public class AlgNoneDemo {
    static final Base64.Encoder ENC = Base64.getUrlEncoder().withoutPadding();    static final byte[] KEY = "lab-key-for-hs256-demo-32-bytes!".getBytes(StandardCharsets.UTF_8);
    static String hmac(String data) throws Exception {        Mac mac = Mac.getInstance("HmacSHA256");        mac.init(new SecretKeySpec(KEY, "HmacSHA256"));        return ENC.encodeToString(mac.doFinal(data.getBytes(StandardCharsets.UTF_8)));    }
    static String header(String token) {        return new String(Base64.getUrlDecoder().decode(token.split("\\.")[0]), StandardCharsets.UTF_8);    }
    static boolean signatureMatches(String token) throws Exception {        int dot = token.lastIndexOf('.');        return MessageDigest.isEqual(hmac(token.substring(0, dot)).getBytes(StandardCharsets.US_ASCII),                token.substring(dot + 1).getBytes(StandardCharsets.US_ASCII));    }
    /** BROKEN: trusts the alg written inside the token. */    static boolean naiveVerify(String token) throws Exception {        if (header(token).contains("\"alg\":\"none\"")) {            return true;                                   // "no signature needed", says the attacker        }        return signatureMatches(token);    }
    /** FIXED: the server expects HS256, always. Anything else is rejected before any check. */    static boolean strictVerify(String token) throws Exception {        if (!header(token).equals("{\"alg\":\"HS256\"}")) {            return false;        }        return signatureMatches(token);    }
    public static void main(String[] args) throws Exception {        String header = ENC.encodeToString("{\"alg\":\"none\"}".getBytes(StandardCharsets.UTF_8));        String payload = ENC.encodeToString("{\"sub\":\"2\",\"roles\":[\"ADMIN\"]}".getBytes(StandardCharsets.UTF_8));        String forged = header + "." + payload + ".";          // empty signature
        System.out.println("Forged token: " + forged);        System.out.println("Naive verifier accepts it?  " + naiveVerify(forged));        System.out.println("Strict verifier accepts it? " + strictVerify(forged));    }}
Output
Forged token: eyJhbGciOiJub25lIn0.eyJzdWIiOiIyIiwicm9sZXMiOlsiQURNSU4iXX0.
Naive verifier accepts it?  true
Strict verifier accepts it? false

What this code does

  • The forged token has {"alg":"none"}, an ADMIN role and an empty signature after the last dot.
  • naiveVerify lets the token choose the algorithm, so the attacker becomes an admin without any key.
  • strictVerify expects one fixed algorithm, so the forged token is rejected before any signature check.

The rule that stops this: the server decides the algorithm, never the token. A ShopLite server expects HS256 with its own key and rejects every token whose header says anything else. A related trick, sending an HS256 token to a server that expects RS256 so it uses the public key as an HMAC secret, is stopped by the same rule.

In ShopLite the rule is one line in a later lesson: NimbusJwtDecoder.withSecretKey(key).macAlgorithm(MacAlgorithm.HS256).

Next step

Check your understanding

12 quick questions