You type your email and password, press Sign in, and a second later you're looking at your inbox. You click a message. Then another. You close the laptop, come back after lunch, and it still knows who you are. You proved your identity once, at nine in the morning, and nobody has asked since.
That should strike you as odd, because the web has no memory. Every click is a new request, and by default a server treats each one as if it came from a stranger. So somewhere between the password and the second click, your browser must have picked up something it could show at the door.
This essay is about that something. We'll follow one sign-in from the button to the sign-out, and take apart the thing called a JWT on the way. You don't need to be a programmer. There are a few lines of code near the end of some sections, and you can skip them without losing the thread.
01The web forgets you after every click
When your browser wants a page, it sends a short text message to a server. The server sends the page back. As far as the rules of HTTP go, the conversation is now over. If you ask for another page two seconds later, nothing in those rules tells the server that you're the same person.
Picture a shopkeeper who forgets you each time you blink. You introduce yourself, ask for the price of rice, get an answer, and blink. Now you want the price of sugar. "Sorry, who are you?"
There are two ways around this. You could introduce yourself and prove it every single time, which would mean sending your password with every click. Nobody wants a password flying about that often. Or the shopkeeper could hand you a slip of paper the first time, and you could hold it up whenever you ask for something.
Every sign-in system you use is a version of the second idea. The rest is detail: what's written on the slip, who can forge it, where you keep it, and how the shop cancels it.
Two words are worth separating before we go on. Authentication asks who you are. Authorization asks what you're allowed to do. Your password answers the first question. Whether you can open the payroll page is the second, and the server has to ask it again on each request.
02The second after you press Sign in
Here is that second, slowed down.
- Your browser sends your email and password to the server. The connection uses HTTPS, so somebody sharing your café Wi-Fi sees only scrambled bytes. The server itself does receive the actual password, for a moment.
- The server looks for an account with that email.
- The database returns the account, along with a long string called a password hash. Your password isn't in there.
- The server runs what you typed through the same hashing recipe and compares the result with the stored one.
- If they match, it creates your slip of paper and sends it back. If you've turned on a second step, such as a code from your phone, it asks for that first.
If they don't match, you get a message like "Invalid email or password". The vagueness is deliberate. A site that says "wrong password" has just confirmed that the email has an account, and an attacker with a list of a million addresses would love to know which ones do. The OWASP authentication guide goes further. It wants the server to do the same amount of work whether the account exists or not, so the answer can't be guessed from how long it took.
03Why the site doesn't keep your password
A hash is a one-way calculation. Put text in, get a fixed-length string out, and there's no practical way to run it backwards. Mixing paint is a fair comparison. Anyone can stir blue into yellow, but you can't hand someone a tin of green and ask for the blue back.
So when you created the account, the site hashed your password and stored only the result. Each time you sign in, it hashes your attempt and checks whether the two strings are the same. It can recognise your password without having it on file. (This is also why a decent site can reset your password but can't email you the old one. If one ever does, change that password everywhere you've used it.)
Two refinements make this safe enough to use.
The first is a salt, a random value mixed in with each password before hashing. Without it, everyone who chose cricket123 would have the same hash, and an attacker could calculate the hashes of popular passwords once and look for matches. With it, two people with the same password end up with different hashes.
The second is slowness. Ordinary hash functions are built to be fast, which is exactly wrong here, because it lets a thief with a stolen database try guesses at enormous speed. Password hashes such as Argon2id and bcrypt are made expensive on purpose. You don't notice a fraction of a second when you sign in. Someone trying a billion guesses does. OWASP's password storage guide recommends Argon2id and keeps bcrypt for older systems.
04The cloakroom ticket: how a session works
You're in. Now the server needs to give you that slip of paper, and the older way to do it works like a theatre cloakroom.
You hand over your coat and get a ticket with a number on it. The ticket says nothing about you or the coat. It's only useful because the attendant has a rack, and on hook 318 there's a coat. Lose the ticket and whoever finds it can collect your coat. Set fire to the rack and the ticket is worthless.
A session is the hook on the rack. After you sign in, the server makes up a long random string, the session ID, and writes down what it stands for:
session ID what the server wrote down
---------------------- -------------------------------------------
k7Qm2v...x9Rt (random) user 42, signed in 9:00, Chrome on a laptop
Your browser gets the random string and nothing else. On each click it sends the string back, the server looks it up, finds user 42, and carries on. The string has to be long and properly random so that nobody can guess a working one. OWASP asks for at least 64 bits of randomness, which leaves more possible values than anyone could work through.
The good part is control. Want to throw somebody out? Delete the row. Their next click arrives with a ticket for an empty hook, and they're back at the sign-in page.
The cost is that the server has to look at the rack on every request. With one server that's nothing. With forty servers in three countries, they all need to reach the same rack, quickly, all day. That's a solved problem (a fast shared store such as Redis is the usual answer), but it's one more thing to run and one more thing that can fall over.
05The season pass: where JWT comes in
Now think of a railway season pass. It has your name on it, the route, the expiry date, and an official stamp that's hard to fake. A ticket inspector in the middle of nowhere can look at it and let you travel. There's no need to phone head office, because everything needed for the decision is printed on the pass. The inspector only has to trust the stamp.
That's a JWT. The letters stand for JSON Web Token, and the specification suggests you pronounce it "jot". It's a small piece of text that carries facts about you, plus a signature that shows who issued it and that nothing has been changed.
So the difference between the two comes down to where the facts live. With a session, the server keeps them and you carry a number. With a JWT, you carry the facts and the server keeps a key.
06Opening up a real JWT
Here's one I made for this essay. The lines are wrapped to fit the page, but it's really one long string with two dots in it.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczo
vL2F1dGguZXhhbXBsZS5jb20iLCJzdWIiOiI0MiIsImF1ZCI6InNob3A
iLCJyb2xlIjoicmVhZGVyIiwiaWF0IjoxNzk2MDA5NDAwLCJleHAiOjE
3OTYwMTAzMDB9.qpWQpzqlBhCPmv4AlTMMFQH9JCsE4vwOtrkli1WfuO
w
It looks encrypted. It isn't. The dots split it into three parts: header, payload and signature. The first two are ordinary text written in an alphabet called Base64URL, which exists so that data can travel safely in web addresses and headers. Undoing it takes no password at all.
The header says how the token was signed:
{
"alg": "HS256",
"typ": "JWT"
}
The payload holds the facts, which the specification calls claims:
{
"iss": "https://auth.example.com",
"sub": "42",
"aud": "shop",
"role": "reader",
"iat": 1796009400,
"exp": 1796010300
}
The three-letter names keep the token short. Those numbers at the end are times, counted in seconds since the start of 1970, which is how computers often store dates.
| Claim | Stands for | In plain words |
|---|---|---|
iss | issuer | Who made this token |
sub | subject | Who it's about. Here, user 42 |
aud | audience | Which service it's meant for |
iat | issued at | When it was made: 9:00 am in India on 30 November 2026 |
exp | expires | When to stop accepting it: fifteen minutes later |
role | (our own) | Something this app chose to add |
None of the standard claims is compulsory. The people building the app decide which to include, and their server has to check the ones they rely on.
Anyone holding a JWT can read it. The signature stops people changing it.
If you remember one thing from this essay, make it that. An ordinary signed JWT is a postcard with a tamper-proof seal. Never put a password, a card number or anything private in the payload. (An encrypted kind exists, called JWE, but it's not what people usually mean by JWT.)
07How the stamp works
The third part is where the trust comes from. The server takes the first two parts exactly as written, mixes them with a secret key that only it knows, and runs the lot through a calculation called HMAC-SHA256. Out comes the signature.
signature = HMAC-SHA256( header + "." + payload , secret key )
When the token comes back, the server repeats the sum and compares. Suppose you decide to promote yourself. You decode the payload, change reader to admin, encode it again and send it. The server does its sum over your edited text and gets a completely different answer from the signature you sent. To produce the right one you'd need the key. Rejected.
You can test this, because I'm publishing the key for this demo token. In real life, that would be a disaster.
// Save as check.mjs and run: node check.mjs
import { createHmac } from 'node:crypto';
const key = 'demo-only-24bd9fac67ea8aca9271a97c586b835ab0adb6c4d1c736cd';
const token = 'paste the token here, as one line';
const [header, payload, signature] = token.split('.');
const expected = createHmac('sha256', key)
.update(header + '.' + payload)
.digest('base64url');
console.log(Buffer.from(payload, 'base64url').toString());
console.log(expected === signature ? 'genuine' : 'tampered with');
Change one character of the payload and run it again. (Real servers use a tested library and a comparison that takes constant time. This is for seeing the idea, and it doesn't check the expiry.)
There's a catch in this scheme. Whoever can check a token can also make one, since both jobs use the same key. That's fine when one server does both. It's uncomfortable when twenty services need to check tokens and you'd rather trust only one of them to issue them.
For that, there's a second kind of signature with a pair of keys. The private key signs and stays locked up in one place. The public key can only check, so you can give it to everybody. You'll see these called RS256 or ES256 in a token's header, where our demo says HS256. It's how "Sign in with Google" can work on sites that Google has never shared a signing secret with.
08The cookie that carries it
People often talk about "cookies versus JWT", as though you pick one. They're different sorts of thing. A cookie is an envelope that the browser stores and sends back by itself. A session ID or a JWT is what you might put inside.
After a successful sign-in, the server's reply can include a line like this:
Set-Cookie: __Host-access=eyJhbGciOi...; Path=/; Max-Age=900; HttpOnly; Secure; SameSite=Lax
From then on, the browser attaches that cookie to requests to this site without your doing anything. The words at the end are the interesting part, and MDN has the full list:
HttpOnlyhides the cookie from JavaScript on the page. If someone manages to sneak a malicious script in, the script can't read the token and post it elsewhere.Securemeans it only travels over HTTPS.SameSite=Laxmeans another site can't quietly send it along with a hidden form. It still goes when you follow an ordinary link in.Max-Age=900makes the browser drop it after 900 seconds.
The other place developers put tokens is localStorage, a notepad that any script on the page can read. It's convenient, and that is the trouble with it. A modern page runs code from many packages, and one bad one is enough to copy the token out. OWASP advises against keeping session IDs or tokens there.
Cookies have a weakness of their own. Because the browser sends them automatically, a hostile site can try to make your browser send a request you never intended. That's called cross-site request forgery, or CSRF. SameSite blocks much of it, and careful sites add a check of their own on anything that changes data.
09What happens on your next click
You're signed in, the cookie is in place, and you open your orders page. Before any of your data is touched, the server goes through something like this:
- Take the token out of the cookie. If there isn't one, ask the visitor to sign in.
- Check the signature, using an algorithm the server chose in advance.
- Check that it hasn't expired.
- Check that the issuer and audience are the expected ones.
- Read the user ID and check that user 42 may see this particular order.
- Only now fetch the order.
In code, the first four steps are short, because a library does them. This is the jose library for JavaScript:
import { jwtVerify } from 'jose';
const { payload } = await jwtVerify(token, key, {
algorithms: ['HS256'],
issuer: 'https://auth.example.com',
audience: 'shop',
requiredClaims: ['exp', 'sub'],
});
// Reaching this line means the token is genuine and still valid.
// Whether this user may see this order is still your job.
Step 5 is the one that gets forgotten. A valid token proves you're user 42. It says nothing about whether order 9001 belongs to you. If the server skips that check, you can change the number in the address bar and read a stranger's order, with a perfectly good token in your hand.
Failures come back as one of two numbers you may have seen. 401 means "I don't know who you are". 403 means "I know who you are, and no".
10The trouble with a pass you can't take back
Go back to the season pass. Suppose yours is stolen, or you're sacked and it was a staff pass. The inspector on the train doesn't phone anyone. The stamp is real and the date is fine, so the thief travels.
JWTs have this same flaw, and it comes directly from what makes them useful. If the server never looks anything up, it can't learn that a token was cancelled. Change your password, and a token issued a minute earlier still checks out. Lose your admin role, and the token goes on saying admin until it expires.
The usual remedy is to make the pass last a very short time, say fifteen minutes, so that a stolen one soon goes stale. But you can't ask people for their password every fifteen minutes. So the server hands out two things at sign-in:
- An access token, usually a JWT, which lives for minutes and goes along with every request.
- A refresh token, which lives for days or weeks, and is only ever sent to one address, to ask for a new access token.
The refresh token is commonly just a long random string, and the server keeps a record of it. Look closely and you'll recognise the cloakroom ticket. The session never went away. What changed is that the server looks at the rack once every fifteen minutes, where before it looked on every click.
When the access token runs out, the app notices the 401, sends the refresh token, gets a fresh pair and repeats your request. You see nothing, except perhaps a page that took slightly longer.
Catching a thief by the second use
There's a neat trick here called rotation. Every time a refresh token is used, the server replaces it and marks the old one as spent. Now suppose a thief copies your refresh token. One of you uses it first and gets a new one. Sooner or later the other turns up with the spent one.
The server can't tell which of you is the thief. It doesn't need to. A spent token coming back means there are two copies about, so it cancels the live one too and makes everyone sign in again. You have your password and the thief, with any luck, doesn't. The OAuth security guidance, RFC 9700, requires either this or a token bound to one device for apps that can't keep a secret, which includes apps that run entirely in your browser or on your phone.
11What signing out really does
Pressing Sign out sounds like one action. It's really two, and a lazy site does only the first.
- The server tells your browser to delete the cookies.
- The server deletes its own record: the session row, or the refresh token.
If it skips the second, your browser has forgotten the token but the token still works, and a copy in the wrong hands is as good as ever.
With JWTs, even doing both leaves a gap. An access token that was copied earlier lasts until its expiry, up to fifteen minutes in our example. For a recipe site that's fine. For a bank it may not be, so stricter systems keep a short list of cancelled token IDs (that's what the jti claim is for) and check each request against it. At which point, yes, they're looking things up on every request again.
"Sign out of all devices" is the same idea applied to every record with your user ID on it. Changing your password should do this as well.
12What "Sign in with Google" changes
With that button, the site you're visiting never sees your Google password. It sends you to Google, and Google does all the checking described above. Then this happens:
- Google sends your browser back to the site with a short one-time code.
- The site's server sends that code to Google directly, along with proof that it's the site it claims to be.
- Google replies with an ID token, which is a JWT saying who you are and that it was made for this site.
- The site checks the signature with Google's public key, checks the issuer, audience and expiry, and finds or creates your account.
- The site starts its own session with you.
The standard behind it is OpenID Connect. The last step explains something people find confusing: signing out of the site doesn't sign you out of Google. They were two separate sessions all along.
13Session or JWT: which one to use
| Server session | JWT access token | |
|---|---|---|
| You carry | A random number | Signed facts about you |
| Server keeps | A record per sign-in | A key, and usually refresh records |
| Each request needs | A lookup | A signature check |
| Cancelling it | Immediate | At expiry, unless you add a list |
| Changed role shows up | Next click, if read from the server | Next token |
| Size | Small | Larger, and sent every time |
| Suits | One website with its own backend | Several services or companies that must trust one issuer |
My view: if you're building one web app with one backend, use sessions. They're simpler, you can cancel them, and the lookup is cheap. Reach for JWTs when a service has to trust a sign-in that happened somewhere else, such as a mobile app calling a dozen APIs, or one company accepting another's users. OWASP's JWT guide also suggests considering a plain session system first.
Plenty of real systems use both. The assistant in my essay on what happens in a chatbox reads a JWT from an HttpOnly cookie before it looks at your question.
14How it goes wrong
The mathematics in JWTs holds up well. The mistakes are mostly in how servers check them, and RFC 8725 collects the classics.
- Believing the token about itself. The header names the algorithm, and one permitted value is
none, meaning unsigned. A careless server reads that and skips the check. An attacker writes any payload they like. The server should decide the algorithm and ignore the token's opinion. - Mixing up the two kinds of key. The server expects RS256, which checks with a public key. The attacker changes the header to HS256 and signs with that public key, which everyone has. A badly written library then treats the public key as the shared secret and accepts it. The cure is the same: fix the algorithm.
- A guessable secret. If the key is
secret123, anyone with one token can try guesses on their own machine until the signature matches. After that they can sign in as whoever they please. Use a long random key. - Not checking the audience. A token made for the photo app gets accepted by the payments app, because both trust the same issuer.
- Decoding without verifying. Many libraries have one function that reads the payload and another that checks it. They look alike, and the first works on forgeries.
- Keeping the session ID from before sign-in. An attacker plants a known ID in your browser, waits for you to sign in, and shares your session. The server should issue a new ID the moment you sign in.
15One ordinary day, start to finish
Let's put it together. Asha is an invented customer of an invented shop that uses short JWTs with refresh tokens.
9:00. She signs in. The server hashes her password attempt, compares it, and sends back two cookies: an access token good until 9:15 and a refresh token good for a week.
9:04. She opens her orders. The server checks the signature, the expiry and the audience, confirms the orders are hers, and shows them. It didn't look up her session.
9:20. She clicks again. The access token has run out, so the server answers 401. The page sends the refresh token, gets a new pair, and tries again. Asha notices nothing.
1:30. She left the laptop shut for hours and opens it after lunch. The access token is long dead and the refresh token is fine. One swap, and she's still signed in.
4:00. She leaves her phone in a taxi. From the laptop she chooses "Sign out of all devices". The server deletes every refresh token with her ID on it. The phone's access token has at most fifteen minutes left, and after that the phone is a stranger.
4:01. The laptop's refresh token was deleted too, so before long it asks her to sign in again. She types her password, and it starts over.
16See it in your own browser
You can look at all this now. Open a site you're signed in to, on a computer, in Chrome. Press F12 (or Cmd+Option+I on a Mac), choose the Application tab, then Cookies. You'll see the names, the expiry dates, and ticks under HttpOnly and Secure. A value that starts with eyJ and has two dots in it is very likely a JWT. Those three letters are simply what {" and a letter turn into at the start of the encoded header.
One warning. Those values are live keys to your account. Don't paste them into a website that offers to decode them, don't put them in a screenshot, and don't give them to anyone who asks. If you want to see inside one, use the short script above on your own machine. Without the key it'll report the signature as wrong, but it will still print the payload.
And the next time a site asks you to sign in again for no obvious reason, you'll have a fair idea why. A pass ran out, or a hook on the rack is empty, or somebody used a token twice.