Authentication & Password Hashing
How a backend verifies who's making a request, without storing raw passwords, and keeps recognizing a logged-in user on later requests.
What is it?
A backend often needs to know "who sent this request, and are they allowed to do this?" Authentication is proving identity, usually by checking a password at login.
The most important rule: never store a user's actual password. Store a hash instead: the output of a one-way function (like bcrypt or argon2) that scrambles the password so it can't be reversed, even if the whole database leaks. At login, you hash the submitted password the same way and compare the two hashes. The plaintext password is never stored or compared directly.
HTTP doesn't remember anything between requests, so after login the backend needs a way to keep recognizing the user:
- a session: the server remembers who's logged in and gives the browser a cookie holding just an id to look it up, or
- a token like a JWT: a small, signed packet of data the client holds and resends, which the server can verify without storing anything.
Explain like I'm 10
Hashing a password is like a paper shredder: you get confetti out, and you can't feed it back in to rebuild the page. To check a password later, you shred the newly typed one the same way and compare the confetti. You never keep the original page.
Examples
Hashing on signup, comparing on login (bcrypt)
const bcrypt = require("bcrypt");
// Signup: hash before storing anything
const passwordHash = await bcrypt.hash(plainPassword, 10);
await pool.query(
"INSERT INTO users (email, password_hash) VALUES ($1, $2)",
[email, passwordHash]
);
// Login: compare against the stored hash
const user = await findUserByEmail(email);
const isValid = user && (await bcrypt.compare(submittedPassword, user.password_hash));
if (!isValid) return res.status(401).json({ error: "invalid credentials" });The plaintext password only exists briefly in memory. The database stores password_hash, never the password, and login compares hashes instead of 'unhashing' anything.
Protecting a route with an auth middleware
function requireAuth(req, res, next) {
const token = req.headers.authorization?.split(" ")[1];
if (!token || !isValidToken(token)) {
return res.status(401).json({ error: "unauthorized" });
}
req.user = decodeToken(token);
next();
}
app.get("/profile", requireAuth, (req, res) => {
res.json(req.user);
});This is the requireAuth middleware from the middleware topic. It runs before the route handler and only calls next() once it has confirmed who the caller is.
The same idea in FastAPI — a dependency instead of middleware
from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import OAuth2PasswordBearer
import jwt
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login")
def get_current_user(token: str = Depends(oauth2_scheme)):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
except jwt.InvalidTokenError:
raise HTTPException(status_code=401, detail="invalid token")
return payload
@app.get("/profile")
async def profile(user: dict = Depends(get_current_user)):
return userOAuth2PasswordBearer tells FastAPI where to find the token (an Authorization: Bearer <token> header) and passes it to get_current_user, which decodes the JWT and verifies its signature. Same protection as requireAuth, written as a dependency instead of a middleware step.
How it works
Password-hashing algorithms (bcrypt, scrypt, argon2) are deliberately slow and mix a random salt into every password. Two users with the same password get different hashes, so an attacker can't precompute one shared table of hashes to crack many accounts at once (a "rainbow table").
After login, there are two ways to stay recognized on later requests:
- A session stores the logged-in state on the server and gives the browser a cookie holding just an id to look it up.
- A token like a JWT carries the identity data itself, signed so the server can verify it wasn't tampered with, without storing anything server-side.
Why does it exist?
If a database stored passwords directly, any breach, backup leak, or careless insider would expose every user's real password at once. People reuse passwords across sites, so the damage spreads beyond your app. Hashing makes stored passwords useless to an attacker even if the whole database is exposed.
Authentication as a whole exists because otherwise a server can't tell a returning, legitimate user from anyone sending a similar request.
When to use it
Any system with real user accounts needs authentication. Hash wherever a password is stored, and use a session or token wherever the backend must keep recognizing a logged-in user across requests.
When not to use it
Don't hand-roll password hashing or session handling for anything real. Use a well-audited library (bcrypt, argon2) or a full auth framework/service. Subtle cryptographic mistakes are easy to make and very costly. Internal tools with no real user accounts may not need full authentication at all.
Common mistakes
Storing passwords in plaintext, or hashing them with a fast general-purpose hash (like MD5 or SHA-256) instead of a slow, purpose-built one like bcrypt.
Hashing manually without a salt and comparing with simple equality, so identical passwords produce identical hashes and rainbow-table attacks work.
Confusing authentication ('who are you?') with authorization ('what are you allowed to do?'). Being logged in doesn't mean access to every resource.
Practice exercises
- Easy:
Explain why a database breach is far less damaging if passwords were hashed with bcrypt instead of stored as plaintext.
- Medium:
Write a signup and login flow using bcrypt.hash and bcrypt.compare, including the SQL to store and look up a user's password_hash.
- Hard:
Explain the difference between session-based and token-based (JWT) authentication, including exactly where the 'you're logged in' state lives in each.
Interview questions
Why shouldn't passwords ever be stored in plaintext?
Anyone who gets into the database (through a breach, an insider, or a leaked backup) gets every user's real password at once. People reuse passwords, so the damage spreads beyond your app.
What's the difference between hashing and encryption for storing passwords?
Encryption is reversible with the right key. Hashing is designed to be irreversible, which is what you want for passwords: you only need to verify a match, never recover the original.
What's the difference between authentication and authorization?
Authentication confirms who a user is. Authorization decides what that authenticated user is allowed to do.
What is a salt, and what specific attack does it defeat that hashing alone doesn't?
Random data, unique per user, mixed into a password before hashing. Without it, users with the same password get identical hashes, so an attacker can precompute one table of hashes for common passwords (a rainbow table) and crack every matching account at once. A per-user salt makes each hash unique, so no precomputed table works.
With bcrypt, where is the salt actually stored, and why doesn't that make it useless?
It's embedded in the hash string itself, so no separate column is needed. That's safe because a salt doesn't need to be secret, only unique per password. It forces an attacker to redo the expensive hashing for each user instead of reusing one precomputed table.
What does the cost factor passed to bcrypt, like the 10 in `bcrypt.hash(password, 10)`, actually control?
How many times the algorithm iterates internally. Each increment roughly doubles the time per hash. A real login pays that cost once, but an attacker pays it for every guess, which makes large-scale guessing impractical.
Why can't you simply use a fast, general-purpose hash like SHA-256 for passwords, even though it's cryptographically secure?
SHA-256 is built to be fast, which is exactly wrong here. An attacker with a stolen hash can try billions of guesses per second on cheap hardware, especially GPUs. bcrypt, scrypt, and argon2 are deliberately slow and tunable to make brute-forcing expensive.
What's a pepper, and how does it differ from a salt?
A single secret value (a salt is per-user) applied to every password before hashing and kept outside the database, e.g. in an environment variable or secrets manager. A database leak alone then isn't enough to brute-force any password, since the attacker also needs the pepper.
How does `bcrypt.compare(submittedPassword, storedHash)` work without ever reversing the stored hash back into the original password?
It takes the salt embedded in storedHash, hashes submittedPassword with that salt and cost factor, and checks the two hash strings for equality. It compares two hashes; it never decrypts the stored one.
What's a timing attack in the context of comparing a submitted password's hash to a stored one, and how do hashing libraries defend against it?
A naive comparison stops at the first mismatched character, so its timing can leak how many leading characters were right. Good libraries use a constant-time comparison that takes the same time wherever, or whether, a mismatch occurs, so timing reveals nothing.
What are the three parts of a JWT, separated by dots, and what does each contain?
A header (token type and signing algorithm), a payload (claims like a user id and expiration), and a signature computed over the header and payload with a secret or private key. Written as header.payload.signature, each part base64url-encoded.
Is the payload of a JWT encrypted — can anyone read it just by decoding it?
No. A standard JWT payload is only base64url-encoded, so anyone holding the token can decode and read it. The signature proves the payload wasn't tampered with but doesn't hide it, so don't put sensitive data in a JWT payload.
What does verifying a JWT's signature actually protect against, if the payload itself isn't secret?
Tampering. If someone changes the payload, like a role claim from "user" to "admin", they can't compute a valid signature without the server's secret key. Verification recomputes the expected signature and rejects any token changed after issue.
What's the `alg: none` JWT vulnerability, and how is it typically prevented?
Some poorly written verification code trusted the token's own alg header, including "none" (no signature), and skipped verification. An attacker could craft a token with alg: none and any claims and have it accepted. The fix: the verifier specifies and enforces which algorithm it accepts, ignoring what the token claims.
Why is it a mistake to let JWT verification accept whatever algorithm the token specifies, rather than pinning to one expected algorithm?
An attacker can confuse asymmetric signing (like RS256, verified with a public key) with symmetric signing (like HS256, verified with a shared secret), e.g. getting a public key treated as an HMAC secret. A forged token is then accepted as valid. Requiring one known algorithm closes this off.
What claim in a JWT controls when it expires, and what happens if verification code forgets to check it?
The exp claim, a Unix timestamp. If it isn't checked, a token stays 'valid' forever, which defeats the point of expiration.
Why can't a JWT be 'logged out' or revoked the same simple way a session can?
A session is looked up on the server each request, so deleting its record invalidates it right away. A JWT is self-contained and checked only by its signature, with nothing to look up. Without a separate server-side revocation list, the server can't invalidate an issued token before it expires.
What's a common approach to work around the difficulty of revoking JWTs immediately?
Keep JWT lifetimes short (minutes, not days) and pair them with a longer-lived refresh token tracked server-side, which can be revoked. Revoking it stops new access tokens from being issued, though any already-issued short-lived token still works until it expires soon after.
What's a refresh token, and how does its lifecycle typically differ from an access token's?
A longer-lived credential, stored server-side so it can be revoked, used only to get a new short-lived access token when the old one expires. The access token goes with every API request. The refresh token is used rarely, so the more sensitive credential is sent less often.
What's the security tradeoff of storing a JWT in localStorage versus in an httpOnly cookie?
Any JavaScript on the page can read localStorage, so an XSS bug can steal the token. JavaScript can't read an httpOnly cookie, which protects against XSS. But the browser sends cookies automatically on matching requests, which opens a different risk, CSRF, needing its own defenses like a SameSite attribute or a CSRF token.
What is session fixation, and how does it differ from simply stealing a session cookie?
Instead of stealing a session, the attacker gets the victim to log in with a session id the attacker already knows (e.g. by pre-setting it before login). Once authenticated, the attacker uses that same id. The standard defense: generate a new session id at successful login, invalidating the old one.
Why should a login endpoint return the same generic error message whether the email doesn't exist or the password is wrong, rather than distinguishing the two?
Different messages for 'no such user' and 'wrong password' let an attacker find out which emails have accounts, one guess at a time. One generic message reveals nothing about which part was wrong.
Why should login attempts be rate-limited per account or per IP?
Without a limit, an attacker can automate unlimited password guesses. Rate limiting (locking out or slowing down after several failures) makes large-scale guessing impractical, on top of the per-guess cost the hashing algorithm already adds.
What's a secure way to implement a 'forgot password' flow, at a high level?
Generate a single-use, random, unguessable token unrelated to the password. Store its hash server-side with a short expiration, and email a link with the token to the account's address. Only allow a new password if a matching, unexpired token is presented. Never email the existing password; if you could, it wasn't properly hashed.
Why should a password-reset token be single-use and short-lived?
A token that works after use, or never expires, can take over the account indefinitely if it's ever intercepted, e.g. from a compromised email account or logged browser history. Single use and short expiry shrink the window an intercepted token would work.
What does multi-factor authentication add on top of a password, and why does it meaningfully raise security even if the password is compromised?
It requires a second, independent proof of identity, often a time-based one-time code from an authenticator app or a hardware key. A leaked or guessed password alone isn't enough. The attacker also needs the second factor, which the same breach usually doesn't expose.
Why is serving a login form and its endpoint only over HTTPS essential, regardless of how well passwords are hashed server-side?
Hashing only protects the stored password. Over plain HTTP, the submitted password, and any session cookie or token sent afterward, crosses the network unencrypted and can be read by anyone watching the traffic. HTTPS protects credentials in transit; hashing at rest doesn't.
What's the difference between authentication middleware reading a token from an Authorization: Bearer header versus from a cookie?
With a Bearer header, the client attaches the token to every request itself, which is common for non-browser API clients or SPAs managing their own tokens. A cookie is attached by the browser automatically, which is convenient but is exactly what enables CSRF unless mitigated.
In a `requireAuth` middleware pattern, why does it call `next()` only after successfully decoding the token, rather than always calling it?
Calling next() unconditionally would run the route whether or not the caller is authenticated. Calling it only after the token check passes means the protected handler never runs for an invalid request. A 401 is returned instead and the chain stops.
Why must the same secret, or key pair, used to sign a JWT also be available wherever it needs to be verified?
The verifier recomputes the expected signature with that secret or key and compares it to the token's signature. Without the right secret (or the matching public key for asymmetric signing), it can't confirm authenticity. So the secret needs protecting just like a password.
What's the practical effect of rotating the secret key used to sign JWTs?
Every existing token was signed with the old key. Once the app verifies only with the new key, all of them fail verification and are effectively invalidated. That's useful to force a universal logout after a suspected key leak, but it logs out every user at once, not just a targeted few.
Why does the column name `password_hash` matter beyond just being descriptive?
It helps prevent a costly mistake: writing or logging a raw password field in code that assumes the column holds the real password. The name makes it explicit everywhere that the stored value is a hash.
What's argon2's relationship to bcrypt, and why might a newer system choose it instead?
Argon2 is a newer password-hashing algorithm that won the 2015 Password Hashing Competition. Unlike bcrypt, it lets you tune memory use as well as compute cost, requiring lots of RAM per hash. That makes it more resistant to GPUs and custom hardware built for fast computation but not large memory.
Where does the boundary sit between what 'authentication' implementation covers, like hashing and JWTs, and the broader conceptual question of sessions vs. tokens as an architectural choice?
How passwords are hashed and verified, and how a JWT is structured, signed, and checked, are details of the login step itself. Whether to keep users recognized with server-side sessions or client-held tokens is a wider architectural tradeoff (statelessness, scaling, revocation) that goes beyond password login, and is covered in its own system-design topic.