Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PassportJS and Express 4 not saving cookies / session correctly

I have an app using Express 4 with Passport 0.3.2. I have set up a passport-local strategy, which is getting the correct user information when the /session endpoint is sent a username and password.

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

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.

Here is my POST listener for /session:

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

Here is my LocalStrategy setup:

passport.use(new LocalStrategy(
    (username, password, done) => {
        let users = userRepository.getAll();

        let usernameFilter = users.filter(u => 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]);
    }
));

Here is my app setup:

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());

I am using the following dependency versions:

"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"

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

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

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

I get the following error thrown:

Error: Failed to serialize user into session

like image 580
James Monger Avatar asked Jun 13 '16 22:06

James Monger


1 Answers

I found this question from a Google search when I had a related problem.

What I realized was that express-session doesn’t persist sessions e.g. between server restarts. Read here for more info.

So I swapped express-session for cookie-session instead:

app.use(cookieSession({
    name: 'MyAppName',
    keys: ['very secret key'],
    maxAge: 30 * 24 * 60 * 60 * 1000 // 30 days
}));

And then PassportJS was persisting my sessions, no further change needed!

like image 65
Tom Söderlund Avatar answered Sep 29 '22 01:09

Tom Söderlund