Overview
After you log in, a system needs to remember that you are authenticated without asking for your password on every click. It does this with a session. Sessions are convenient and essential — and, if mishandled, a rich target for attackers.
Learning objectives
- Explain what a session is and why it exists.
- Describe how session tokens and cookies work.
- Identify common session attacks and defenses.
Core concept
HTTP is stateless — each request is independent and carries no memory of previous ones. A session bridges that gap: after login, the server issues a session token (often stored in a cookie) that the browser sends with each subsequent request. The server uses the token to recognize the already-authenticated user. Alternatively, some systems use signed tokens such as JWTs that carry the identity claims directly.
How it works
A typical flow:
- User authenticates successfully.
- The server creates a session and returns a token (e.g. in a cookie).
- The browser automatically includes the token on later requests.
- The server validates the token and treats the request as authenticated.
- On logout or timeout, the session is invalidated.
Secure cookies use flags like HttpOnly (JavaScript cannot read them, reducing theft via XSS), Secure (sent only over HTTPS), and SameSite (limits cross-site sending, reducing CSRF).
Practical example
You log into a banking site and browse several pages without re-entering your password — the session cookie identifies you each time. When you click "log out," the server destroys the session so the old token no longer works. If the site set a short idle timeout, walking away also ends the session automatically.
Cybersecurity relevance
Attacks target sessions directly: session hijacking (stealing a valid token), session fixation (forcing a known token onto a victim), and cross-site request forgery (CSRF) (tricking a browser into sending its cookie on an attacker's request). Defenses include the cookie flags above, regenerating tokens after login, short timeouts, and anti-CSRF tokens.
Common mistakes
- Not invalidating sessions on logout or after a password change.
- Omitting
HttpOnly/Secure/SameSiteflags, exposing tokens to theft. - Never expiring sessions, so a stolen token works indefinitely.
Key takeaways
- A session lets a stateless protocol remember an authenticated user via a token, usually in a cookie.
- Cookie flags (
HttpOnly,Secure,SameSite) are key session defenses. - Sessions are attacked through hijacking, fixation, and CSRF; expiry and token regeneration limit the damage.
Check your understanding
- Why does HTTP being "stateless" make sessions necessary?
- What does the
HttpOnlycookie flag protect against, and how?

