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
- Identification: claiming an identity ("I am ada@example.com").
- Authentication: proving it. Proof comes from something you know (a password), something you have (a phone, a security key) or something you are (a fingerprint). Using two different kinds is multi-factor authentication (MFA); two passwords are not two factors.
- Authorisation: deciding what an authenticated identity may do ("may Ada read order 42?"). It is a separate check, made on every request, by the server.
- Session: the state that remembers a successful login so the user does not send a password with every request.
- Token: a value the client presents as proof of a login or a permission. A session id is one kind of token.
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:
| Function | Settings | Time for one hash (one core) |
|---|---|---|
| SHA-256 | none | 0.0006 ms (about 1,574,000 per second) |
| scrypt | N = 2^15, r = 8, p = 1 (32 MiB of memory) | 104 ms |
| PBKDF2-HMAC-SHA256 | 600,000 iterations | 188 ms |
| scrypt | N = 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:
- Use a maintained library or your framework's password hasher instead of assembling one (see above).
- Choose the parameters from current guidance (the OWASP Password Storage Cheat Sheet lists minimums for Argon2id, scrypt, bcrypt and PBKDF2 and is updated as hardware improves), then measure on your own servers: a login should take a fraction of a second, not seconds, and a burst of logins should not exhaust memory or CPU.
- Store the parameters with the hash (as above) so you can raise the cost later. At the next successful login, if the stored parameters are older than your current ones, hash the password again and replace it.
- bcrypt is still acceptable but truncates passwords at 72 bytes; pre-hashing is a known workaround and a known source of mistakes.
- A pepper (a secret key mixed in, kept outside the database in a secret store or an HSM) adds protection if only the database leaks. It is an extra layer, not a substitute for the above.
- Password policy: current NIST guidance (SP 800-63B) favours length over complexity rules: allow long passphrases (at least 64 characters) and all characters, check new passwords against lists of breached and common passwords, and do not force periodic changes without a reason. Do not truncate or silently modify passwords.
- Never log passwords, never email them, and never put them in URLs.
3. Sessions: the cookie that remembers a login
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:
- Make it unguessable: at least 128 bits from a cryptographically secure random generator, never a counter, a timestamp or a hash of user data.
- Store it server-side in a shared store (a database or Redis), not in memory of one server, or a load balancer will send the user to a server that has never heard of them. Store only a hash of the id if you want a leaked session table to be useless.
- Create a new id at login (and when privileges change). Otherwise an attacker who planted a known session id on a victim's browser (session fixation) is logged in the moment the victim authenticates.
- Expire sessions in two ways: an idle timeout (no activity for, say, 30 minutes) and an absolute timeout (at most a few days to weeks, however active).
- Log out on the server: delete the session row. Clearing the cookie in the browser alone leaves a stolen cookie working.
- End the user's other sessions when they change their password or turn on MFA.
Cookie attributes
Set-Cookie: __Host-sid=7e1f...c9; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=1800
| Attribute | What it does |
|---|---|
HttpOnly | JavaScript cannot read the cookie, so an XSS bug cannot copy it (it can still act as the user, see section 5) |
Secure | sent only over HTTPS, never in clear text (see TLS and HTTPS) |
SameSite=Lax or Strict | the browser does not attach the cookie to most cross-site requests, which blunts CSRF |
Path=/, no Domain | the cookie belongs to exactly this host, not to its subdomains |
__Host- name prefix | the browser refuses the cookie unless it is Secure, has Path=/ and no Domain, so a sibling subdomain cannot overwrite it |
Max-Age / Expires | how 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:
SameSite=LaxorStrictdoes not stop requests that come from a sibling subdomain. Ifblog.example.comhosts user content, has an XSS bug or was taken over, its requests toapp.example.comstill carry the cookie. Check theOriginheader or use a CSRF token as well, and treat every subdomain under your registrable domain as inside your trust boundary.__Host-protects your cookie from being overwritten or shadowed by a sibling subdomain (cookie injection or "cookie tossing"), because it must have noDomainattribute. It does not remove the first problem, and it does not make a compromised sibling harmless.
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:
- The payload is not secret. It is only encoded: anyone holding the token reads
{"sub":"user-42","role":"member","exp":1893456000}. Never put secrets or private data in it. - The signature is what protects it. Changing
roletoadminin the payload while keeping the old signature made verification fail (False). Only someone with the key can produce a valid token.
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 id | Self-contained token (JWT) | |
|---|---|---|
| Server stores state | yes (every request is a lookup) | not to check the signature, but often elsewhere (see below) |
| Revoke at once | yes, delete the row | hard until it expires, unless you keep a block list |
| Size | tiny | hundreds of bytes in every request |
| Good fit | one web application with its own login | calls between services, third-party APIs, short-lived delegated access |
| Common mistake | predictable ids | long 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):
- Pin the algorithm you expect when verifying. Some early libraries accepted a token whose header said
"alg": "none"(no signature at all), or let an attacker switch from an asymmetric to a symmetric algorithm using the public key as the secret. - Check the claims:
exp(not expired),iss(the issuer you trust),aud(meant for you), andnbfif used. - Use a long random key for HMAC, or an asymmetric algorithm (RS256, ES256, EdDSA) when many services must verify tokens that one service issues, so verifiers hold only a public key.
- Where the client keeps the token matters. In
localStorageany script on the page, including injected ones, can read it. In anHttpOnlycookie scripts cannot, but then CSRF protection is needed.
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:
SameSite=Lax(orStrict) cookies. Some browsers (Chrome and Edge) already treat cookies asLaxby default, but set it explicitly.- Never change state with
GET.Laxstill sends cookies on top-levelGETnavigations. - A CSRF token: a random value tied to the session that the page includes in every state-changing request, and the server checks.
- Checking the
Originheader on state-changing requests. - APIs that read credentials from an
Authorizationheader (not a cookie) are not open to CSRF, because the browser does not add that header by itself.
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:
- The browser only carries a short-lived code, never the token itself. The application swaps the code for tokens in a direct call to the server.
- PKCE (Proof Key for Code Exchange, RFC 7636) stops someone who steals the code from using it. The application invents a random
code_verifier, sends only its hash (code_challenge = BASE64URL(SHA-256(verifier))) at the start, and reveals the verifier when it exchanges the code. A thief who has only the code does not know the verifier. The standard's own example verifierdBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXkproduced the challengeE9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cMin this guide's check, exactly as published. - The
stateparameter is a random value the application sets and checks on return, which prevents CSRF on the login itself. - Scopes list what is being asked for (
openid email,calendar.readonly); the user sees them on the consent screen. Ask for the least you need. - Redirect URIs must match exactly what you registered. Wildcards and open redirects let an attacker steer the code to their own site.
- The old implicit flow (tokens straight in the URL fragment) and the password grant (the app collects the user's password) are discouraged by the current security best practice (RFC 9700); use the code flow.
- Validate the ID token like any JWT: signature (against the provider's published keys),
iss,aud(your client id),expand thenonceyou sent. Use a maintained OIDC library for this. - An access token is for the API; an ID token is for the application to learn who the user is. Do not send an ID token to an API as if it were an access token.
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.
- Check on the server, on every request, for the specific object. The classic flaw is IDOR (insecure direct object reference, also called broken object-level authorisation):
GET /orders/42returns the order to any logged-in user, so changing the number in the URL reads other people's orders. The fix is to check ownership or permission for the object in the handler (or in the query:WHERE id = $1 AND owner_id = $2). - Deny by default. A new endpoint should be forbidden until someone grants access.
- Choose a model that fits: RBAC (role-based: admin, editor, viewer) for most applications; ABAC or relationship-based rules ("editors of this project") when access depends on the object or its owner. Keep the roles few and the check in one place.
- Do not trust the client. Hiding a button is a convenience, not a control. Hidden fields,
rolevalues in a JSON body andisAdminflags in a cookie can all be changed by the user. - Return
403or404consistently. Returning404for objects the user may not know exist avoids confirming that they do (see designing a REST API). - Least privilege for services too: a database account that can only do what the service needs, and tokens with narrow scopes.
- In multi-tenant systems make the tenant part of every query and, where the database supports it, enforce it there too (see designing a multi-tenant system).
- Log logins, failures, password and MFA changes, and permission denials, with user, time and address, but never the password or token.
9. The account life cycle
- Sign-up and email verification: send a single-use link with a long random token that expires, and treat the address as unverified until it is used.
- Password reset: generate a random token with at least 128 bits, store only its hash, make it single-use and short-lived (an hour or so), and show the same response whether or not the address exists. After a reset, end all of the user's sessions. Do not email a new password.
- Changing an email or password: ask for the current password (or a fresh MFA check) first, and notify the old address.
- Remember me: a separate long-lived token, stored hashed and rotated on use, scoped to a device, revocable from a list of the user's sessions.
- Deleting an account: remove sessions and tokens too, and plan for what happens to the data (see your privacy obligations).
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.
| Threat | Question to ask | Typical controls |
|---|---|---|
| Session theft | If 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 replay | What 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 abuse | Can 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 downgrade | Can 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 escalation | Can 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 authorisation | For 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 access | Can 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 stuffing | How 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
- Storing passwords in plain text, with a fast hash such as SHA-256 or MD5, or without a salt.
- Comparing secrets or hashes with
==. - Predictable session ids, or the same id before and after login.
- A session cookie without
HttpOnly,SecureandSameSite. - Logout that only deletes the cookie in the browser.
- Long-lived JWTs holding secrets, no algorithm pinned, claims not checked.
- Tokens in
localStorageon a site that has any XSS risk. - A state-changing
GET, and no CSRF protection on cookie-authenticatedPOSTs. - Different messages for "no such user" and "wrong password".
- Checking that the user is logged in, but not that the object is theirs.
- Inventing your own scheme for passwords, tokens or OAuth instead of using a maintained library or provider.
- Reset links that never expire, or that are stored in plain text.
11. Things to mention in an interview
- Separate authentication from authorisation and say what each looks like on a request.
- Passwords: slow, salted, memory-hard hash (Argon2id, scrypt, bcrypt or PBKDF2), constant-time compare, parameters stored and upgradable, no fast hashes. Quote the cost trade-off: 100 to 500 ms per login against billions of guesses.
- Sessions versus JWTs: a lookup and easy revocation versus cheap verification across services and hard revocation; say that the choice is a default for the situation, that real JWT systems keep refresh-token and account state on the server, and that a session is only as safe as its implementation.
- Cookie flags and what each one defends against.
- XSS, CSRF and credential stuffing: one sentence on how each works and the main defence.
- OAuth 2.0 and OIDC: explain the code flow with PKCE, and the difference between an access token and an ID token.
- MFA: TOTP, SMS and passkeys, and why passkeys resist credential phishing (origin-bound signatures) while recovery flows and device compromise remain risks.
- Authorisation: server-side, per object, deny by default, IDOR.
Questions interviewers like to add:
- "Why salt, if the hash is slow?" Salts make each user's hash different and defeat precomputed tables, so the attacker must attack each password separately.
- "Where do you store a JWT in a browser?" Either has risks:
localStorageis readable by injected script; anHttpOnlycookie is not but needs CSRF defences. A common choice is a short-lived access token in memory plus a refresh token in anHttpOnly,Secure,SameSitecookie. - "How do you log a JWT user out?" Let it expire quickly, revoke the refresh token, and keep a block list of token ids only where needed.
- "What does PKCE protect against?" A stolen authorization code being redeemed by someone who did not start the flow.
- "A user reports someone else's data in their account. Where do you look?" Object-level authorisation, caching of personalised responses, and a session or token shared between users.
- "How would you design password reset?" A single-use, hashed, short-lived token; the same response for unknown addresses; all sessions ended afterwards.
Quick recap
- Authentication answers who; authorisation answers what, and it is checked on the server for every object.
- 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.
- A session is a random id in an
HttpOnly,Secure,SameSitecookie, backed by a server-side store with new ids at login and real logout. - 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.
- XSS, CSRF, credential stuffing and enumeration each have a specific defence; HttpOnly does not stop XSS from acting as the user.
- OAuth 2.0 delegates access, OIDC adds login; use the authorization code flow with PKCE, an exact redirect URI and a checked
state. - 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.
- Most breaches are authorisation bugs: check the object, deny by default, and never trust the client.
Sources
- OWASP Cheat Sheet Series, Password Storage, Session Management and Cross-Site Request Forgery Prevention. Current parameters and defences.
- NIST, SP 800-63B: Digital Identity Guidelines, Authentication and Lifecycle Management. Password length, breached-password checks and authenticator types.
- 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).
- T. Lodderstedt et al., RFC 9700: Best Current Practice for OAuth 2.0 Security.
- OpenID Foundation, OpenID Connect Core 1.0.
- M. Jones et al., RFC 7519: JSON Web Token, and Y. Sheffer et al., RFC 8725: JSON Web Token Best Current Practices.
- D. M'Raihi et al., RFC 6238: TOTP, Time-Based One-Time Password Algorithm (test vectors in Appendix B).
- W3C, Web Authentication: An API for accessing Public Key Credentials.
- MDN Web Docs, Set-Cookie. Cookie attributes and prefixes.
Practise this topic: Security