Intermediate LevelExpress JS
Why must you call req.session.regenerate() upon user login to prevent Session Fixation security attacks?
❓ Interview Prompt: Explain Session Fixation vulnerabilities, session ID rotation, and calling req.session.regenerate() on authentication.
In a Session Fixation attack, an attacker obtains a valid anonymous session ID cookie and tricks a victim into logging in with it. If the application retains the same session ID after login, the attacker gains authenticated access!
Defense:
Always call 'req.session.regenerate(callback)' immediately upon successful user login to issue a brand new session ID cookie and purge old session data!
Code Implementation Example
javascript
app.post('/login', (req, res) => {
if (req.body.user === 'admin' && req.body.password === 'secret') {
// Regenerate session ID to prevent Session Fixation attacks!
req.session.regenerate((err) => {
if (err) return res.status(500).json({ error: 'Session error' });
req.session.authenticated = true;
res.json({ message: 'Authenticated safely with new session ID' });
});
}
});💡Regenerating session ID on login to defeat Session Fixation attacks.
🎯 Interview Key Takeaway
Call req.session.regenerate() on user authentication to issue a new session ID and defeat Session Fixation.
#Session Fixation#express-session#Security#Intermediate
Back to all Express JS Questions→