JWT it down

By Daniel Samson · 2024-03-08

If you've got more than one service and you don't fancy every one of them phoning a central session store on every request, you want JWTs. Here's what they are and how to use them without shooting yourself in the foot.

What is a JWT?

A JSON Web Token is three base64url-encoded parts joined by dots: a header, a payload, and a signature. The header says how it was signed. The payload carries the claims — who the user is, what they can do, when it expires. The signature proves the first two parts haven't been tampered with.

Crucial point that trips everyone up: a JWT is signed, not encrypted. Anyone can read the payload. Don't put secrets in it.

Why it's good for distributed authorization

Because it's self-contained and signed, any service can verify a token on its own — no round trip to an auth server, no shared session table. The claims travel with the request. A user's identity and permissions arrive already attached, and each service just checks the signature and reads what it needs.

How verification actually works

Use asymmetric signing (RS256 or ES256). The auth server holds the private key and signs tokens. Every other service holds only the public key and verifies. The signing secret never leaves the one service that mints tokens, and you can rotate keys via a published JWKS endpoint.

The traps, and how to dodge them

  • You can't easily revoke a JWT. Keep them short-lived (minutes, not days) and pair them with a refresh token for the "log me out everywhere" story.

  • Pin the algorithm. The classic alg: none attack works because lazy libraries trust the header. Don't.

  • Always check expiry, issuer, and audience. A valid signature on a token meant for a different service is still the wrong token.

  • Keep the payload small. It's sent on every request.

Get those right and JWTs let you spread authorization across a fleet of services without a chatty, single-point-of-failure session store. Get them wrong and you've built a lovely, stateless way to never log anyone out.