Secure Session Management
TL;DR: Set your session cookies with HttpOnly, Secure, and a reasonable expiry. Regenerate the session ID after login. These three things block most common session attacks.
A session is how your app knows that the person making a request is the same person who logged in. It works by storing a session ID in a cookie and checking it on every request.
The problem is that cookies can be stolen. There are two main ways this happens. If your cookie is accessible to JavaScript, an XSS vulnerability anywhere on your page lets an attacker read it. If your session is transmitted over HTTP instead of HTTPS, anyone on the same network can intercept it.
The HttpOnly flag stops JavaScript from accessing the cookie entirely. The Secure flag ensures it only gets sent over HTTPS. Together, they close both of those doors.
There’s also session fixation: an attacker tricks a user into starting a session with a known ID, then waits for them to log in. The fix is to regenerate the session ID immediately after a successful login.
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: true,
cookie: { secure: true, httpOnly: true }
}));
Set a reasonable expiry too. Sessions that never expire are a quiet security risk. If someone’s laptop gets stolen, an open session is as good as an open front door.
Further reading: OWASP Session Management Cheat Sheet