What Is JWT? JSON Web Tokens Explained With a Working Example
A JWT lets a server trust a request without looking anything up. Build one from scratch, try to tamper with it and watch it fail, then learn when tokens beat sessions and how to use them safely.
- A JWT is a compact, signed token with three parts: header, payload and signature.
- The signature proves a token has not been changed, so the server can trust it without a lookup.
- The payload is readable by anyone, so never put secrets in it.
- Tokens are hard to revoke, so keep them short-lived, and verify them with a trusted library.
After you log in, how does a server know that each later request is really from you? One popular answer is a JSON Web Token, or JWT, usually pronounced “jot”. It is a small, signed piece of data that the client sends with each request, and the server can check it without touching a database.
The fastest way to understand a JWT is to build one and then try to break it. We did that using only Python’s standard library, on Python 3.13, and the output below comes from that run. This code is for learning. In a real application, use a well-maintained library, because the details of verification are easy to get wrong.
What is a JWT?
JWT is an open standard, defined in RFC 7519, for passing claims between two parties as a compact string. A claim is simply a statement, such as “this user’s ID is 42”. Because the token is signed, the receiver can confirm who issued it and that nobody has altered it.
Think of a festival wristband. Staff at the gate check your ticket once and give you a band that is hard to fake. After that, each stall just looks at the band, with no need to phone the ticket office. A JWT works in much the same way for an API.
How JWT login works
- The user sends a username and password to the login endpoint.
- The server checks them and creates a signed token.
- The client stores the token.
- Each later request includes it, typically in a header:
Authorization: Bearer <token>. - The server verifies the signature and expiry, then reads the claims.
The main benefit is in step 5. The server does not have to look up a session, which is convenient when many services or servers need to check the same token. If you are new to APIs, start with what is an API.
The three parts of a JWT
A JWT looks like random text, but it is three Base64URL-encoded sections separated by dots. Here is one we generated:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.eyJzdWIiOiI0MiIsInJvbGUiOiJ1c2VyIiwiaWF0IjoxNzkzNTAwMDAwLCJleHAiOjE3OTM1MDA5MDB9
.7YfUDH_T-iDh8bMmUT8mmKYwOstzT8Ty--DTTAmQGWM
We have added line breaks to make it easier to read. Decoding the first two parts gives plain JSON:
Header: {"alg":"HS256","typ":"JWT"}
Payload: {"sub":"42","role":"user","iat":1793500000,"exp":1793500900}
| Part | Contains | Purpose |
|---|---|---|
| Header | Token type and signing algorithm | Says how to verify the token |
| Payload | Claims about the user or session | The actual information |
| Signature | A hash of the first two parts, using a key | Proves integrity and origin |
Standard claims
| Claim | Name | Meaning |
|---|---|---|
sub |
Subject | Who the token is about, usually a user ID |
iss |
Issuer | Who created the token |
aud |
Audience | Who the token is intended for |
exp |
Expiration | When the token stops being valid |
iat |
Issued at | When it was created |
nbf |
Not before | When it starts being valid |
jti |
JWT ID | A unique ID for this token |
You can also add custom claims, like role. Times are Unix timestamps, in seconds. Keep the payload small, since the token travels with every request.
Build one yourself
Creating a token involves encoding the two JSON parts, and then signing them with a secret using HMAC-SHA256:
import base64, hashlib, hmac, json
SECRET = b"demo-secret-do-not-use-in-production"
def b64url(data):
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
def sign(message):
return b64url(hmac.new(SECRET, message.encode(), hashlib.sha256).digest())
def create_token(payload):
header = {"alg": "HS256", "typ": "JWT"}
parts = [
b64url(json.dumps(header, separators=(",", ":")).encode()),
b64url(json.dumps(payload, separators=(",", ":")).encode()),
]
message = ".".join(parts)
return message + "." + sign(message)
Verification works by recalculating the signature, and comparing it with the one in the token. Only someone with the secret can produce a matching one:
def verify_token(token, now):
header, payload, signature = token.split(".")
expected = sign(header + "." + payload)
if not hmac.compare_digest(signature, expected):
raise ValueError("bad signature")
claims = json.loads(b64url_decode(payload))
if claims["exp"] < now:
raise ValueError("token expired")
return claims
A valid token returned its claims as expected. compare_digest is used since it runs in constant time, which avoids leaking information through timing differences.
Try to tamper with it
Suppose an attacker decodes the payload, changes "role":"user" to "role":"admin", encodes it again and keeps the old signature. We tried this, along with two other attacks:
| Attempt | Result |
|---|---|
| Changed the role to admin | bad signature |
| Used the token 1 second after expiry | token expired |
Set "alg":"none" and removed the signature |
bad signature |
That last attempt targets a real historic weakness. Some libraries once trusted the token’s own header, so an attacker could simply declare that no signature was needed. Our code always uses one fixed algorithm, which is why it was rejected. In a real library, always specify the algorithms you accept.
Signed, not encrypted
This is the most misunderstood point about JWTs. Our forged token was rejected, yet its contents were still perfectly readable:
{"sub":"42","role":"admin","iat":1793500000,"exp":1793500900}
Base64URL is an encoding, not encryption, and anybody can reverse it with no key at all. The signature stops people from changing the data, but not from reading it. So never put passwords, card numbers or private personal data in a JWT payload. If the contents must be hidden, use encrypted tokens (JWE), or just keep the data on the server.
HS256 vs RS256
| Aspect | HS256 | RS256 or ES256 |
|---|---|---|
| Type | Symmetric | Asymmetric |
| Keys | One shared secret | A private key signs, a public key verifies |
| Who can create tokens | Anyone holding the secret | Only the private key holder |
| Best for | One service, or a small trusted group | Many services, third parties, identity providers |
With asymmetric signing, other services can verify tokens without being able to mint their own, which limits the damage if one is compromised.
JWT vs sessions
JWTs are often presented as a modern replacement for sessions. In reality, each has trade-offs:
| Aspect | Server session | JWT |
|---|---|---|
| Where state lives | On the server | In the token |
| Lookup on each request | Usually | Not needed |
| Logging out or revoking | Easy, delete the session | Hard before expiry |
| Size per request | Small ID | Larger token (ours was 161 characters) |
| Across many services | Needs shared storage | Each can verify it directly |
| Changing permissions | Applies immediately | Old token stays valid until expiry |
For a traditional server-rendered website, a session cookie is often simpler and safer. JWTs tend to make more sense for APIs consumed by several services, or for mobile clients.
Tip: Do not choose JWT just because it sounds stateless. Many real systems add a denylist or a database check to support logout, which brings back the lookup that JWT was meant to avoid.
Where to store tokens in a browser
| Location | XSS risk | CSRF risk | Notes |
|---|---|---|---|
localStorage |
High, as scripts can read it | Low | Simple, but exposed to any injected script |
| HttpOnly cookie | Lower, as scripts cannot read it | Needs protection | Use Secure and SameSite |
| In-memory variable | Lower | Low | Lost on refresh, so it needs a refresh flow |
Many security guides favour HttpOnly, Secure, SameSite cookies for web apps. Whichever you pick, always use HTTPS. To send a token from JavaScript, see our JavaScript Fetch API tutorial.
Refresh tokens
Short expiry limits the damage from a stolen token, but nobody wants to log in every 15 minutes. The usual solution uses two tokens:
- Access token: short-lived, such as minutes, and sent with every API request.
- Refresh token: longer-lived, stored more carefully and used only to obtain new access tokens.
The server keeps track of refresh tokens, so it can revoke them, which gives you a practical logout. Rotating them on each use also helps you detect theft, because a stolen old token gets replayed.
Common security mistakes
- Decoding without verifying. Reading a payload does not make it trustworthy. Always check the signature.
- Accepting any algorithm. Set an explicit list of allowed algorithms.
- Using a weak secret. Short secrets can be cracked offline. Use a long random value, and keep it out of source control.
- Skipping expiry. Tokens with no
expcan work forever if stolen. - Not checking
issandaud. Otherwise a token issued for one service may be accepted by another. - Trusting stale claims. A role inside a token can be out of date until it expires.
- Logging tokens. Anyone reading your logs could reuse them.
- Not testing failure paths. Add tests for expired and modified tokens, as well as valid ones. Our API testing with Postman guide can help.
Final thoughts
A JWT is signed data that a server can trust without a lookup, not a secret container and not an automatic upgrade over sessions. Use short expiry, verify everything with a maintained library, and keep private data out of the payload. To see it for yourself, run a small script like ours, change one character of a token and watch verification fail.
Frequently asked questions
What is a JWT used for?
JWTs are mostly used for authentication and authorization in APIs. After login, a client sends the token with each request, and the server verifies it to identify the user.
Is a JWT encrypted?
Usually not. A standard JWT is signed and encoded, so anyone can read its payload. The signature only prevents changes. Encrypted tokens use a related format called JWE.
How long should a JWT last?
Access tokens are commonly short-lived, often minutes rather than days. Pair them with a refresh token, so users do not have to log in constantly.
Can a JWT be revoked?
Not by itself, as it stays valid until it expires. Revocation requires server-side tracking, such as a denylist, which removes some of the stateless benefit.
Is JWT better than sessions?
Neither is always better. Sessions are simpler to revoke and suit many websites, while JWTs suit APIs and services that need to verify identity independently.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.