Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 39 ยท Tokens, JWT and OAuth

JSON Web Tokens (JWT) Explained

Learn what a JSON Web Token is, how header, payload and signature fit together, and build and verify an HS256 JWT by hand with node:crypto.

A JSON Web Token (JWT, pronounced "jot") is a compact string that carries a few claims about a user, such as who they are and when the token expires. The server signs the string, so any later change is detectable. Because the token carries its own data, an API can check it without looking anything up in a database. That is why JWTs are popular for stateless REST APIs.

In this lesson you will take a token apart, build one by hand with only node:crypto, and verify it. Doing it by hand removes the magic: a JWT is three Base64URL strings joined by dots, plus one HMAC.

A JWT has three parts

Header Algorithm and token type.
Payload Claims about the user.
Signature Proves nobody changed it.

Joined as header.payload.signature

1 / 2

Anatomy of a token

A JWT looks like this, with line breaks added for reading:

TEXT
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.eyJzdWIiOiI0MiIsInJvbGUiOiJlZGl0b3IifQ
.k3Qm...signature...

Each part is JSON turned into Base64URL: the Base64 alphabet with - and _ instead of + and /, and no = padding. That makes it safe inside URLs and HTTP headers.

Part Example (decoded) Purpose
Header {"alg":"HS256","typ":"JWT"} Which algorithm signed the token
Payload {"sub":"42","role":"editor","exp":1767225600} The claims
Signature 32 bytes for HS256 HMAC of header.payload with a secret

A JWT is signed, not encrypted. Anyone who holds the token can read the payload by Base64URL-decoding it. Never put passwords, card numbers or other secrets in it.

Registered claims

The JWT standard (RFC 7519) reserves a few short claim names. You can add your own, but use these where they fit.

Claim Name Meaning
sub Subject Who the token is about, usually a user ID
iss Issuer Who created the token
aud Audience Which API the token is for
exp Expiration time Seconds since 1970; the token is invalid after this
nbf Not before The token is invalid before this time
iat Issued at When the token was created
jti JWT ID A unique ID, useful for revocation lists

Times are seconds since the Unix epoch, not milliseconds. Mixing them up is a classic bug: Date.now() returns milliseconds, so divide by 1000.

Build a token by hand

HS256 means "HMAC with SHA-256". The server and the verifier share one secret. The signature is HMAC(secret, base64url(header) + "." + base64url(payload)). This demo uses a fixed payload and secret, so the output is the same on every run.

Node.js Sign a JWT with node:crypto

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that decoding the header and payload needs no secret at all. Only the signature depends on it.

Verify a token

Verification repeats the same computation and compares the result with the signature that arrived. Three rules matter:

  1. Recompute the signature yourself and compare it with timingSafeEqual, which takes the same time whether or not the first bytes match. A plain === can leak information through timing.
  2. Check the algorithm in the header against the one you expect. Never let the token choose.
  3. Check the claims after the signature: exp, nbf, iss and aud. A valid signature on an expired token is still a rejected token.
Node.js Verify, tamper and expire

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The forged token fails because the signature was computed over the old payload. Changing even one character of the payload changes the HMAC completely.

Sending a token to the API

After login the client keeps the token and sends it in the Authorization header with the Bearer scheme:

HTTP
GET /api/notes HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

A missing, malformed or invalid token gets 401 Unauthorized with a WWW-Authenticate: Bearer header. A valid token whose user is not allowed to do the action gets 403 Forbidden.

HS256 versus RS256 and ES256

Algorithm Keys Use when
HS256 One shared secret One service both signs and verifies
RS256 RSA private key signs, public key verifies Many services verify tokens but only one issues them
ES256 Elliptic-curve key pair Like RS256, with shorter keys and signatures

With a key pair you can publish the public key (often as a JWKS document) so every service verifies tokens without being able to forge them. You will try this in JWT Pitfalls and Best Practices.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What are the three parts of a JWT, in order?

    A JWT is header.payload.signature, each part Base64URL-encoded and joined by dots.
  2. 2. Why should you not store a password in a JWT payload?

    Signing proves integrity, not secrecy. Base64URL decoding needs no key.
  3. 3. Why compare signatures with timingSafeEqual instead of ===?

    Constant-time comparison takes the same time however many leading bytes match, so attackers learn nothing from response timing.
  4. 4. The exp claim is 1767229200. What unit is it in?

    JWT time claims are NumericDate values, which are seconds since the Unix epoch. Date.now() returns milliseconds, so divide by 1000.
  5. 5. An attacker changes role from viewer to admin in a signed token's payload. What happens at verification?

    The signature covers header and payload. Without the secret the attacker cannot produce a matching signature.

Summary

  • A JWT is header.payload.signature, each part Base64URL text, with the first two being JSON.
  • HS256 signs header.payload with HMAC-SHA-256 and a shared secret.
  • The payload is readable by anyone, so keep secrets out of it.
  • Verify in order: structure, expected algorithm, signature (constant-time), then claims such as exp.
  • Send the token in Authorization: Bearer ...; answer failures with 401, and permission problems with 403.
  • Use RS256 or ES256 when several services must verify tokens but only one may issue them.

Next: JWT Pitfalls and Best Practices