bytekit

What Is a JWT? JSON Web Tokens Explained Simply

The three parts of a JSON Web Token, how the signature actually protects it, the checks your server must make, and the mistakes that turn JWTs into a security hole.

By Tushar Dowerah · · 8 min read

If you have worked with a modern login system, an API or a single sign-on provider, you have met strings like this one:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzQyIiwibmFtZSI6IkFkYSBMb3ZlbGFjZSIsImlhdCI6MTcwMDAwMDAwMCwiZXhwIjoxNzAwMDAzNjAwfQ.c2lnbmF0dXJl

That is a JSON Web Token, or JWT, usually pronounced “jot”. It looks like random noise, but it is a carefully structured message. This guide explains what is inside, how it is protected, and the handful of rules that separate a secure JWT setup from a broken one.

The problem JWTs solve

HTTP has no memory. Every request your browser sends to a server arrives on its own, so after you log in, the server needs a way to recognise you on the next request, and the one after that.

The classic answer is a session: the server stores “session 8f3a… belongs to user 42” in a database and gives your browser a cookie with that random ID. On every request, the server looks the ID up.

A JWT turns this around. Instead of a random ID that points to data on the server, the token carries the data itself, such as the user ID, their role and an expiry time, and is signed so it cannot be changed. Any server that knows the signing key can check the token and trust what it says, without asking a central database. That is useful when many services, or servers in different regions, all need to know who is calling them.

The three parts of a token

A JWT is three pieces of text joined by dots: header.payload.signature. Each piece is encoded with Base64URL, a variant of Base64 that uses only characters safe in web addresses.

1. The header

The first part, eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9, decodes to:

{ "alg": "HS256", "typ": "JWT" }

It says which algorithm signed the token (here HMAC with SHA-256) and that this is a JWT. The header can also include a kid (key ID) that tells the server which of several keys to use.

2. The payload

The second part decodes to the actual message:

{
  "sub": "user_42",
  "name": "Ada Lovelace",
  "iat": 1700000000,
  "exp": 1700003600
}

3. The signature

The third part is a cryptographic signature over the first two. It is the only part that cannot be produced without the key, and it is what lets the server detect any change to the header or payload.

JWT DecoderPaste a token to see its header, payload and expiry in plain language. It is decoded on your device and never uploaded.

Claims: what goes in the payload

Each field in the payload is called a claim. The JWT standard (RFC 7519) defines a few short, registered names that most libraries understand:

ClaimNameMeaning
issIssuerWho created the token, for example https://auth.example.com
subSubjectWho the token is about, usually a user ID
audAudienceWhich service the token is meant for
expExpiration timeAfter this moment the token must be rejected
nbfNot beforeBefore this moment the token must be rejected
iatIssued atWhen the token was created
jtiJWT IDA unique ID, useful for blocking a single token

Times are written as Unix timestamps: the number of seconds since 1 January 1970, UTC. In the example, iat is 1700000000, which is 14 November 2023 at 22:13:20 UTC, and exp is exactly 3,600 seconds, or one hour, later. A classic bug is creating these in milliseconds, which puts the expiry tens of thousands of years in the future.

Unix Timestamp ConverterTurn exp and iat values into readable dates in your own time zone, and back again.

You can add your own claims too, such as role or tenant. Keep the payload small, because the token is sent with every single request.

How the signature works

To sign a token, the server takes the encoded header and payload, joins them with a dot, and signs that exact text. There are two families of algorithms.

Shared secret: HS256

signature = HMAC-SHA256(
  base64url(header) + "." + base64url(payload),
  secret
)

The same secret both creates and checks the signature. It is simple and fast, and fine when one application issues and verifies its own tokens. The secret must be long and random, at least 32 bytes, because a short secret can be brute-forced offline from any token.

Key pair: RS256 and ES256

With RS256 (RSA) or ES256 (elliptic curve), a private key signs and a matching public key verifies. Only the login service holds the private key, while any number of other services can verify tokens with the public key, which is safe to share. Identity providers such as Google, Microsoft and Auth0 work this way and publish their public keys at a JWKS (JSON Web Key Set) address.

Either way, if an attacker changes even one character of the payload, say "role": "user" to "role": "admin", the signature no longer matches and the server rejects the token.

What your server must check

Nearly every real-world JWT vulnerability comes from skipping one of these checks. Use a well-maintained library for your language, and make sure it is configured to do all of them.

  1. Verify the signature with an algorithm you choose. Tell the library exactly which algorithm to expect, for example only RS256. Never let the token’s own header decide. Old libraries that trusted the header could be fooled by "alg": "none", meaning no signature at all, or by an attacker signing an HS256 token with the server’s public RSA key used as if it were a shared secret.
  2. Check the expiry. Reject tokens whose exp has passed, and those whose nbf is still in the future. Allow at most a minute or so of clock difference between servers.
  3. Check the issuer and audience. A token issued for your mobile app’s API should not be accepted by your admin API, even if both trust the same login provider.
  4. Decide what to trust. The payload tells you who the user is. For critical actions, such as changing an email address or making a payment, still check the database for their current permissions.

Where to store a JWT in the browser

This is one of the most debated questions in web security, and both common answers have trade-offs.

WhereStrengthWeakness
HttpOnly, Secure, SameSite cookieJavaScript cannot read it, so a cross-site scripting (XSS) bug cannot steal the tokenSent automatically, so you must protect against cross-site request forgery (SameSite helps a lot)
localStorage or sessionStorageSimple, and easy to send to APIs on other domainsAny script on the page can read it, so a single XSS bug or a compromised third-party script leaks it
In memory onlyHard to steal and gone when the tab closesLost on refresh, so it needs a refresh token in a cookie alongside

For a typical website talking to its own backend, an HttpOnly cookie with Secure and SameSite=Lax or Strict is the safer default. Whatever you choose, keep tokens short-lived and treat any XSS bug as critical, because it can act as the user even when it cannot read the token.

Logging out, expiry and refresh tokens

A JWT’s greatest strength, that servers do not need to look anything up, is also its main weakness: once issued, a token stays valid until it expires. Deleting it from the browser on logout does not stop a stolen copy from working.

Most systems handle this with two tokens:

  • A short-lived access token, typically valid for 5 to 15 minutes, sent with each API request.
  • A long-lived refresh token, stored safely and tracked on the server, used only to get a new access token. Logging out, or a password change, deletes the refresh token on the server, so the session ends within minutes.

Rotating the refresh token on every use, and treating reuse of an old one as a sign of theft, adds another layer. If you need instant revocation, keep a short block list of jti values until those tokens would expire anyway.

When a JWT is the wrong choice

JWTs shine when several services need to verify identity independently, for single sign-on, and for short-lived, signed messages such as email verification links. For a single website with one backend, a classic server-side session cookie is often simpler: logout works instantly, there is nothing to decode, and the cookie is tiny.

A few quick rules of thumb:

  • Do not use a JWT as a general-purpose, long-lived session with no way to revoke it.
  • Do not store a growing list of permissions or profile data in the payload.
  • Do not invent your own signing scheme. Use a maintained library and standard algorithms.
  • Do log and inspect tokens while debugging, but use test tokens, and never paste a live production token into a website you do not control.

Once you understand that a JWT is just signed, readable JSON, the rest follows: check the signature properly, keep the contents boring, and keep the lifetime short.

Base64 Encoder & DecoderDecode or encode Base64 and Base64URL text, the encoding used by each part of a JWT.

Written by Tushar Dowerah

Independent software developer from Dibrugarh, Assam, India, coding since 2020 and building ByteKit’s free, private tools. Spotted a mistake or have a question? Send a message.

Keep reading

All posts