PassportJS and Express 4 not saving cookies / session correctly
<p>I have an app using Express 4 with Passport 0.3.2. I have set up a <code>passport-local</code> strategy, which is getting the correct user information when the <code>/session</code> endpoint is sent a username and password.</p>

<p>However the user information is never saved correctly. As such <code>req.user</code> is always undefined in all listeners and <code>req.isAuthenticated()</code> always returns false.</p>

<p>I have seen other posts which often find issues with the ordering of the middleware setup however I have ordered them in the correct way and so I am not sure where to go from here.</p>

<p>Here is my <code>POST</code> listener for <code>/session</code>:</p>

<pre><code>app.post("/session",
    passport.authenticate('local'),
    (req: any, res: any) =&gt; {
        // if we reach this point, we authenticated correctly
        res.sendStatus(201);
    }
);
</code></pre>

<p>Here is my <code>LocalStrategy</code> setup:</p>

<pre><code>passport.use(new LocalStrategy(
    (username, password, done) =&gt; {
        let users = userRepository.getAll();

        let usernameFilter = users.filter(u =&gt; u.getUsername() === username);
        if (!usernameFilter || usernameFilter.length !== 1) {
            return done(null, false, { message: 'Incorrect username.' });
        }

        if (!password || password !== "correct") {
            return done(null, false, { message: 'Incorrect password.' });
        }

        return done(null, usernameFilter[0]);
    }
));
</code></pre>

<p>Here is my app setup:</p>

<pre><code>let app = express();
app.use(cookieParser());
app.use(bodyParser.json());
app.use(expressSession({
    secret: 'my secret key',
    resave: true,
    saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
</code></pre>

<p>I am using the following dependency versions:</p>

<pre><code>"body-parser": "^1.15.1",
"cookie-parser": "^1.4.3",
"express": "^4.13.4",
"express-session": "^1.13.0",
"passport": "^0.3.2",
"passport-local": "^1.0.0"
</code></pre>

<hr>

<p>I have added a callback to my <code>POST /session</code>, however an error is thrown. This is my callback:</p>

<pre><code>app.post("/session",
    passport.authenticate('local', {
      session: false
    }),
    (req: express.Request, res: express.Response) =&gt; {
        req.logIn(req.user, (err: any) =&gt; {
            if (err)
                throw err;
        });

        // if we reach this point, we authenticated correctly
        res.sendStatus(201);
    }
);
</code></pre>

<p>I get the following error thrown:</p>

<blockquote>
  <p>Error: Failed to serialize user into session</p>
</blockquote>