You log in to a web app, and from that moment your browser sends a long string starting with eyJ along with every request. Paste that string into any online tool and you suddenly see your username, your role and an expiry date, in plain text.
What is JWT? A JWT (JSON Web Token, pronounced “jot”) is a compact, digitally signed data package made of three parts: a header, a payload with claims such as the user ID and expiry time, and a signature. The server issues the token at login, the client sends it with every request, and the server uses the signature to check that nobody has changed the content. One thing to keep in mind from the start: a JWT is signed, but usually not encrypted. Anyone who sees the token can read it.
In this article we explain JWT from scratch: how a token is structured, how to decode one yourself, when it beats a classic session and where the well-known traps are. We didn’t just read the spec. On 19 November 2026 we used the two most popular Node.js libraries (jsonwebtoken 9.0.3 and jose 6.2.18) on our own server to forge tokens, tamper with them, let them expire and crack a weak secret. A few of the results are worth knowing for anyone who uses JWTs.
A recent (November 2026) walkthrough by TechPrep covering authentication vs. authorization and the three parts of a JWT. Further down there is a broader video on sessions, JWT and OAuth.
What is JWT? The short answer in five sentences
- A JWT is a text token made of three Base64URL-encoded parts separated by dots:
header.payload.signature. - The payload contains so-called claims, statements like “user 42”, “role: user”, “valid until 08:18”.
- The signature is computed from the header, the payload and a secret key. Change a single character in the payload and the signature no longer matches.
- That’s why the server doesn’t need to remember anything: it checks the signature and knows the content came from itself. This is called stateless.
- Because the content is only encoded and not encrypted, secrets don’t belong in a JWT. And because the server keeps no record, an issued token can’t easily be revoked.
The underlying standard is RFC 7519 from 2015. Signing is defined in RFC 7515 (JWS), encryption in RFC 7516 (JWE). When people say “JWT” in everyday use, they almost always mean a signed, unencrypted token, technically a JWS.
How is a JWT structured? Header, payload and signature
We created this token for our test with jsonwebtoken (secret: geheim, valid for 15 minutes):
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI0MiIsIm5hbWUiOiJBbm5hIiwicm9sZSI6InVzZXIiLCJpYXQiOjE3OTUwNzU0MDgsImV4cCI6MTc5NTA3NjMwOH0.85aOKP5abpyjvNv8jmqqXj1Eah1osQOUS9o83G4I0C4
180 characters, two dots, three parts. Decoded:
1. Header
{"alg":"HS256","typ":"JWT"}
The header says how the token is signed. HS256 means HMAC with SHA-256, i.e. a shared secret. By the way, the reason almost every JWT starts with eyJ is right here: {" followed by a letter always encodes to eyJ in Base64.
2. Payload
{"sub":"42","name":"Anna","role":"user","iat":1795075408,"exp":1795076308}
These are the claims. Some names are defined by the standard (“registered claims”):
| Claim | Meaning | Example |
|---|---|---|
sub | Subject: who the token is about | user ID 42 |
iat | Issued at (Unix seconds) | 1795075408 |
exp | Expiration | 1795076308 = 19 Nov 2026, 08:18:28 UTC |
nbf | Not before | rarely used |
iss | Issuer | https://auth.example.com |
aud | Audience: who it’s meant for | api |
jti | JWT ID: unique identifier | useful for deny lists |
Everything else (name, role) is a custom claim chosen by the application.
3. Signature
85aOKP5abpyjvNv8jmqqXj1Eah1osQOUS9o83G4I0C4
This is HMAC-SHA256(secret, base64url(header) + "." + base64url(payload)), Base64URL-encoded again. Only someone who knows the secret can produce these 43 characters.

Decoding a JWT yourself, without an online tool
Many tutorials send you to jwt.io or a similar site to decode tokens. That works, but you’re pasting a real, valid login token into someone else’s website. Fine for a test token, not a great idea for a production token from your admin area. You can decode locally, with one small trap.
The obvious base64 approach half fails:
$ echo "$TOKEN" | cut -d. -f2 | base64 -d
{"sub":"42","name":"Anna","role":"user","iat":1795075408,"exp":1795076308}base64: invalid input
You do get the output, but base64 reports an error and exits with code 1, which kills a script running with set -e. The reason: JWT uses Base64URL, where + and / are replaced by - and _ and the trailing = padding is dropped. In our test, even basenc --base64url -d from GNU coreutils complained about the missing padding.
Reliable with Python (available on every Linux distribution):
python3 -c "import base64,sys;p=sys.argv[1].split('.')[1];print(base64.urlsafe_b64decode(p+'='*(-len(p)%4)).decode())" "$TOKEN"
In Node.js:
const [h, p] = token.split('.');
console.log(JSON.parse(Buffer.from(p, 'base64url').toString()));
In the browser (DevTools console):
JSON.parse(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')))
To read the expiry time: date -u -d @1795076308.
The key takeaway of this section: reading a JWT requires no key. Anyone who intercepts the token, finds it in a log or sees it in LocalStorage can read its content. So passwords, addresses, account numbers and internal details do not belong in the payload.
How does JWT authentication work?
The typical flow in a web app or API:
- The user sends username and password to
/login. - The server checks them and creates a JWT with
sub, roles andexp. - The client stores the token (cookie, memory or LocalStorage) and sends it with every request, usually as a header:
Authorization: Bearer eyJ…. - On every request, the server checks the signature and the expiry. If both are fine, it trusts the content without querying the database.
That’s exactly how our own agent game server works: at login it issues an HS256 token containing user ID, name and type, valid for 30 days. As a test we sent the same token once without a signature (just header.payload.). Response: HTTP 401. That’s how it should be.
Access tokens and refresh tokens
Since a JWT is hard to revoke (more on that below), practice has settled on two tokens:
- Access token: a short-lived JWT, typically 5 to 15 minutes, sent with every request.
- Refresh token: a long-lived, usually random token that the server stores in the database. The client uses it to get a new access token when the old one expires.
That gives you both: most requests run without a database lookup, and you can still lock a user out by deleting their refresh token. They’re out within 15 minutes at the latest.
Anton Putra walks through Basic auth, sessions, API keys, bearer tokens, JWT and OAuth one request at a time (November 2026).
Our test: what happens when you tamper with a JWT?
For the test we installed the two most widely used JavaScript libraries in a throwaway folder on our server (Node.js 22.23.5): jsonwebtoken 9.0.3 (the classic from Auth0) and jose 6.2.18 (modern, zero dependencies). For one comparison we also added the old version jsonwebtoken 8.5.1, and npm audit immediately reported “1 high severity vulnerability” on install. All attacks ran only against local test functions, never against real services.
Test 1: changing the role from “user” to “admin”
The simplest attack: decode the payload, replace "role":"user" with "role":"admin", re-encode, keep the old signature.
| Check | Result |
|---|---|
jwt.verify(token, secret) | rejected: invalid signature |
jwt.decode(token) | role: "admin", no error |
The signature does its job. But the second row is the real finding: decode() checks nothing. It just reads the token. If your code accidentally uses decode instead of verify, say because it’s “faster” or because you only need the user ID for a moment, you have no protection at all. This mistake comes up surprisingly often in code reviews.

Test 2: the alg=none trap
The standard allows "alg":"none" in the header, meaning an unsigned token. It ends with a dot and has no signature:
eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiI0MiIsIm5hbWUiOiJBbm5hIiwicm9sZSI6ImFkbWluIn0.
The attacker’s idea: if the server trusts the alg field in the header, it simply checks nothing when it says none. Our results:
| Scenario | Result |
|---|---|
jsonwebtoken 9.0.3, normal with secret | rejected: jwt signature is required |
9.0.3, key missing (undefined) | rejected: please specify "none" in "algorithms" to verify unsigned tokens |
9.0.3, spellings None, NONE, nOnE | all rejected |
9.0.3, algorithms: ['none'] and no key | accepted, role: admin |
jsonwebtoken 8.5.1, key missing | accepted, role: admin |
| 8.5.1, with secret | rejected |
jose 6.2.18 | rejected: alg none is not supported |
| hand-rolled verify function (see below) | accepted, role: admin |
Three lessons:
First: current libraries are safe unless you explicitly configure them to be unsafe. jsonwebtoken 9 only accepts an unsigned token if you allow none yourself. jose doesn’t support none for verification at all.
Second: old versions are a real risk. In jsonwebtoken 8.5.1 a missing key was enough for the forged admin token to pass. That’s CVE-2022-23540, fixed in version 9.0.0 in December 2022. How does a key go “missing”? Typically through an environment variable that isn’t set on the server: jwt.verify(token, process.env.JWT_SECRET) with an empty JWT_SECRET. Check your dependencies with npm ls jsonwebtoken.
Third: rolling your own is the most dangerous option. Our deliberately naive verify function looked like this, and you’ll find similar code in tutorials and Stack Overflow answers:
function verifyNaive(token, key) {
const [h, p, s] = token.split('.');
const header = JSON.parse(Buffer.from(h, 'base64url'));
if (header.alg === 'none') return JSON.parse(Buffer.from(p, 'base64url')); // ← bug
const sig = crypto.createHmac('sha256', key).update(h + '.' + p).digest('base64url');
if (sig !== s) throw new Error('bad signature'); // ← also bad
return JSON.parse(Buffer.from(p, 'base64url'));
}
It falls for alg: none instantly. It also compares signatures with !==, which in theory allows timing attacks (use crypto.timingSafeEqual), and it never checks exp. Don’t build JWT verification yourself.

Test 3: algorithm confusion (RS256 → HS256)
With RS256 the server signs with a private RSA key and verifies with the public one, which is often freely available (for example at /.well-known/jwks.json). The classic attack: take the public key, use it to sign a token with HS256 and set "alg":"HS256" in the header. A badly built library then uses the public key as the HMAC secret, and the signature checks out.
| Library | Result |
|---|---|
jsonwebtoken 9.0.3 | rejected: invalid algorithm |
jsonwebtoken 8.5.1 | rejected: invalid algorithm |
jose 6.2.18 | rejected: KeyObject instances must be of type "secret" for the HS256 algorithm |
Both libraries recognise from the PEM format that the key is a public key and refuse HMAC with it. The attack isn’t dead though: libraries in other languages and older versions have been affected in the past. The proper defence is one line: pin the algorithm when verifying instead of taking it from the header.
jwt.verify(token, publicKey, { algorithms: ['RS256'] });
Test 4: expiry
| Scenario | Result |
|---|---|
| Token expired 5 seconds ago | rejected: jwt expired |
same with clockTolerance: 10 | accepted |
same with ignoreExpiration: true | accepted |
Token without exp | accepted, valid forever |
The last row is the important one: jwt.sign() sets no expiry unless you ask for one. Such a token stays valid as long as the secret doesn’t change, which could mean years. Always pass expiresIn. A small clockTolerance (a few seconds) is sensible when several servers have slightly different clocks.
Test 5: cracking a weak secret
Anyone who gets hold of an HS256 token can guess the secret offline: they just try candidates and compare signatures. The server never notices, no rate limit or fail2ban kicks in.
Our test: a token signed with the secret sommer2026 (“summer2026” in German), plus a wordlist built from John the Ripper’s default list (3,546 entries) with typical suffixes like 123, !, 2025, plus seasons with years. 25,004 candidates in total.
- Found after 24,869 attempts in 52 milliseconds, in plain Node.js on a single CPU core.
- Raw throughput: about 504,000 HMAC-SHA256 checks per second on one core. Our server has twelve.
- Specialised tools such as hashcat on a GPU are many times faster.
And: neither library warned us. jsonwebtoken happily signed with the secret a (one character), jose with geheim. The secret must be a long random value, not a word:
openssl rand -base64 48
That gives you 64 characters with 384 bits of randomness, which no wordlist will ever hit. Our game server reads its secret from a file with 96 characters. Treat the secret like a password: not in the Git repository, not in frontend code, not baked into Docker images.
HS256, RS256 or ES256: which algorithm?
| HS256 | RS256 | ES256 | |
|---|---|---|---|
| Method | HMAC, one shared secret | RSA, private + public key | Elliptic curve P-256 |
| Who can verify? | only holders of the secret (who can also forge) | anyone with the public key | anyone with the public key |
| Token length in our test* | 180 chars | 438 chars | 182 chars |
| Verify time in our test | 24 µs | 40 µs | 56 µs |
| Typical use | a single service verifying its own tokens | identity providers (Keycloak, Auth0, Entra ID) | like RS256, more compact |
* HS256 with five claims; RS256 and ES256 with an identical, smaller payload. Measured with jsonwebtoken 9.0.3, average of 20,000 verifications each.
Our rule of thumb: if only one service verifies its own tokens, HS256 with a long random secret is fine. As soon as several services need to verify tokens, use an asymmetric algorithm. Otherwise every service needs the secret, and each of them could also issue tokens with it. ES256 produces shorter tokens than RS256. The verify time is so small for all three that it won’t matter in a real application.
JWT vs. session: which is better?
The honest answer: for a normal website with a login, a classic session is often the better choice. Side by side:
| Session cookie | JWT | |
|---|---|---|
| What the client holds | a random ID (43 chars in our test) | the whole token (180 to 725 chars in our test) |
| Where the data lives | on the server (database, Redis) | in the token itself |
| Logout / lockout | immediate: delete the session | only on expiry, unless you add a deny list |
| Changing permissions | takes effect immediately | only with the next token |
| Multiple servers | need a shared session store | verify independently |
| Third-party services / mobile apps | awkward | built for it |
Our “fat” test token with email, three roles, 30 permissions, iss and aud was 725 characters long. Those bytes travel with every request, including images and scripts if the token lives in a cookie. A session ID is 43 characters.
JWT pays off mainly when: several services need to check the same login, an third-party identity provider issues tokens (OpenID Connect uses JWTs as ID tokens), mobile apps or other programs call an API, or services pass short-lived permissions between each other.
A session is usually better when: it’s a single server with its own login page, users must be logged out instantly, or permissions change often.

Where should you store a JWT in the browser?
This has been debated for years. In short:
- LocalStorage / SessionStorage: convenient, but any JavaScript on the page can read the token. One XSS hole, for example through a compromised npm package or an ad script, and the token is gone. On the plus side it isn’t vulnerable to CSRF, because the browser doesn’t send it automatically.
- HttpOnly cookie: JavaScript can’t get at the token. But the browser sends it automatically, so you need CSRF protection:
SameSite=LaxorStrict, plus token or origin checks. - In memory only (a JavaScript variable) plus a refresh token in an HttpOnly cookie: considered a good compromise for single-page apps. After a reload the app fetches a fresh access token via the refresh endpoint.
For most web apps we recommend HttpOnly + Secure + SameSite=Lax with a short lifetime. None of these options fully protects against XSS, because an attacker with script access can make requests on the user’s behalf even without the token. With an HttpOnly cookie, though, they can’t take the token with them and use it later from somewhere else.
Wherever it’s stored, the token must always travel over HTTPS. Whoever reads it along the way is the user until it expires.
Revoking a JWT: the built-in problem
Stolen laptop, employee leaves, password changed: an already-issued JWT stays valid until exp. The server deliberately stored nothing. The usual remedies:
- Short lifetimes for access tokens (5 to 15 minutes) and refresh tokens stored in the database. This is the standard solution.
- Deny list of the
jtiof revoked tokens, for example in Redis until they expire. That brings back a store lookup per request, though. - Token version per user: the token says
ver: 7, so does the database. On password change it goes to 8 and every old token fails. Also costs a lookup. - Rotate the secret: invalidates all tokens at once, so every user has to log in again. That’s the emergency option when the secret itself is compromised.
30-day lifetimes like our game server’s are convenient, but they’re also 30 days in which a stolen token works. For a game server with bot accounts that’s acceptable; for an admin panel or online banking it isn’t.
Checklist: using JWT securely
- Use an established library and keep it updated (
jsonwebtoken≥ 9,jose,PyJWT≥ 2 in Python,firebase/php-jwt≥ 6 in PHP). Don’t write your own verification. verify, neverdecode, whenever you want to trust the content.- Pin the algorithm:
algorithms: ['HS256']or['RS256'], never take it from the header, never allownone. - Secret with at least 256 bits of randomness (
openssl rand -base64 48), stored outside the code. Check at startup that it’s set, and refuse to start if it isn’t. - Always set
exp, keep access tokens short, store refresh tokens server-side. - Check
issandaudas soon as more than one service issues or accepts tokens. Otherwise a token for service A may also work at service B. - No secrets in the payload. Anyone can read it.
- Keep the payload small. No full permission lists when a role will do.
- No tokens in URLs (
?token=…): they end up in server logs, browser history and the Referer header. - HTTPS only, and in cookies with
HttpOnly,SecureandSameSite.
What we didn’t test
So that nobody reads more into our test than it shows: we only checked two JavaScript libraries in one or two versions each, not PHP, Python, Java or Go. We left out encrypted tokens (JWE), as well as attacks via the kid or jku header, where an attacker gets the server to load a key of their choosing. We also didn’t measure GPU cracking; the 504,000 attempts per second are a lower bound on a single CPU core. All tests ran against local functions, never against third-party systems. The test folder was deleted afterwards.
FAQ: common questions about JWT
What does JWT stand for?
JWT stands for JSON Web Token. It’s an open standard (RFC 7519) for compact, signed data packages in JSON format. According to the spec it’s pronounced like the English word “jot”.
Is a JWT encrypted?
No, usually not. A normal JWT is just Base64URL-encoded and signed. Anyone can read the content, but nobody can change it unnoticed. Encrypted tokens exist as JWE (RFC 7516), but they’re rare in web apps.
Can you decode a JWT without the key?
Yes. Header and payload can be read with any Base64 tool, as shown above. The key is only needed to verify the signature or to create a new token.
What is the alg=none vulnerability?
An attacker sets "alg":"none" in the header and drops the signature. If the server blindly follows the header’s algorithm, it accepts the forged token. Current libraries reject this. In our test, however, an old jsonwebtoken version (8.5.1, with a missing key) and a hand-rolled verify function both fell for it.
How long should a JWT be valid?
Access tokens 5 to 15 minutes; refresh tokens days to a few weeks, stored in the database so they can be revoked. A token without exp is valid forever.
What happens if a JWT is stolen?
The thief can impersonate the user until it expires. Hence short lifetimes, HTTPS, HttpOnly cookies and a way to revoke (delete the refresh token, bump the token version). If the secret is stolen, the thief can mint any token they like, and only a new secret helps.
Is JWT better than session cookies?
Not in general. JWT shines when several services or third-party clients need to verify the login. For a single website with its own login, a session is often simpler and can be ended instantly.
Where should I store a JWT in the browser?
Ideally in a cookie with HttpOnly, Secure and SameSite=Lax, or in memory only with a refresh token in an HttpOnly cookie. LocalStorage is convenient but readable by every script on the page.
How long must the JWT secret be?
For HS256, at least 256 bits of real randomness, i.e. 32 random bytes or more. A word plus a year was found in 52 milliseconds in our test.
What’s the difference between JWT and OAuth?
OAuth 2.0 is a protocol that lets an app access someone else’s account. JWT is a format for tokens. OAuth may use JWTs as access tokens but doesn’t have to. OpenID Connect, the login layer on top of OAuth, does require JWT for the ID token.
Are JWTs vulnerable to CSRF?
Only when they’re stored in a cookie, because the browser sends cookies automatically. In the Authorization header they aren’t vulnerable to CSRF. We tested the details in our article What is CSRF?.
Can I just change the role inside a JWT?
You can read it, but not change it. In our test the modified role immediately caused invalid signature, as long as the server uses verify(). If it only uses decode(), the change goes through. That’s exactly why the difference matters so much.
Conclusion: what is JWT, and when should you use it?
A JWT is a signed pass that the server issues once and afterwards only checks. That’s elegant, because no session store is needed, and it’s the standard for APIs, mobile apps and identity providers. It comes with two properties you have to know about, though: the content is publicly readable, and an issued token can’t simply be taken back.
Our test showed that current libraries reliably fend off the well-known attacks (alg=none, algorithm confusion, tampered payloads). The danger is at the edges: old versions, decode() instead of verify(), tokens without expiry, hand-rolled verification and above all weak secrets, which no library complains about and which fall offline in milliseconds.
If you only do three things today: check your version with npm ls jsonwebtoken (or your language’s equivalent), pin the algorithm when verifying, and replace every secret that isn’t a long random value.
Further reading: What is an API?, What is CSRF?, Understanding and setting up HTTPS and our overview of the most common IT security vulnerabilities.
