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.

Without a credential the server cannot link a later request to the login; with a session cookie it canbrowserserverno memory of youPOST /login · email + password200 OK · welcome backGET /accountwho is this?401 Unauthorizedthe fix: every request carries a credentialGET /account · Cookie: sid=o6R_hVpQ…sid → user 42200 OK · your account
Figure 1HTTP has no memory. The second request arrives with nothing linking it to the login, so the server cannot tell who sent it. The fix is a credential, here a session cookie, sent with every request.

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")
  = ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f

Every 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.
Password hashing: at sign-up the password and a random salt go through Argon2id and only the result is stored; at log-in the typed password is hashed with the stored salt and comparedat sign-uppasswordtyped by the usersalt16 random bytesArgon2idslow on purposedatabase rowparams + salt + hashat log-intyped passwordfrom the login formArgon2idsame salt + paramsequal?constant-time comparesalt + paramsstored hashyes: sign inno: reject
Figure 2At sign-up the server stores only the salt, the cost parameters and the hash. At log-in it repeats the same slow computation on what the user typed and compares the results. The password itself is never stored.

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/ahjs

Reading 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 False

Because 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:

  1. 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.
  2. 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.
  3. It sends the ID to the browser in a Set-Cookie response header.
  4. The browser returns it in a Cookie header on every later request to the site, and the server looks it up to find the user.
  5. Logging out deletes the record, so the ID becomes worthless even if someone has a copy.
Login with a server-side session: the server stores a session id, sends it in a cookie, looks it up on later requests and deletes it at logoutbrowserserveryour appsession storeRedis or SQLPOST /login · email + passwordcheck the password hashsave sid → user 42Set-Cookie: sid=o6R_…; HttpOnlylater: every request to the siteGET /orders · Cookie: sid=o6R_…look up siduser 42, not expired200 OK · orders for user 42logging outPOST /logout · Cookie: sid=…delete sidSet-Cookie: sid=; Max-Age=0
Figure 3A server-side session. The cookie holds only a random ID; who the user is, and whether the session is still valid, lives in the session store. Logging out deletes the record, which ends the session immediately.

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=Lax

Cookie attributes

AttributeWhat it doesSession cookie
HttpOnlyHides the cookie from JavaScript (document.cookie). It is still sent with requests.Always
SecureOnly sent over HTTPS, never plain HTTP.Always
SameSite=LaxSent 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=StrictNever 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=NoneSent on every request, including cross-site ones. Requires Secure.Only for cross-site embeds
DomainWithout it, only the exact host that set the cookie receives it. Domain=example.com shares it with every subdomain.Omit
PathLimits the cookie to URLs under a path. A convenience, not a security boundary.Path=/
Max-Age / ExpiresWhen the browser deletes it. With neither, it lasts until the browser session ends.Match the session lifetime
__Host- prefixThe 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.

An injected script can read a token from localStorage and send it to an attacker, but cannot read an HttpOnly cookiebrowser tab on bank.exampleinjectedscriptfrom an XSS buglocalStoragetoken=eyJhbGci…cookie jarsid, HttpOnlyreadsblockedsent offattackerevil.exampleHttpOnly stops theft,but the script can stillsend requests as you.
Figure 4What an XSS bug exposes. A token in localStorage can be read and sent to another machine. An HttpOnly cookie is invisible to the script, though the script can still make requests from the page while it is open.

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.

Cross-site request forgery: a page on evil.example makes the browser post to bank.example; with SameSite=None the cookie is attached, with SameSite=Lax it is notevil.exampleattacker’s pageyour browsersigned in to bankbank.exampletrusts its cookiesession cookie set with SameSite=Nonehidden form auto-submitshas a cookie for bankPOST /transfer · Cookie: sid=…transfer approvedthe same attack with SameSite=Laxhidden form auto-submitscross-site POST: no cookiePOST /transfer (no cookie)no session: 401
Figure 5CSRF. The attacker’s page never sees the bank cookie; it only needs the browser to attach it. With SameSite=Lax the browser withholds the cookie from a cross-site POST, so the bank sees an anonymous request.

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 (or Sec-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-IORbl8DkiIGKAcM6hWPxxXTO8CU
The three parts of a JWT: a base64url header, payload and signature, with the decoded header and payload shown as JSONeyJhbGciOiJIUzI1NiIs….eyJzdWIiOiI0MiIsInJv….q13e5D6SbaMb-E8-IORb…headerpayloadsignature{"alg": "HS256","typ": "JWT"}how it was signed{"sub": "42","role": "user","iss": "https://auth.example","aud": "api.example","iat": 1795251600,"exp": 1795252500}the claims, readable by anyoneHMAC-SHA256(header + "." +payload,secret)detects any change
Figure 6A real HS256 token, cut short. The header and payload are base64url-encoded JSON that anyone can decode; the signature is an HMAC over the first two parts, so any change to them is detectable.

Signed 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) and iat (issued at): seconds since 1 January 1970 UTC. Here 1795251600 is 21 November 2026 at 09:00 UTC, and the token expires 15 minutes later.
  • nbf (not before) and jti (a unique token ID) are optional; jti is 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:

Try to tamper with the token

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”.

Every signature here is a real HMAC-SHA-256 value, computed with the demo secret or, for the guessed key, with “secret”. Only the API’s verdict is simulated.

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.

HS256 uses one shared secret to sign and verify; RS256 and ES256 sign with a private key and verify with a published public keyHS256: one shared secretauth serversigns tokensAPIverifies tokenssigned JWTsecret keysigns with itverifies with itwhoever can verify a token can also forge oneRS256 or ES256: a key pairauth serverprivate key: signsany APIpublic key: verifiessigned JWTpublic key (JWKS)publishesfetchesAPIs hold only the public key, so they cannot forge tokens
Figure 7Two ways to sign. With HS256 every verifier holds the signing secret, so every verifier could forge tokens. With RS256 or ES256 only the auth server holds the private key; APIs verify with the public key, published as a JWKS.

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 inReadable by injected script?Sent automatically?Survives a reload?
A JavaScript variableYes, while the page is openNoNo
localStorageYesNo, so no CSRF riskYes
HttpOnly cookieNoYes, so defend against CSRFYes

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: Bearer header, 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.

Access and refresh tokens with rotation: a short-lived access token is used until it expires, then a refresh token is exchanged for a new pair; replaying a used refresh token revokes the familyclientbrowser or appauth serverissues tokensAPIyour resourcePOST /loginaccess (15 min) + refresh R1GET /orders · Bearer <access>check signature + exp200 OK15 minutes laterGET /orders · Bearer <access>401 token expiredPOST /token · refresh=R1R1 valid: retire it, issue R2new access + refresh R2later, an attacker replays a stolen copy of R1POST /token · refresh=R1R1 was already used: revoke R2 too401 · sign in again
Figure 8Access tokens are short-lived and checked locally by the API. When one expires, the client trades its refresh token for a new pair, and the old refresh token is retired. If a retired token ever comes back, the server assumes theft and revokes the whole chain.

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 jti values 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.

Sign in with Google using the OAuth 2.0 authorisation code flow with PKCE and an OpenID Connect ID tokenbrowserthe useryour appserverGoogleidentity providerclick “Sign in with Google”create state, nonce, verifier302 → Google + code_challengeGET /authorize?…&code_challenge=…sign in + consent302 → /callback?code=…&state=…GET /callback?code=…&state=…state matches?POST /token · code + verifierhash(verifier) ok?id_token + access_tokenverify id_token: signature, iss, aud, exp, nonceSet-Cookie: session
Figure 9“Sign in with Google” as an authorisation code flow with PKCE. The browser only ever carries a one-time code; your server swaps it, plus the PKCE verifier, for tokens over a direct connection to Google, verifies the ID token and starts its own session.
  1. Prepare. Your app generates a state value (ties the callback to this browser), a nonce (Google copies it into the ID token, so an old token cannot be replayed) and a PKCE code_verifier, and keeps them in the user’s pre-login session.
  2. Redirect. It sends the browser to Google with scope=openid email profile, the state, the nonce and a code_challenge: the SHA-256 hash of the verifier.
  3. Sign in at Google. The user authenticates with Google and agrees to share their profile. Your app sees none of this.
  4. Callback. Google redirects back to your registered redirect_uri with a one-time code and the state, which your app checks.
  5. 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.
  6. 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), exp and nonce. 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, HttpOnly and SameSite=Lax or Strict.
  • 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, iss and aud, 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, SameSite and __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, iss and aud.
  • 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