CS Fundamentals Trainer · Guides

Authentication and sessions

Storing passwords (measured hashing costs), sessions and cookie flags, JWTs, XSS and CSRF, OAuth 2.0 with PKCE and OpenID Connect, one-time codes and passkeys, and the authorisation mistakes behind most breaches.

29 min read

Almost every application has to answer two questions on every request: who is this? (authentication) and what may they do? (authorisation). Getting the first one wrong lets strangers in; getting the second one wrong lets legitimate users see each other's data. This guide covers how to store passwords, how sessions and tokens carry a login from request to request, the web attacks that target them (XSS, CSRF, brute force), how "Log in with Google" really works (OAuth 2.0, OpenID Connect and PKCE), second factors and passkeys, and the authorisation mistakes behind most API breaches.

Where a claim can be checked with code, it was: the hashing times, the JWT tamper test, the one-time-password (TOTP) codes and the PKCE challenge below were all computed for this guide (Python 3.13 on a single core), and the TOTP and PKCE results were compared with the test vectors published in their RFCs.

1. Words that get mixed up

HTTP is stateless: every request stands alone. Everything below is a way to attach "this request comes from the person who logged in a minute ago" to a request, safely.

2. Storing passwords

The rule is short: never store a password, only a slow, salted hash of it, so that a stolen database does not give the attacker the passwords. Three details make the difference.

A fast hash is the wrong tool. Hashes such as SHA-256 are built to be fast, which is exactly what an attacker guessing passwords wants. On one CPU core here, plain SHA-256 computed about 1.57 million hashes per second. A password hash made to be slow takes a fixed, deliberate cost per guess:

FunctionSettingsTime for one hash (one core)
SHA-256none0.0006 ms (about 1,574,000 per second)
scryptN = 2^15, r = 8, p = 1 (32 MiB of memory)104 ms
PBKDF2-HMAC-SHA256600,000 iterations188 ms
scryptN = 2^17, r = 8, p = 1 (128 MiB)463 ms

PBKDF2 at 600,000 iterations lets an attacker try roughly 296,000 times fewer passwords per second per core than plain SHA-256. That is the entire point. The cost is small for you (one hash per login) and large for someone trying billions of guesses. Memory-hard functions such as Argon2id and scrypt are better still, because they also make fast hardware (GPUs, custom chips) expensive to build.

Every password gets its own random salt. A salt is random bytes stored next to the hash and mixed in. It makes two users with the same password produce different hashes, and it makes precomputed tables ("rainbow tables") useless. Use at least 16 random bytes from the operating system's secure random generator.

Compare in constant time. Comparing hashes with == can stop at the first different byte, and the time it takes can leak information. Use hmac.compare_digest, crypto.timingSafeEqual, subtle.ConstantTimeCompare or CryptographicOperations.FixedTimeEquals.

These samples show the shape of a password hasher. They are not meant to be copied into production. Use your framework's or a maintained library's hasher (ASP.NET Core Identity's PasswordHasher, Django's make_password, argon2-cffi, bcrypt, the argon2 package for Node), which already handle the encoding, parameter checks, upgrades and edge cases that the samples below only gesture at. If you do write one, the two points the samples try to show are: store the parameters and salt together with the hash, and never run the expensive step on a thread that other requests need.

import hashlib, hmac, os

def hash_password(password: str) -> str:
    salt = os.urandom(16)
    key = hashlib.scrypt(password.encode(), salt=salt, n=2**15, r=8, p=1, maxmem=2**26)
    # store the parameters with the hash so they can be raised later
    return f"scrypt$15$8$1${salt.hex()}${key.hex()}"

def verify_password(password: str, stored: str) -> bool:
    _, log_n, r, p, salt, key = stored.split("$")
    candidate = hashlib.scrypt(password.encode(), salt=bytes.fromhex(salt),
                               n=2**int(log_n), r=int(r), p=int(p), maxmem=2**26)
    return hmac.compare_digest(candidate, bytes.fromhex(key))

# From async code (FastAPI, aiohttp) this is a blocking call: run it off the event loop.
#   ok = await asyncio.to_thread(verify_password, password, stored)
import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";
import { promisify } from "node:util";

const scryptAsync = promisify(scrypt); // runs on libuv's thread pool, not on the event loop
const opts = { N: 2 ** 15, r: 8, p: 1, maxmem: 64 * 1024 * 1024 };

export async function hashPassword(password) {
  const salt = randomBytes(16);
  const key = await scryptAsync(password, salt, 32, opts);
  return `scrypt$15$8$1$${salt.toString("hex")}$${key.toString("hex")}`;
}

export async function verifyPassword(password, stored) {
  const [, logN, r, p, salt, key] = stored.split("$");
  const want = Buffer.from(key, "hex");
  const candidate = await scryptAsync(password, Buffer.from(salt, "hex"), want.length,
    { ...opts, N: 2 ** Number(logN), r: Number(r), p: Number(p) });
  return timingSafeEqual(candidate, want);
}
package password

import (
	"crypto/rand"
	"crypto/subtle"
	"encoding/base64"
	"errors"
	"fmt"
	"strings"

	"golang.org/x/crypto/argon2"
)

// Current cost: the OWASP minimum for Argon2id (19 MiB of memory, 2 passes, 1 lane).
const (
	memoryKiB = 19 * 1024
	passes    = 2
	lanes     = 1
	keyLen    = 32
)

var (
	enc        = base64.RawStdEncoding
	ErrBadHash = errors.New("unrecognised password hash")
)

// Hash returns a PHC-format string: $argon2id$v=19$m=19456,t=2,p=1$<salt>$<key>
func Hash(password string) (string, error) {
	salt := make([]byte, 16)
	if _, err := rand.Read(salt); err != nil {
		return "", err
	}
	key := argon2.IDKey([]byte(password), salt, passes, memoryKiB, lanes, keyLen)
	return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
		argon2.Version, memoryKiB, passes, lanes, enc.EncodeToString(salt), enc.EncodeToString(key)), nil
}

// Verify reports whether password matches the stored hash. An error means the
// stored value is not a hash this code understands, not that the password is wrong.
func Verify(password, stored string) (bool, error) {
	parts := strings.Split(stored, "$") // "", "argon2id", "v=19", "m=..,t=..,p=..", salt, key
	if len(parts) != 6 || parts[1] != "argon2id" {
		return false, ErrBadHash
	}
	var version int
	if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
		return false, ErrBadHash
	}
	var m, t uint32
	var p uint8
	if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &m, &t, &p); err != nil {
		return false, ErrBadHash
	}
	// Refuse absurd parameters from a corrupted record rather than allocating gigabytes.
	if m < 8 || m > 1<<20 || t < 1 || t > 10 || p < 1 || p > 16 {
		return false, ErrBadHash
	}
	salt, err := enc.DecodeString(parts[4])
	if err != nil || len(salt) < 8 {
		return false, ErrBadHash
	}
	want, err := enc.DecodeString(parts[5])
	if err != nil || len(want) < 16 || len(want) > 64 {
		return false, ErrBadHash
	}
	got := argon2.IDKey([]byte(password), salt, t, m, p, uint32(len(want)))
	return subtle.ConstantTimeCompare(got, want) == 1, nil
}
var salt = RandomNumberGenerator.GetBytes(16);
byte[] key = Rfc2898DeriveBytes.Pbkdf2(password, salt, 600_000, HashAlgorithmName.SHA256, 32);
// later: recompute with the stored salt and compare with CryptographicOperations.FixedTimeEquals
// (the C# sample is only the key derivation: storing the parameters and checking them is up to you)

Do not run the hash on the event loop. A password hash is deliberate, heavy CPU work, so on a single-threaded server it must not run on the thread that serves everyone else. scryptSync in Node.js (or hashlib.scrypt called directly inside an async def) blocks that thread for the whole computation. In one test, with the settings above on a 2-core container, a burst of four logins through scryptSync delayed a 10 ms timer, standing in for every other request, by about 380 to 440 ms, while the asynchronous scrypt delayed it by under 5 ms and finished the same four logins in about half the time. Treat those numbers as one illustration, not a benchmark. The asynchronous API moves the work to a worker thread, but those threads are limited too (Node's thread pool has four by default), so a login burst still queues. Rate limiting logins and capping how many hashes run at once keeps a flood from exhausting CPU and memory.

More points:

The classic design: after a successful login the server creates a random session id, stores what it needs about the session on the server (user id, time created, last seen), and sends the id to the browser in a cookie. The browser sends it back automatically with each request.

Diagram: A server-side session

The session id is a secret as good as the password for as long as it lives, so:

Set-Cookie: __Host-sid=7e1f...c9; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=1800
AttributeWhat it does
HttpOnlyJavaScript cannot read the cookie, so an XSS bug cannot copy it (it can still act as the user, see section 5)
Securesent only over HTTPS, never in clear text (see TLS and HTTPS)
SameSite=Lax or Strictthe browser does not attach the cookie to most cross-site requests, which blunts CSRF
Path=/, no Domainthe cookie belongs to exactly this host, not to its subdomains
__Host- name prefixthe browser refuses the cookie unless it is Secure, has Path=/ and no Domain, so a sibling subdomain cannot overwrite it
Max-Age / Expireshow long the browser keeps it

Same-site is not the same as same-origin. An origin is scheme, host and port (https://app.example.com). A site is coarser: the scheme plus the registrable domain, here https://example.com. So https://app.example.com and https://blog.example.com are different origins but the same site. SameSite compares sites, which has two consequences:

Browser rules like CORS and Origin checks work on origins, while SameSite works on sites, so keep the two apart when you reason about a request. Domains listed in the Public Suffix List (such as github.io) count as separate sites per subdomain.

4. Tokens and JWTs

A JSON Web Token (JWT) is a token the server can check without looking anything up. It has three base64url parts joined by dots: a header, a payload of claims (who, until when), and a signature over the first two parts.

Here is a real one, built by hand with HMAC-SHA-256 and a server secret:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyLTQyIiwicm9sZSI6Im1lbWJlciIsImV4cCI6MTg5MzQ1NjAwMH0.Ed1tR05nS_KWHgBfJvJLBvr1Z_9bla8UJFlqQ-LDSm8

Two things to see from it:

Because nothing is looked up, a JWT scales well across many services. The cost is revocation: the server cannot easily cancel one before its exp, because it kept no record. That is why access tokens should be short-lived (minutes), paired with a refresh token that is stored server-side, rotated on every use and revocable.

Server-side session idSelf-contained token (JWT)
Server stores stateyes (every request is a lookup)not to check the signature, but often elsewhere (see below)
Revoke at onceyes, delete the rowhard until it expires, unless you keep a block list
Sizetinyhundreds of bytes in every request
Good fitone web application with its own logincalls between services, third-party APIs, short-lived delegated access
Common mistakepredictable idslong lifetime, secrets in the payload

The two columns are not as separate as the table suggests. A complete system built on JWTs usually still keeps server-side state: refresh tokens that are rotated and revocable, a record of whether the account is disabled or its password was changed, and authorisation data that is checked on the server because a token's claims can be stale. Conversely, a session cookie is not safe by itself: predictable ids, missing flags, no new id at login, no expiry or no CSRF defence make it just as exposed.

So treat this as a default, not a universal rule. For an ordinary web application with its own users and one backend, a session cookie is usually the simpler place to start, because logout and revocation are a single delete. Reach for JWTs when you have a reason, such as several services verifying tokens issued by one, or delegated access for third parties, and then plan for the state they still need.

Rules when you do use JWTs (see RFC 8725):

5. Attacks that target logins

Cross-site scripting (XSS) is attacker-supplied script running inside your page. It can read anything in the page and localStorage, and it can send requests as the user. HttpOnly stops it from copying the session cookie, but not from using it, so the real fix is to prevent XSS: escape output for its context, use a framework that does it by default, and add a Content Security Policy as a second line of defence.

Cross-site request forgery (CSRF) exploits the fact that browsers attach cookies automatically. A malicious page can make the victim's browser send POST /transfer to your site, with the victim's cookie. Defences, usually combined:

Brute force and credential stuffing. Attackers try common passwords against one account, or replay email and password pairs leaked from other sites against yours. People reuse passwords, so this works. Defences: rate limit by account and by address, slow down repeated failures rather than permanently locking accounts (a lockout is itself a way to attack a user), reject breached passwords at sign-up, watch for logins from new places, and offer MFA.

Account enumeration. "No account with that email" and "wrong password" tell an attacker which emails are registered. Use one message for both ("email or password is wrong"), and make registration and password-reset responses the same whether or not the address exists ("if that address is registered, we sent a link").

Clickjacking: a page of yours inside a hidden frame on another site. Forbid framing with Content-Security-Policy: frame-ancestors 'none'.

6. OAuth 2.0 and OpenID Connect: "Log in with ..."

OAuth 2.0 lets a user give an application limited access to something held by another service without giving it a password: "let this app read my calendar". It is about authorisation. OpenID Connect (OIDC) is a thin layer on top that adds authentication: an ID token (a JWT) that tells the application who logged in. "Log in with Google" is OIDC.

The roles: the user (resource owner), the client (the application), the authorization server (Google, your identity provider) and the resource server (the API that holds the data).

The flow to use for web, mobile and single-page applications is the authorization code flow with PKCE:

Diagram: Authorization code flow with PKCE

Why it is built this way:

7. Second factors, one-time codes and passkeys

A password alone is weak because it can be guessed, reused or phished. A second factor makes a stolen password insufficient.

TOTP (time-based one-time passwords, RFC 6238) is the six-digit code in an authenticator app. Both sides share a secret, and each computes HMAC(secret, floor(time / 30 s)) and takes six digits from the result. There is no network call between the app and the server. The computation was implemented in a few lines and checked against the RFC: with the RFC's test secret 12345678901234567890, time 59 s gave 94287082 and time 1,111,111,109 s gave 07081804, the published values.

import hmac, hashlib, struct

def totp(secret: bytes, now: float, step: int = 30, digits: int = 6) -> str:
    counter = int(now // step)
    mac = hmac.new(secret, struct.pack(">Q", counter), hashlib.sha1).digest()
    offset = mac[-1] & 0x0F                      # "dynamic truncation"
    number = struct.unpack(">I", mac[offset:offset + 4])[0] & 0x7FFFFFFF
    return str(number % 10**digits).zfill(digits)

Implementation notes: accept the code from the previous and next 30-second window to allow clock drift, never accept the same code twice, rate limit attempts (there are only a million six-digit codes), keep the secret encrypted at rest, and issue recovery codes at set-up. A code sent by SMS is better than nothing but can be intercepted (SIM swapping), so prefer an app or a key.

Phishing is the weakness of one-time codes. A fake site can ask for the password and the current code and pass both on at once.

Passkeys (WebAuthn / FIDO2) are built to resist that attack. The device creates a key pair per site: the private key never leaves the device (or the user's synchronised keychain), the server stores the public key, and at login the device signs a challenge from the server. The browser includes the site's origin in what is signed, so a look-alike domain cannot obtain a usable signature. There is no shared secret to steal from your database and nothing to type. That makes passkeys resistant to credential phishing, a big step up from passwords and codes. It does not make an account impossible to compromise: a user can still be tricked into approving a request on a device they hold, an attacker who passes a weak account-recovery flow can enrol their own passkey, and malware on an unlocked device can act as the user. The recovery and enrolment paths are now the weakest link, so protect them as carefully as the login. For new products, offer passkeys, and keep a password plus TOTP or recovery option for users without them.

8. Authorisation: what the user may do

Authentication only says who. After it, every request must still be checked against what that identity may do.

9. The account life cycle

A threat-model checklist for reviews

When you review an authentication design, walk through these threats and ask what stops each one. A real review adds the threats specific to your product.

ThreatQuestion to askTypical controls
Session theftIf a session id or token leaks (XSS, a log, malware), how much can the attacker do and for how long?HttpOnly/Secure cookies, short idle and absolute timeouts, new id at login, re-authentication for sensitive actions, a list of sessions the user can revoke
Refresh-token replayWhat happens if a refresh token is used twice?rotation on every use, reuse detection that revokes the whole token family, binding to a device, storing only a hash
Account recovery abuseCan an attacker take over an account through "forgot password", email change or support staff?single-use hashed short-lived reset tokens, notification to the old address, a delay or extra check for risky changes, an identical response for unknown accounts
MFA reset and downgradeCan the second factor be removed or bypassed more easily than it was added?the same strength of check to reset as to log in, recovery codes shown once, alerts, no silent fall-back to SMS
Privilege escalationCan a normal user reach admin functions, or give themselves a role?server-side checks on every request, roles not taken from the client, deny by default, separate admin paths with stronger authentication
API object authorisationFor each endpoint that takes an id, is ownership or permission checked for that object?the check in the handler or the query (WHERE id = $1 AND owner_id = $2), tests that call each endpoint as another user
Cross-tenant accessCan a request, a cache, a background job or a report cross from one tenant to another?tenant id in every query and cache key, database-level enforcement where possible, tests with two tenants
Brute force and credential stuffingHow fast can an attacker try passwords, and would you notice?rate limits by account and address, breached-password checks, MFA, alerts on unusual logins

10. Common mistakes

  1. Storing passwords in plain text, with a fast hash such as SHA-256 or MD5, or without a salt.
  2. Comparing secrets or hashes with ==.
  3. Predictable session ids, or the same id before and after login.
  4. A session cookie without HttpOnly, Secure and SameSite.
  5. Logout that only deletes the cookie in the browser.
  6. Long-lived JWTs holding secrets, no algorithm pinned, claims not checked.
  7. Tokens in localStorage on a site that has any XSS risk.
  8. A state-changing GET, and no CSRF protection on cookie-authenticated POSTs.
  9. Different messages for "no such user" and "wrong password".
  10. Checking that the user is logged in, but not that the object is theirs.
  11. Inventing your own scheme for passwords, tokens or OAuth instead of using a maintained library or provider.
  12. Reset links that never expire, or that are stored in plain text.

11. Things to mention in an interview

Questions interviewers like to add:

Quick recap

  1. Authentication answers who; authorisation answers what, and it is checked on the server for every object.
  2. Hash passwords with a slow, salted, memory-hard function and compare in constant time. Here, SHA-256 ran about 1.57 million times per second per core, while PBKDF2 at 600,000 iterations took 188 ms and scrypt at 128 MiB took 463 ms.
  3. A session is a random id in an HttpOnly, Secure, SameSite cookie, backed by a server-side store with new ids at login and real logout.
  4. A JWT's payload is readable by anyone and its signature stops tampering; keep it short-lived, pin the algorithm and check the claims. Sessions are a sensible default for a single web app, and a full JWT system still needs server-side state for refresh tokens and revocation.
  5. XSS, CSRF, credential stuffing and enumeration each have a specific defence; HttpOnly does not stop XSS from acting as the user.
  6. OAuth 2.0 delegates access, OIDC adds login; use the authorization code flow with PKCE, an exact redirect URI and a checked state.
  7. TOTP is HMAC over a 30-second counter and can be relayed by a fake site; passkeys sign a challenge bound to the site's origin and so resist credential phishing, though account recovery and enrolment can still be attacked.
  8. Most breaches are authorisation bugs: check the object, deny by default, and never trust the client.

Sources

  1. OWASP Cheat Sheet Series, Password Storage, Session Management and Cross-Site Request Forgery Prevention. Current parameters and defences.
  2. NIST, SP 800-63B: Digital Identity Guidelines, Authentication and Lifecycle Management. Password length, breached-password checks and authenticator types.
  3. D. Hardt, RFC 6749: The OAuth 2.0 Authorization Framework, and N. Sakimura et al., RFC 7636: Proof Key for Code Exchange (the test vector in section 6 is from its Appendix B).
  4. T. Lodderstedt et al., RFC 9700: Best Current Practice for OAuth 2.0 Security.
  5. OpenID Foundation, OpenID Connect Core 1.0.
  6. M. Jones et al., RFC 7519: JSON Web Token, and Y. Sheffer et al., RFC 8725: JSON Web Token Best Current Practices.
  7. D. M'Raihi et al., RFC 6238: TOTP, Time-Based One-Time Password Algorithm (test vectors in Appendix B).
  8. W3C, Web Authentication: An API for accessing Public Key Credentials.
  9. MDN Web Docs, Set-Cookie. Cookie attributes and prefixes.

Practise this topic: Security

More guides