A session is a temporary connection between a user and a web server that persists across multiple HTTP requests. Since HTTP is stateless (each request is independent), sessions provide a mechanism to identify returning requests as coming from the same logged-in user.
How Sessions Work
- You log in to a website. The server creates a session record in its storage (database, memory, cache).
- The server sends a unique session ID to your browser, usually in a cookie.
- Your browser sends this session ID cookie with every subsequent request.
- The server looks up the session ID to identify you and your permissions.
- When you log out (or the session expires), the server deletes the session record.
Session vs Cookie
- The session is stored on the server. The server holds your identity and data.
- The cookie is stored in the browser. It contains just the session ID — a reference, not the data itself.
Session Security
- Session hijacking — If an attacker steals a session ID (via XSS or sniffing), they can impersonate the user.
- Session fixation — Attacker sets a known session ID before login; user unknowingly authenticates it.
- Session expiry — Sessions should expire after inactivity (typically 15–60 minutes for sensitive apps).
Best Practices
- Always use HTTPS to prevent session ID interception.
- Use
HttpOnlyandSecureflags on session cookies. - Regenerate the session ID after login.
- Implement idle session timeouts.