Course contentsShow
← Node.js
Lesson 993 of 1,9809. Authentication and Identity ManagementFree lesson

Preventing Session Fixation Attacks

Regenerate session identifiers upon user login to ensure token freshness.

In this lesson, you will learn how to neutralize session fixation attacks by ensuring your application generates a fresh session identifier every time a user successfully authenticates.

The Problem: Pre-Authenticated Sessions

A Session Fixation attack occurs when an attacker provides a victim with a valid session ID before they log in. For example, an attacker might visit your login page, copy the session cookie generated by your server, and send a crafted link containing that ID to a victim. If your application keeps using the same session ID after the victim logs in, the attacker—who already knows the ID—suddenly gains access to the victim’s authenticated session.

The Solution: Regenerating the Identifier

The defense is simple but vital: Never reuse a session ID after a privilege change. When a user transitions from an "unauthenticated" guest to an "authenticated" user, you must destroy the old session and create a brand-new one.

In a standard Node.js environment using a library like express-session, you can achieve this by invoking the session.regenerate() method during your login route:

app.post('/login', async (req, res) => {
  const user = await authenticateUser(req.body);
  
  if (user) {
    // 1. Capture existing session data if needed
    const oldSession = req.session;

    // 2. Regenerate the session ID
    req.session.regenerate((err) => {
      if (err) return res.status(500).send('Error regenerating session');

      // 3. Re-attach user data to the fresh session
      req.session.user = { id: user.id };
      
      // 4. Save and redirect
      req.session.save((err) => {
        if (err) return res.status(500).send('Error saving session');
        res.redirect('/dashboard');
      });
    });
  } else {
    res.status(401).send('Login failed');
  }
});

By calling regenerate, the server invalidates the old cookie and issues a new one. Even if an attacker knew the pre-login session ID, that ID becomes useless the moment the user completes their login, effectively locking the attacker out of the new, authenticated session.

Key Takeaway: Always trigger a session regeneration immediately upon authentication to ensure that any pre-login session identifiers cannot be leveraged for account takeover.