DEV Community

Cover image for JWT: the theory before the code
Kevin
Kevin

Posted on

JWT: the theory before the code

What is a JWT?

JWT stands for JSON Web Token. It's a way to pass information between two parties in a compact, self-contained format. The key idea is that the token itself carries the data the server doesn't need to store anything to validate it.

The three parts

A JWT looks like this:

Three base64 encoded strings joined by dots.

Header contains the token type and the signing algorithm (usually HS256 or RS256).

Payload is the actual data, called "claims". Things like user id, role, expiration time.

Signature is created by combining the header, payload, and a secret key. This is what makes the token trustworthy.

How trust works

When your server receives a JWT, it doesn't look up the user in a database to verify the request. Instead, it recalculates the signature using the secret key and checks if it matches the one in the token.

If someone tampers with the payload, the signature won't match. That's the whole point.

Claims

The payload is made of claims, statements about the user or the session. There are registered ones like sub (subject, usually the user id), exp (expiration timestamp), and iat (issued at). You can also add your own custom claims like role or plan.

What JWT is not

JWT is not encryption. The payload is encoded, not encrypted. Anyone can decode it and read the contents. Never put sensitive data like passwords in a JWT.

What it does guarantee is integrity: you can trust that the data hasn't been modified since it was signed.

Top comments (0)