CS Fundamentals Trainer · Guides
Authentication and sessions: passwords, cookies, tokens and OAuth without the folklore
How to store passwords, what a session is and how session cookies are protected, when a signed token (JWT) is a good idea and when it is not, how OAuth 2.0 and OpenID Connect divide the work between authorization and login, multi-factor authentication and passkeys, and the mistakes that show up in most breach reports.
5 min read
Authentication answers "who is this?". Authorization answers "what may they do?". They are separate problems, and mixing them up is behind many bugs. This guide covers the first one: how a system recognises a user and keeps recognising them for the next request.
Passwords
Never store a password; store the output of a password hashing function designed to be slow and memory-hungry: Argon2id (first choice), scrypt or bcrypt. A general-purpose hash such as SHA-256 is far too fast: a GPU can try billions per second.
- Each password gets a unique random salt, stored beside the hash. It means that identical passwords give different hashes and that precomputed tables do not work. The libraries do this for you; use their
hashandverifyfunctions and the stored string that contains the parameters. - Tune the cost so that one hash takes tens of milliseconds on your server, and revisit it every few years. Store the parameters so you can rehash on login when they change.
- A pepper (a secret kept outside the database, such as in a key vault) adds protection if only the database leaks.
- Compare secrets with a constant-time function to avoid timing leaks.
- Follow current guidance (NIST SP 800-63B): require length (at least 8, allow 64 or more), allow any characters including spaces and paste, check against lists of breached passwords and do not force periodic changes or composition rules.
- Rate-limit login attempts per account and per address, and respond identically whether the user exists or not.
- Reset by a single-use, short-lived, random token sent to a verified channel. Store only its hash, and invalidate other sessions after a reset.
Sessions
HTTP has no memory, so after a login the server issues something the browser sends back each time. The classic design is the server-side session: a long random identifier (at least 128 bits from a secure random generator) goes into a cookie, and the server looks it up in a store (database, Redis) to find the user. Because the state is on the server, you can revoke a session instantly.
Cookie attributes that matter:
HttpOnly: JavaScript cannot read it, so XSS cannot steal it directly.Secure: sent only over HTTPS.SameSite=Lax(orStrict): not sent on most cross-site requests, which blocks most CSRF.- Scope it narrowly (
Path, no wideDomain), and prefer the__Host-prefix, which forcesSecure,Path=/and noDomain. - Set an idle timeout and an absolute lifetime.
Rules in the flow: issue a new session id on login (otherwise an attacker who planted an id before login, called session fixation, shares it), destroy the session on logout, and ask for the password again before sensitive actions (change email, add a payment method).
Tokens and JWTs
A JSON Web Token is a signed (and sometimes encrypted) JSON document: header.payload.signature. The server can check a signature without a lookup, which is why JWTs are popular for APIs and across services. The trade-offs are real:
- Revocation is hard. A valid token stays valid until it expires, unless you keep a deny list, which brings back the lookup. Keep access tokens short (minutes) and use a refresh token that the server can revoke.
- The payload is readable by anyone (it is only encoded). Never put secrets in it.
- Verify everything: signature with a fixed, expected algorithm (reject
noneand algorithm switching),exp,nbf,issandaud. - Where to keep it in a browser:
localStorageis readable by any script on the page, so XSS steals it; anHttpOnlycookie is not. For a browser app on your own domain, an ordinary session cookie is usually simpler and safer than JWTs.
Use JWTs when several independent services must validate identity without calling a central store; otherwise a server-side session is the boring, safe choice.
OAuth 2.0 and OpenID Connect
OAuth 2.0 is about delegated authorization: letting an application act on your behalf at another service without handing it your password. It gives the app an access token with limited scopes. It does not say who you are.
OpenID Connect (OIDC) adds an identity layer on top: an ID token (a JWT) that says who logged in, issued by an identity provider. "Sign in with X" is OIDC.
For web and mobile applications, use the authorization code flow with PKCE:
- The app sends the browser to the provider with a random
state(CSRF protection) and a PKCEcode_challenge. - The user signs in at the provider and consents.
- The provider redirects back with a one-time
code. - The app's server exchanges the code plus the PKCE
code_verifierfor tokens. - The app validates the ID token (
iss,aud,exp,nonce) and creates its own session.
The implicit flow (tokens in the URL fragment) and the password grant are deprecated. Register exact redirect URIs, and never accept an arbitrary redirect_uri.
Multi-factor authentication and passkeys
A second factor defeats the most common attack, reuse of leaked passwords. In order of strength: passkeys/WebAuthn and hardware keys (phishing-resistant, because the credential is bound to the real site's domain), app-based one-time codes (TOTP), then SMS (weakest: SIM swapping, interception). Offer recovery codes, and treat the recovery path as part of the attack surface.
Mistakes that keep appearing
- Fast hashes, unsalted hashes, or reversible encryption of passwords.
- Session ids that are predictable or are not rotated at login.
- Tokens in URLs (they leak through logs and
Referer). - Verifying a JWT's signature but not its audience, issuer or expiry.
- Different error messages for "no such user" and "wrong password".
- No rate limit on login, reset and code-verification endpoints.
- Trusting client-supplied identity (a
userIdin the request body) instead of the session. - Long-lived, never-rotated API keys in code repositories.
Sources
- OWASP Authentication Cheat Sheet and Session Management Cheat Sheet.
- OWASP Password Storage Cheat Sheet.
- NIST SP 800-63B: Digital Identity Guidelines, Authentication.
- RFC 7636: Proof Key for Code Exchange (PKCE) and OpenID Connect Core 1.0.
- RFC 8725: JSON Web Token Best Current Practices.
Practise this topic: Security