Authentication & Sessions
How a server remembers who you are across requests, even though HTTP doesn't.
What is it?
HTTP is stateless: the server doesn't remember you between requests. Yet apps do remember you. You log in once and stay logged in. That memory is built on top of HTTP, usually in one of two ways:
- Sessions: the server tracks who's logged in and gives your browser a small id that points to your session.
- Tokens: the server gives your browser a self-contained piece of data that proves who you are, so the server stores nothing.
Explain like I'm 10
A session is like a wristband at a venue: the venue keeps a list of which wristband went to which customer and checks yours against it at each door. A token is like a signed, tamper-proof ticket that carries everything needed to prove it's valid. Nobody checks a list; they just verify the signature.
Examples
A simple session-based login flow
// 1. User logs in with correct credentials
POST /login { username: "amara", password: "..." }
// 2. Server creates a session record and sends back a cookie
Set-Cookie: sessionId=abc123; HttpOnly
// 3. Every later request automatically includes that cookie
GET /dashboard
Cookie: sessionId=abc123
// 4. Server looks up "abc123" in its session store to know who's askingHow it works
With sessions, the server stores session data (who's logged in, since when) in memory or a database under a random session id, and gives that id to the browser as a cookie. Each later request sends the cookie, and the server looks up the session.
With tokens (commonly JWTs), the server signs a small piece of data holding the user's identity. It can be verified without a lookup: the token is the proof, as long as its signature checks out.
Why does it exist?
Without it, a server couldn't tell visitors apart or remember that you already proved who you are. Every request would need your full credentials again, which is impractical and insecure.
When to use it
Use sessions when you want the server in full control, able to revoke access instantly by deleting a session record.
Use tokens to avoid a central lookup on every request, especially across several independent services. The cost: tokens are harder to revoke early.
When not to use it
Don't build authentication from scratch outside a learning exercise. Subtle mistakes (weak session ids, wrong token signature checks) are a common cause of serious security holes. Use well-established, audited libraries and frameworks instead.
Common mistakes
Storing session ids or tokens where JavaScript can read them (open to theft via XSS) instead of in an HttpOnly cookie.
Assuming a token can be revoked instantly like a session. A signed token generally stays valid until it expires unless you build extra revocation logic.
Sending credentials or session ids over plain HTTP instead of HTTPS, exposing them to anyone on the network.
Practice exercises
- Easy:
Explain in your own words why HTTP being stateless means a server needs a separate way to 'remember' a logged-in user.
- Medium:
Describe the difference between a session id and a token, and one advantage each has over the other.
- Hard:
Explain how a service could quickly revoke a compromised session versus a compromised token, and why one is harder.
Interview questions
Why can't the server just 'remember' a user across requests using HTTP alone?
HTTP is stateless by design: each request is handled on its own. Remembering a user needs a mechanism like a session or token on top.
What's the difference between a session and a token?
A session keeps the user's state on the server, found by an id the client holds. A token carries the user's state itself (signed, so it can be verified), and the server stores nothing.
Why is a token harder to revoke early than a session?
You revoke a session by deleting its record on the server. A signed token is self-contained and stays valid until it expires, unless you build extra revocation tracking.
What's the difference between authentication and authorization?
Authentication answers 'who are you?' by verifying identity, usually with credentials. Authorization answers 'what are you allowed to do?' for a user already identified.
What is a cookie, and how does the browser know to send it automatically on future requests?
A small piece of data the server asks the browser to store via a Set-Cookie header. The browser then attaches it to every later request to the same domain (within the cookie's scope) in the Cookie header, without app code doing it.
What does the HttpOnly flag on a cookie protect against?
It stops page JavaScript from reading the cookie. Even if an attacker injects a script (XSS), they can't directly steal a session id or token stored in an HttpOnly cookie.
What does the Secure flag on a cookie do?
The browser only sends that cookie over HTTPS, so it's never exposed in plaintext over unencrypted HTTP.
What is the SameSite cookie attribute, and what problem does it help prevent?
It controls whether a cookie is sent with requests that come from a different site than the one that set it. Strict or Lax stops the browser from attaching a user's session cookie to requests forged by a malicious site (CSRF).
What is CSRF (Cross-Site Request Forgery), and how does SameSite help mitigate it?
CSRF tricks a logged-in user's browser into sending an unwanted authenticated request, embedded on a malicious page. It works because browsers normally attach cookies no matter where a request starts. SameSite blocks the cookie on requests that come from another site.
What is XSS (Cross-Site Scripting), and why does it matter for deciding where to store an auth token?
XSS injects malicious script into a trusted page (e.g. via unescaped user input) and runs it there. Anything JavaScript can read, like localStorage, that script can steal; an HttpOnly cookie it cannot.
Why is storing a JWT in localStorage often discouraged compared to an HttpOnly cookie?
Any script on the page can read localStorage, so a successful XSS attack can steal the token. An HttpOnly cookie is invisible to JavaScript, closing that route (though cookies bring their own CSRF concerns).
What is a JWT structurally made up of?
Three base64url-encoded parts separated by dots: a header (the algorithm used), a payload (the claims, like user id and expiry), and a signature (computed over header and payload to detect tampering).
Does base64-encoding a JWT's payload make its contents secret? Why or why not?
No. base64 is an encoding, not encryption, so anyone can decode and read the payload. The signature only proves it wasn't altered. Never treat a JWT as confidential or put sensitive data in it unless it's also encrypted.
How does a server verify that a JWT hasn't been tampered with?
It recomputes the signature over the header and payload with its secret (or the public key, for asymmetric signing) and checks it matches the token's signature. Any change to header or payload gives a different signature and fails.
What's the difference between signing a JWT with a symmetric secret (HMAC) versus an asymmetric key pair (RSA/ECDSA)?
With HMAC, one secret both signs and verifies, so any service that can verify a token could also forge one. With a key pair, only the private-key holder can sign, while any number of services verify with the public key and can't create tokens.
Why might a system use short-lived access tokens paired with longer-lived refresh tokens?
A short-lived access token limits how long a stolen one is useful. The refresh token (kept more securely, used less often) gets new access tokens without making the user log in again. It balances security and convenience.
What happens if a refresh token is stolen, and how do systems typically mitigate that risk?
An attacker could keep minting new access tokens. Systems use refresh token rotation (a new refresh token on each use, the old one invalidated) and treat reuse of an already-rotated token as a sign of theft.
Why do session-based systems scale less trivially across multiple servers than token-based systems, and how is that usually solved?
A session lives on the server that created it, so a request landing on another server won't find it unless state is shared. The usual fixes are a shared session store (like Redis) every server reads, or routing a client back to the same server (sticky sessions).
What is a sticky session, and what problem does it cause for load balancing?
A load balancer setting that sends all of a client's requests to the same backend, so its in-memory session stays available. It weakens even load spreading, and losing that server hits all clients pinned to it.
Why is storing passwords in plain text always wrong, regardless of any other security measures in place?
If the database is ever exposed (a leak, a misconfigured backup, an insider), every real password is revealed. Since people reuse passwords, one breach can compromise their accounts on other sites too.
What is password hashing, and why is a slow, purpose-built algorithm like bcrypt preferred over a fast general-purpose hash like SHA-256?
Hashing stores a one-way transformation of the password, not the password. bcrypt and similar algorithms are deliberately slow and tunable, making mass guessing expensive. A fast hash like SHA-256 lets an attacker try billions of guesses per second on stolen hashes.
What is a salt, and what attack does it protect against?
Random data, unique per user, added to a password before hashing. It defeats precomputed rainbow-table attacks and hides when two users share a password, since the same password gives different hashes once salted.
Why is sending credentials over plain HTTP a serious vulnerability, even if the password is hashed before storage?
Hashing protects the password at rest in the database. Over plain HTTP, anyone watching the network (e.g. on shared Wi-Fi) can capture the plaintext password in transit, before the server ever hashes it.
What is multi-factor authentication (MFA), and why does it improve security beyond a strong password alone?
MFA requires more than one independent factor: something you know (a password) plus something you have (a phone) or something you are (a fingerprint). A stolen or guessed password alone isn't enough without the second factor.
What is OAuth, and what problem does it solve that a plain username/password login doesn't?
A protocol for delegated access. A user grants one app limited access to their data on another service without giving that app their password, so third-party apps never hold credentials they shouldn't be trusted with.
What's the difference between using OAuth for delegated access and using it for 'Sign in with Google/GitHub'-style login?
Delegated access grants a specific scope of permission on a resource (like reading a user's calendar). 'Sign in with' login reuses the same flow only to confirm identity (via OpenID Connect on top of OAuth), without necessarily requesting access to other data.
Why is it a mistake to treat a valid JWT signature as proof that a user's access hasn't been revoked?
A valid signature only proves the token is untampered and was issued by the server. It says nothing about revocation: a self-contained token passes that check until it expires, unless the system tracks revocations separately.
Describe a realistic scenario where you'd choose token-based auth over session-based auth.
Several independent backend services (microservices, or a public API used by many clients). Any service with the public key (or shared secret) can verify identity on its own, with no central session store every service must query.
Describe a realistic scenario where you'd choose session-based auth over token-based auth.
A traditional server-rendered web app with one backend (or a few tightly coupled services). Sessions give easy, immediate revocation (delete the record) and avoid token problems like revocation lists or key distribution across services it doesn't have.
Why should session ids and tokens be generated using a cryptographically secure random generator rather than something predictable?
If an id can be guessed (e.g. from a counter or weak random source), an attacker can forge a valid session id or token for another user without stealing anything, defeating the whole mechanism.