Authentication with JWT

Authentication with JWT in Node.js: At a multi-day music festival you do not present your ticket and photo ID every time you walk up to a stage.

The Analogy: The Tamper-Evident Festival Wristband

At a multi-day music festival you do not present your ticket and photo ID every time you walk up to a stage. At the main gate on the first day, staff check your paperwork once and clip a wristband onto you: a printed band stamped with your access tier, such as general or VIP, and the date on which it stops working. After that, every stage steward simply glances at the band and waves you through. The expensive check happens a single time at the gate, and the band becomes the proof you carry everywhere.

The band is deliberately readable by anyone. A steward reads your tier and expiry at a glance without phoning the box office, and so can you, and so can a stranger standing next to you. There is no secret hidden in the printing; the information is in plain sight. What prevents forgery is not secrecy but a tamper-evident feature: a foil hologram pressed into the band with festival equipment that an ordinary copy shop cannot reproduce. Anyone may read the band freely; what they cannot do is manufacture a genuine stamp.

This is what makes the steward's job fast and stateless. They never phone a central list of attendees; they inspect the band, confirm the hologram is intact and genuine, read the tier and the date, and decide on the spot. The festival's authority was baked into the stamp at the moment of issue, so thousands of stewards at dozens of stages can each verify independently, with nothing but the band in front of them and the knowledge of what a real stamp looks like.

The weakness is the exact flip side of that convenience. The band is a bearer credential: whoever physically holds a genuine, unexpired, correctly stamped band gets in, no further questions asked. If someone slips their VIP band off and hands it to a friend, or it is lifted from a bag, the new holder walks straight into the VIP area, because the stamp is real and the date has not passed. Nothing on the band ties it to the original person, and a steward who checks only the stamp cannot tell. The band stays valid until its printed expiry, so a stolen one is a working key for the rest of its short life. In JWT terms, a leaked token is usable by anyone who holds it until it expires, which is precisely why tokens are signed rather than treated as secret, kept short-lived, and transmitted only over TLS.


Syntax or Core Structure

A JSON Web Token is three base64url-encoded parts joined by dots: a header naming the algorithm, a payload of claims, and a signature over the first two. The signature is what the server can recompute and check; the header and payload are merely encoded, not encrypted, so anyone can read them. The whole token is a single self-contained string, which is what lets it be handed back on every request in an Authorization: Bearer header and verified without a database lookup.

The Three Parts

A token is written as header.payload.signature, three base64url segments separated by dots, and you can see all three in the sample token printed further below. Base64url is chosen over plain base64 because the result travels inside URLs and HTTP headers: it swaps the + and / characters for - and _ and drops the trailing padding, so a token can be dropped into an Authorization header without any further escaping. The two dots are literal separators, not encoded data, which is why splitting a token on the dot character cleanly recovers its three parts. The header and payload decode back to readable JSON; only the signature is an opaque HMAC digest rather than encoded text you can read.

Signing and Verifying

const jwt = require('jsonwebtoken');
const secret = 'festival-secret';

const token = jwt.sign({ tier: 'vip', holder: 'ada' }, secret, { noTimestamp: true });
const decoded = jwt.verify(token, secret);   // throws if the signature is wrong

Reading Without the Secret

const claims = jwt.decode(token);   // no secret needed, no signature check

Technical Depth: Stamp, Claims, and Verification

Anatomy of a Token

The three parts each carry a distinct role, and only the signature depends on the secret. The header is tiny: it names the signing algorithm, such as HS256, and the token type, so the verifier knows how to recompute the signature. The payload holds the claims, the actual statements the token is making about its bearer. The signature is an HMAC computed over the encoded header and payload together with the secret, which is why changing even one character of either part invalidates it: the recomputed HMAC no longer matches the one attached.

PartContentsProtected by the secret?
Headeralgorithm and token typeNo, only encoded
Payloadthe claims such as tier and expiryNo, only encoded
SignatureHMAC of header and payloadYes, requires the secret

Signed, Not Secret

Because the payload is only base64url-encoded, jwt.decode reads it with no secret and no signature check, exactly like reading the printing on a wristband. Signing a fixed payload with noTimestamp makes the token deterministic, so the same input always yields the same string:

const token = jwt.sign({ tier: 'vip', holder: 'ada' }, secret, { noTimestamp: true });
console.log('token: ' + token);
const decoded = jwt.verify(token, secret);
console.log('verified tier: ' + decoded.tier + ' holder: ' + decoded.holder);
const readable = jwt.decode(token);
console.log('decoded without secret: ' + readable.tier + ' ' + readable.holder);

The token is three dot-separated segments; verification returns the claims, and decode returns the same claims without any secret at all:

Output:

token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0aWVyIjoidmlwIiwiaG9sZGVyIjoiYWRhIn0.DomatQjt8uCB5-zzO4RHLnoHip0xsUogTUp2C_GORjk
verified tier: vip holder: ada
decoded without secret: vip ada

Standard Claims

The payload can hold your own data plus a set of registered claims that libraries understand and treat specially. These have short, three-letter names by convention, and jsonwebtoken acts on some of them automatically during verify while leaving others purely informational for your own code to interpret. The single most important one is exp, because it is the only claim in this table that the library will reject a token over without being asked.

ClaimMeaningChecked by verify
expexpiry time as a unix timestampyes, rejects if past
iatissued-at timeno, informational
subsubject, usually a user idno, up to you
ississuer of the tokenonly if you demand it

Real World Example: A Forged Stamp and an Expired Band

Two failures matter most in practice, and both throw at verification time. The first is a forged stamp: a token verified with the wrong secret. The server recomputes the signature with its own secret, finds it does not match, and rejects the token before trusting a single claim.

const token = jwt.sign({ tier: 'vip', holder: 'ada' }, secret, { noTimestamp: true });
try {
  jwt.verify(token, 'forged-secret');
} catch (e) {
  console.log('name: ' + e.name);
  console.log('message: ' + e.message);
}

A wrong secret is caught as a signature failure, the digital equivalent of a hologram that does not match the festival's own:

Output:

name: JsonWebTokenError
message: invalid signature

The second failure is an expired band. This token carries an exp set to a fixed time in the past, so even though its signature is perfectly valid, verify refuses it and reports when it lapsed:

const token = jwt.sign({ tier: 'ga', exp: 1000000000 }, secret, { noTimestamp: true });
try {
  jwt.verify(token, secret);
} catch (e) {
  console.log('name: ' + e.name);
  console.log('expiredAt: ' + Math.floor(e.expiredAt.getTime() / 1000));
}

The signature is genuine, but the printed date has passed, so entry is refused:

Output:

name: TokenExpiredError
expiredAt: 1000000000

Those two failures are isolated scripts, useful for reading an error name in the clear but far from how a server actually spends a token. In a running application the same two checks, a valid signature and an unexpired exp, live inside one piece of middleware that every protected route shares. The gate reads the wristband from the Authorization header, hands the raw string to verify, and on success attaches the decoded holder to the request so the handler downstream can trust it without repeating the work:

function requireBand(req, res, next) {
  const header = req.headers['authorization'] || '';
  const token = header.replace('Bearer ', '');
  if (!token) {
    return res.status(401).json({ error: 'no band' });
  }
  try {
    req.holder = jwt.verify(token, secret);
    next();
  } catch (e) {
    res.status(401).json({ error: e.name });
  }
}

app.get('/vip', requireBand, function (req, res) {
  res.json({ welcome: req.holder.holder, tier: req.holder.tier });
});

Three requests exercise every branch of the gate. A request with no header never reaches verify: the middleware turns it away at the door with a plain no-band message. A request carrying a made-up string does reach verify, which recomputes the signature over the forged header and payload, finds no match against the festival secret, and surfaces the JsonWebTokenError name. A request carrying the exact band handed out by the /issued route passes cleanly, and the handler answers with the holder's name and tier lifted straight from the verified claims:

Output:

no header    -> {"error":"no band"} [401]
garbage band -> {"error":"JsonWebTokenError"} [401]
valid band   -> {"welcome":"ada","tier":"vip"} [200]

Notice that the two rejections carry the identical 401 status with different bodies, and the handler for /vip never runs until requireBand calls next: an unverified request cannot leak so much as a tier. The holder object on the request is the decoded payload, so req.holder.holder reads the holder claim while req.holder.tier reads the tier, exactly the values that were signed. That is the whole point of the stamp: the handler trusts req.holder because the middleware already proved the signature, not because it re-checked anything itself.

The design flaw to name is the bearer nature of the token, straight from the analogy. Between issue and expiry there is no built-in way to revoke a single token: a leaked one works until exp, and shortening exp to limit the damage forces users to re-authenticate more often. Real systems paper over this with short-lived access tokens plus a separate refresh token and a server-side deny-list for emergencies, but the core token itself, once signed, trusts whoever holds it. Putting secrets in the payload is the other classic error: since anyone can decode it, the payload is a public postcard, not a sealed envelope.


Common Mistakes

  1. Thinking a JWT is encrypted. The payload is only base64url-encoded, so anyone can decode and read it. Never place passwords, keys, or other secrets in the claims.
  1. Trusting decode instead of verify. jwt.decode does not check the signature, so relying on it accepts forged tokens. Always use jwt.verify with the secret on any token you act on.
  1. Using a weak or hard-coded secret. A short or committed secret lets an attacker forge valid signatures. Use a long random secret from configuration, never a literal in the source.
  1. Omitting an expiry. A token with no exp is valid forever, so a single leak is permanent. Always set a short expiry so a stolen token stops working on its own.
  1. Storing tokens in localStorage without care. Tokens in localStorage are readable by any injected script, making XSS a token theft. Prefer httpOnly cookies or guard the app against script injection.
  1. Accepting the alg from the token header. Honoring the token's own alg field enables the none-algorithm and algorithm-confusion attacks. Pin the expected algorithm in the verify options instead.
  1. Treating a valid signature as authorization. A genuine token proves who the holder claims to be, not what they may do; you still must check the tier or role before granting access to a protected action.
  1. Ignoring clock skew. Verifying exp across servers with unsynchronized clocks causes spurious expiries or late acceptances. Keep clocks in sync and allow a small tolerance if the library supports it.
  1. Assuming you can log a user out by deleting the client token. Because the token is a bearer credential, a copy already taken still works until exp; genuine revocation needs a server-side deny-list or short lifetimes with refresh.

Best Practices

  • Verify, never merely decode. Run every incoming token through jwt.verify with the secret and the expected algorithm so a forged or tampered token is rejected before any claim is trusted.
  • Keep access tokens short-lived. Set a small exp and pair it with a refresh token, so a leaked access token expires quickly while users are not forced to log in constantly.
  • Pin the algorithm. Pass an explicit algorithms list to verify so the server, not the attacker-controlled header, decides how signatures are checked.
  • Store the secret in configuration. Load a long random signing secret from an environment variable or secret manager, and rotate it rather than hard-coding it in the repository.
  • Put only non-sensitive claims in the payload. Treat the payload as public and include just an id, a tier, and timing claims, keeping anything secret on the server keyed by the subject.
  • Transmit tokens only over TLS. Send tokens exclusively over HTTPS so a bearer credential cannot be read off the wire, and prefer httpOnly cookies to shield them from client scripts.
  • Check authorization separately from authentication. After verifying the token, still confirm the tier or role for the specific action, since a valid token is identity, not permission.
  • Plan for revocation. Maintain a deny-list or a token-version check on the server for the cases where you must invalidate a token before its natural expiry.

Practice Exercises

  1. Sign and verify a token. Create a token with a small payload and a secret using noTimestamp, verify it with the same secret, and print the claims to confirm they survive the round trip.
  1. Read a token without the secret. Call jwt.decode on the token from the first exercise and print a claim, then explain in one sentence why this proves the payload is not secret.
  1. Forge and detect. Verify a valid token with a different secret, catch the error, and print its name and message to show that a wrong secret is caught as an invalid signature.
  1. Expire a band on purpose. Sign a token whose exp is a fixed time in the past, verify it, and catch the TokenExpiredError, printing the moment it lapsed to demonstrate expiry enforcement.