Hi,
I've been struggling to user req.user using a custom callback for authenticate.
The code i'm using is the following:
router.post('/in', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err); // Error 500
}
if (!user) {
//Authentication failed
return res.json(401, { "error": info.message });
}
//Authentication successful
res.send(200);
})(req, res, next);
}); `
With this code, accessing req.user return undifined.
Sadly, adding this line
req.user = user
after
//Authentication successful
won't work.
However, adding
req.session.user = user works !
In addition, without the custom callback, req.user is correctly set.
I think I've pointed out an unexpected behavior, or maybe I'm doing something wrong.
Regards
Got the same problem. It appeared after upgrading from Express 3 to Express 4
I think it is related to the fact that you are using a custom callback without using the req.login method, not to whether you're using Express 3 or 4.
From the docs, _"Note that when using a custom callback, it becomes the application's responsibility to establish a session (by calling req.login()) and send a response."_
You should add this code if your authentication is successful :
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/users/' + user.username);
});
@WaldoJeffers I stumbled upon this same problem and your answer is correct. Thanks!
Most helpful comment
I think it is related to the fact that you are using a custom callback without using the
req.loginmethod, not to whether you're using Express 3 or 4.From the docs, _"Note that when using a custom callback, it becomes the application's responsibility to establish a session (by calling req.login()) and send a response."_
You should add this code if your authentication is successful :