How authentication works on the web: passwords, sessions, cookies and JWTs
A diagram-first guide to web authentication: password hashing, server-side sessions, cookies and their security flags, JSON Web Tokens, refresh tokens, and when to use which.
HTTP forgets you between requests
Every page view, form submission and API call is a separate HTTP request, and the protocol keeps no memory between them. When your browser asks for /account a second after you logged in, the server receives a brand-new request. Nothing in HTTP itself says it came from the person who just typed the right password. HTTP is stateless.
So any request that needs an identity has to carry proof of one. Nearly everything in web authentication answers two questions. How does a user prove who they are the first time? And what do they carry afterwards, so they don’t have to prove it again on every click? This guide follows the usual answers: a password checked against a stored hash, then either a session cookie or a signed token such as a JWT, and finally delegated sign-in with Google and a second factor.
Storing passwords: salt and a slow hash
The first credential is usually a password, and the first rule is that the server must never be able to read it back. Databases leak, through backups, injection bugs, misconfigured storage or insiders, so design as if your users table will one day be public. Encrypting passwords is not enough either: anything the server can decrypt, an attacker who reaches the server can decrypt too.
Instead, store a one-way hash. At login, hash the attempt the same way and compare. But not with a general-purpose hash such as SHA-256. Those are built to be fast, and fast is exactly wrong here: a single modern GPU computes billions of SHA-256 hashes a second. Here is the plain SHA-256 of a common password:
sha256("password123")
= ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94fEvery user who chose that password has exactly that hash, in your database and in everyone else’s. Attackers keep precomputed tables of hashes for huge lists of common passwords, so cracking it is a lookup, not a computation. Two changes fix this:
- A salt. Generate a random value for each user, mix it into the hash and store it alongside. Identical passwords now produce different hashes, precomputed tables become useless, and every hash has to be attacked separately.
- A slow, memory-hard hash. Use a function designed for passwords, with a cost you can tune. Argon2id is the current first choice; scrypt and bcrypt remain acceptable. Your server pays the cost once per login, while an attacker pays it for every single guess, and the memory requirement blunts the advantage of GPUs.
The stored value is self-describing. Here are two real Argon2id hashes of the same password, “correct horse battery staple”, using the minimum parameters suggested by OWASP’s Password Storage Cheat Sheet (19 MiB of memory, 2 iterations, parallelism of 1):
$argon2id$v=19$m=19456,t=2,p=1$oBXw0sgLSuoSiKfJh8SMxw$0FKu773bAkPsi3joFFyBRoWy2GDuUR/G9BSHuLTKypk
$argon2id$v=19$m=19456,t=2,p=1$w38ozjc6rmAKDf4Vd1IYRg$M+4MzKYn12JMrISEKTffdd1luHK3l1XuqnSIPJ/ahjsReading left to right: the algorithm, its version, the cost parameters (m is memory in KiB, t the number of passes, p the parallelism), then the 16-byte salt and the 32-byte hash, both in base64. Same password, different salts, completely different results.
In practice a library generates the salt, builds that string and compares in constant time for you:
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
ph = PasswordHasher() # Argon2id, random salt per hash
def sign_up(password: str) -> str:
return ph.hash(password) # store this string
def log_in(stored: str, attempt: str) -> bool:
try:
return ph.verify(stored, attempt)
except VerifyMismatchError:
return FalseBecause the parameters travel with each hash, you can raise them later: after a successful login, ph.check_needs_rehash(stored) says whether the hash uses older settings, and you re-hash the password the user just typed. If you use bcrypt, note that it ignores input beyond 72 bytes, one more reason to prefer Argon2id for new systems.
Sessions and cookies
The login flow
Once the password checks out, the server needs to remember that fact, so the user doesn’t have to send their password with every request. The classic answer is a server-side session:
- The server generates a session ID: a long random value from a cryptographically secure generator, meaningless on its own. 32 random bytes (256 bits) is plenty.
- It saves a record in a session store (Redis, a database table, or memory if there is only one server) mapping that ID to the user and an expiry time.
- It sends the ID to the browser in a
Set-Cookieresponse header. - The browser returns it in a
Cookieheader on every later request to the site, and the server looks it up to find the user. - Logging out deletes the record, so the ID becomes worthless even if someone has a copy.
The session ID is an opaque token: a pointer to state the server holds, not a container of facts. To end a session, at logout or after a password change, you delete a record and it is over on the next request. Remember that for the JWT section, where it stops being true. In Express, the end of a successful login looks like this (sessions stands for your store):
import crypto from 'node:crypto';
// ...after the password hash has been verified
const sessionId = crypto.randomBytes(32).toString('base64url');
await sessions.set(sessionId, { userId: user.id }, { ttlSeconds: 8 * 60 * 60 });
res.cookie('__Host-sid', sessionId, {
httpOnly: true,
secure: true,
sameSite: 'lax',
path: '/',
maxAge: 8 * 60 * 60 * 1000, // Express takes milliseconds
});What the browser does with cookies
A cookie is a small named value that a server asks the browser to keep. From then on, the browser decides on every request whether to attach it, based on the destination URL and the cookie’s attributes, and not on which page or script started the request. That automatic attachment makes cookies convenient, and it is also the root cause of CSRF. The attributes are how you constrain it. The code above produces this header (Express also adds an equivalent Expires):
Set-Cookie: __Host-sid=o6R_hVpQPp2VTJ__OC1KM6U0rxNrfAAeS3rUPYuaMcY; Max-Age=28800; Path=/; HttpOnly; Secure; SameSite=LaxCookie attributes
| Attribute | What it does | Session cookie |
|---|---|---|
HttpOnly | Hides the cookie from JavaScript (document.cookie). It is still sent with requests. | Always |
Secure | Only sent over HTTPS, never plain HTTP. | Always |
SameSite=Lax | Sent on same-site requests and on top-level GET navigations from other sites; withheld from cross-site POSTs, iframes, images and fetch calls. | Good default |
SameSite=Strict | Never sent on cross-site requests, not even when the user follows a link from another site (they arrive looking signed out). | High-risk apps |
SameSite=None | Sent on every request, including cross-site ones. Requires Secure. | Only for cross-site embeds |
Domain | Without it, only the exact host that set the cookie receives it. Domain=example.com shares it with every subdomain. | Omit |
Path | Limits the cookie to URLs under a path. A convenience, not a security boundary. | Path=/ |
Max-Age / Expires | When the browser deletes it. With neither, it lasts until the browser session ends. | Match the session lifetime |
__Host- prefix | The browser rejects the cookie unless it has Secure, Path=/ and no Domain, which pins it to one host. | Use it |
Two definitions make SameSite clearer. An origin is the scheme, host and port, such as https://app.example.com. A site is broader: the registrable domain, such as example.com, so app.example.com and api.example.com are the same site. That is why SameSite offers no protection from a compromised sibling subdomain. Chrome and Edge treat a cookie with no SameSite attribute as Lax, but not every browser does, so always set it explicitly.
XSS, CSRF and session fixation
Three attacks explain most of those rules. None needs the password; each targets what the browser carries.
Cross-site scripting (XSS) and HttpOnly
If an attacker manages to run JavaScript on your page, for example through a comment field that is rendered as raw HTML, that script runs with your page’s full privileges. It can read whatever your own code can read: the DOM, localStorage, sessionStorage and any cookie without HttpOnly. One line sends a stolen token to a server the attacker controls, where it keeps working from their machine until it expires.
HttpOnly keeps the session cookie out of the script’s reach, so the credential cannot be carried away. It does not make XSS harmless: while the page is open, the script can still call fetch() and the browser will attach the cookie. The real defence is not having XSS. Rely on your framework’s escaping (React escapes text by default), sanitise any user-supplied HTML you must render, and add a Content Security Policy as a second layer.
Cross-site request forgery (CSRF)
CSRF abuses the automatic part. Suppose you are signed in to bank.example and visit a page on evil.example. That page contains a hidden form that posts to bank.example/transfer and submits itself. The request comes from your browser, so unless something stops it, the browser attaches your bank cookie and the bank sees a perfectly valid session asking to move money. The attacker never sees the cookie. They don’t need to.
Layer the defences:
- SameSite=Lax or Strict on the session cookie stops the browser attaching it to cross-site POSTs, which defeats the classic attack.
- A CSRF token: a random value tied to the session, embedded in each form or sent as a request header, and checked on every state-changing request. The attacker’s page cannot read it, because the same-origin policy stops it reading your pages.
- Origin checks: on state-changing requests, inspect the
Origin(orSec-Fetch-Site) header and reject requests from other sites. - No state changes on GET. Lax still sends cookies when a user follows a link from another site, so a GET that deletes or transfers anything is exposed.
Session fixation
Here the attacker plants a session ID they already know in the victim’s browser, for instance through a cookie set from a compromised subdomain, or an old app that accepted session IDs in the URL. The victim logs in, the server marks that existing session as authenticated, and the attacker’s copy of the ID is now signed in too. The fix is simple: issue a brand-new session ID at login, and whenever privileges change, and discard the old one. Most frameworks do this for you; with express-session it is req.session.regenerate().
JSON Web Tokens
Sessions keep state on the server and hand the browser a pointer. A JSON Web Token (JWT) flips that around: the facts about the user travel inside the token, signed by the issuer, so any service holding the right key can check the token without looking anything up.
A JWT is three base64url-encoded parts joined by dots: header.payload.signature. Here is a real one, signed with HS256 using the deliberately weak demo secret demo-secret-do-not-use. It is a single string; the line breaks at the dots are only for display:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
.eyJzdWIiOiI0MiIsInJvbGUiOiJ1c2VyIiwiaXNzIjoiaHR0cHM6Ly9hdXRoLmV4YW1wbGUiLCJhdWQiOiJhcGkuZXhhbXBsZSIsImlhdCI6MTc5NTI1MTYwMCwiZXhwIjoxNzk1MjUyNTAwfQ
.q13e5D6SbaMb-E8-IORbl8DkiIGKAcM6hWPxxXTO8CUSigned is not encrypted
Base64url is an encoding, not encryption. Anyone who holds the token can decode the payload in a second. The signature guarantees integrity: the claims have not changed since the issuer signed them. It says nothing about secrecy, so never put passwords, keys or personal data the user should not see into a JWT. Encrypted JWTs (JWE) exist, but most systems simply keep sensitive data out.
Claims
The fields in the payload are called claims. A handful are registered by the standard, and verifiers should check them:
sub(subject): who the token is about, usually a stable user ID.iss(issuer): who created it. Reject issuers you don’t trust.aud(audience): who it is for. An API should reject a token minted for a different API, even from the same issuer.exp(expiry) andiat(issued at): seconds since 1 January 1970 UTC. Here1795251600is 21 November 2026 at 09:00 UTC, and the token expires 15 minutes later.nbf(not before) andjti(a unique token ID) are optional;jtiis handy for revocation lists.
Anything else, like role above, is a custom claim.
How the signature is made and checked
For HS256 the signature is an HMAC-SHA-256 of the first two parts, keyed with the secret. Nothing more, as this standard-library Python shows. It prints exactly the token above:
import base64, hashlib, hmac
def b64url(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
header = b64url(b'{"alg":"HS256","typ":"JWT"}')
payload = b64url(b'{"sub":"42","role":"user","iss":"https://auth.example",'
b'"aud":"api.example","iat":1795251600,"exp":1795252500}')
signature = hmac.new(b"demo-secret-do-not-use",
f"{header}.{payload}".encode(), hashlib.sha256).digest()
print(f"{header}.{payload}.{b64url(signature)}")To verify, the server recomputes the HMAC over the header and payload it received and compares the result with the signature the token carries. Change a single character of the payload and they no longer match. Try it:
token the API receives
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI0MiIsInJvbGUiOiJ1c2VyIiwiaXNzIjoiaHR0cHM6Ly9hdXRoLmV4YW1wbGUiLCJhdWQiOiJhcGkuZXhhbXBsZSIsImlhdCI6MTc5NTI1MTYwMCwiZXhwIjoxNzk1MjUyNTAwfQ.q13e5D6SbaMb-E8-IORbl8DkiIGKAcM6hWPxxXTO8CU
decoded header and payload
{"alg":"HS256","typ":"JWT"}
{"sub":"42","role":"user","iss":"https://auth.example","aud":"api.example","iat":1795251600,"exp":1795252500}
signature the server computes with its secret
q13e5D6SbaMb-E8-IORbl8DkiIGKAcM6hWPxxXTO8CU
signature the token carries
q13e5D6SbaMb-E8-IORbl8DkiIGKAcM6hWPxxXTO8CU
Accepted. The two signatures match, so the API treats the request as user 42 with role “user”.
Shared secrets and key pairs
HS256 is symmetric: the same secret signs and verifies. That is fine when one service both issues and checks its own tokens, but every service that can verify can also forge. RS256 (RSA) and ES256 (elliptic curve) use a key pair instead. The auth server signs with a private key that never leaves it and publishes the matching public key, usually as a JSON Web Key Set (JWKS). Any number of APIs can then verify tokens without being able to create them. Google’s ID tokens, which appear later in this guide, work this way.
In production, use a maintained library and tell it exactly what you expect. With jose in Node.js:
import { jwtVerify } from 'jose';
const key = new TextEncoder().encode(process.env.JWT_SECRET); // 32+ random bytes
export async function userIdFrom(token) {
const { payload } = await jwtVerify(token, key, {
algorithms: ['HS256'], // never let the token choose
issuer: 'https://auth.example',
audience: 'api.example',
}); // also checks exp and nbf, and throws if anything fails
return payload.sub; // "42"
}Access tokens, refresh tokens and revocation
Where to keep a token in the browser
A session ID lives in a cookie by default. A JWT can live almost anywhere, and the choice decides which attack you most need to worry about.
| Stored in | Readable by injected script? | Sent automatically? | Survives a reload? |
|---|---|---|---|
| A JavaScript variable | Yes, while the page is open | No | No |
| localStorage | Yes | No, so no CSRF risk | Yes |
| HttpOnly cookie | No | Yes, so defend against CSRF | Yes |
A token in localStorage is immune to CSRF, because nothing attaches it automatically, but a single XSS bug lets an attacker copy it and use it from anywhere until it expires. An HttpOnly, Secure, SameSite cookie keeps the token away from script, and CSRF has well-understood defences, so for a browser app talking to its own backend the cookie is the safer default. Many teams go one step further with a backend for frontend: the server holds any OAuth tokens, and the browser only ever sees an ordinary session cookie.
Short-lived access tokens, long-lived refresh tokens
Because a JWT is checked without a lookup, a stolen one keeps working until exp. So systems built on JWTs usually issue two tokens:
- An access token: short-lived (often 5 to 15 minutes), sent with every API call in an
Authorization: Bearerheader, and verified locally by each API. - A refresh token: long-lived (days or weeks), sent only to the auth server’s token endpoint to get a new access token. It is usually an opaque random value recorded on the server, so it can be revoked.
With refresh token rotation, every refresh returns a new refresh token and retires the old one. If a retired token is ever presented again, two parties hold copies and one of them is an attacker, so the server revokes the whole chain and the user signs in again.
The revocation problem
Logging out of a session deletes a record. Logging out with a stateless JWT does nothing to the token: it stays valid until it expires, wherever copies exist. The options are all compromises:
- Keep access tokens short-lived and revoke the refresh token, accepting a window of a few minutes.
- Keep a denylist of revoked
jtivalues until they expire. That is a lookup on every request: state again. - Store a per-user “valid after” time or token version and reject older tokens. Also a lookup, but a small and easily cached one.
- Rotate the signing key to invalidate every token at once. For emergencies only.
Notice that the robust options bring server-side state back.
Sessions or JWTs?
Both carry the same message after login, “this request comes from user 42”. The difference is where the truth lives.
Server-side sessions
- An opaque random ID in a cookie; the state lives on the server
- Logout and revocation are instant: delete the record
- One store lookup per request, usually cheap
- Simple, and supported well by every web framework
- Several servers need a shared store such as Redis
JWTs (stateless tokens)
- Signed claims carried inside the token itself
- Any service with the key can verify it, no lookup
- Hard to revoke before exp, so keep them short-lived
- Much larger than a session ID, and sent on every request
- More to get right: algorithms, claims, storage, refresh
For most web apps, where a browser talks to a backend you control, server-side sessions in a secure cookie are the simpler and safer choice. A lookup in Redis or an indexed table is cheap, and you get instant logout for free. Reach for JWTs when their properties actually pay off:
- many services or APIs need to verify identity without all calling one central store;
- mobile apps, desktop apps and third-party integrations, where cookies are awkward;
- service-to-service calls, where a short-lived signed token says which service is calling;
- you use an identity provider such as Auth0, Amazon Cognito or Microsoft Entra ID that issues them anyway.
Mixing the two is common: a session cookie between the browser and your backend, and short-lived JWTs between that backend and internal services.
“Sign in with Google”: OAuth 2.0 and OpenID Connect
“Sign in with Google” lets Google check the password and second factor, so your app never sees either. Two standards are involved. OAuth 2.0 is about authorisation: letting an app obtain an access token to call an API on a user’s behalf. OpenID Connect (OIDC) is a thin layer on top that adds authentication: alongside the access token, the provider returns an ID token, a JWT signed by Google that states who the user is.
The recommended flow for web apps is the authorisation code flow with PKCE (Proof Key for Code Exchange). The browser is only ever handed a short-lived, single-use code; the tokens travel directly between your server and Google.
- Prepare. Your app generates a
statevalue (ties the callback to this browser), anonce(Google copies it into the ID token, so an old token cannot be replayed) and a PKCEcode_verifier, and keeps them in the user’s pre-login session. - Redirect. It sends the browser to Google with
scope=openid email profile, the state, the nonce and acode_challenge: the SHA-256 hash of the verifier. - Sign in at Google. The user authenticates with Google and agrees to share their profile. Your app sees none of this.
- Callback. Google redirects back to your registered
redirect_uriwith a one-timecodeand the state, which your app checks. - Exchange. Your server posts the code, the original verifier and its client secret to Google’s token endpoint. Google hashes the verifier and compares it with the challenge, so an intercepted code is useless on its own.
- Verify and sign in. Google returns an ID token and an access token. Your app verifies the ID token’s signature against Google’s published keys and checks
iss,aud(your client ID),expandnonce. Then it finds or creates the user and starts an ordinary session.
The PKCE pair is just a random string and its hash. These two values are real:
import base64, hashlib, secrets
verifier = secrets.token_urlsafe(32) # kept by your app
challenge = base64.urlsafe_b64encode(
hashlib.sha256(verifier.encode()).digest()
).rstrip(b"=").decode() # sent to Google in the redirect
# verifier = "W0gC7Ts0kqoZRbSQjqxJsksn4VDGMoq-Q_58q3LpQRc"
# challenge = "pzBPACq_K-UrcaiHNwCA0ouLPwNGS37ZewDgzF0nr_Y"Two details trip people up. Identify users by the ID token’s sub claim, Google’s stable account ID, not by email address, which can change. And notice where the flow ends: in a normal session cookie. OAuth and OIDC replace the password check at the start, not the session mechanics that follow.
MFA and a security checklist
Passwords get phished, guessed and reused across sites. Multi-factor authentication asks for a second, different kind of proof: something you have (a phone or security key) or something you are (a fingerprint, which usually just unlocks a key stored on the device). The common options differ a lot in strength:
- SMS codes are the weakest: they can be intercepted, or redirected with a SIM swap. Still better than nothing.
- Authenticator apps (TOTP) share a secret with your server at setup, then derive a six-digit code from an HMAC of the current 30-second time window. Solid, but a convincing fake login page can ask for the code and replay it in real time.
- Passkeys and security keys (WebAuthn) use a key pair, with the private key kept on the device. The browser binds each credential to your domain, so a look-alike phishing site cannot use it. Of the common options, only this one resists phishing, and passkeys can replace the password entirely.
A practical checklist for any login system:
- Serve everything over HTTPS and enable HSTS.
- Hash passwords with Argon2id (or scrypt or bcrypt), and never log them.
- Check new passwords against breached-password lists; favour length over composition rules.
- Rate-limit login, reset and MFA endpoints, and answer an unknown account exactly as you answer a wrong password.
- Use session IDs of at least 128 random bits, rotate them at login, delete them at logout, and enforce idle and absolute timeouts.
- Set session cookies with
__Host-,Secure,HttpOnlyandSameSite=LaxorStrict. - Add CSRF tokens or Origin checks to state-changing requests, and never change state on GET.
- Prevent XSS with framework escaping, sanitised HTML and a Content Security Policy.
- For JWTs, pin the algorithm, check
exp,issandaud, use strong keys and rotate refresh tokens with reuse detection. - Make password-reset tokens random, single-use and short-lived, and store only their hash.
- Offer MFA, ideally passkeys, and re-authenticate users before email or password changes.
Summary
- HTTP is stateless, so every authenticated request carries a credential. Authentication says who the user is; authorisation decides what they may do.
- Store passwords as salted, slow, memory-hard hashes such as Argon2id. Never plaintext or a fast hash.
- A server-side session is a random ID in a cookie pointing to state on the server: simple, with instant revocation.
HttpOnly,Secure,SameSiteand__Host-limit XSS damage and block most CSRF. Regenerate the session ID at login.- A JWT is signed, base64url-encoded claims: tamper-evident but readable by anyone. Pin the algorithm and check
exp,issandaud. - JWTs are hard to revoke, so keep access tokens short-lived and rotate refresh tokens.
- Sessions are the right default for most web apps; JWTs suit distributed APIs and mobile clients.
- “Sign in with Google” is OAuth 2.0 with PKCE plus an OpenID Connect ID token, ending in an ordinary session. Add MFA, ideally passkeys.
Further reading on this site
- How AI agents work: the tool-calling loop. An agent that calls APIs for a user needs the same delegated, scoped, short-lived tokens described in the OAuth section.
- How retrieval-augmented generation (RAG) works. An assistant that answers from internal documents has to apply the same authorisation rules as the rest of your app, or it will quote documents the user is not allowed to open.