The serializeUser () passport is not called with this authenticate () callback

Using passport.js, I write the route so that I have access to the MongoDb userDoc document. But at the same time, so ... passport.serializeUser() will never be called and the req object will not be user .

 auth.route('/auth/facebook/callback') .get(function(req, res, next) { passport.authenticate('facebook', function(err, userDoc, info) { if (err) { return next(err); } // I don't think !userDoc will ever happen because of mongo upsert if (!userDoc) { return res.redirect('/login'); } res.cookie('facebookPicUrl', userDoc.value.facebook.picture, {maxAge : 9999999, httpOnly: false, secure: false, signed: false }); res.redirect('http://localhost:9000/users') })(req, res, next); }); 

But if I write it this way, req.user will be what it should be:

 auth.route('/auth/facebook/callback') .get(passport.authenticate('facebook', { failureRedirect: '/login' }), function(req, res) { res.redirect('http://localhost:9000/users') }); 

How to do this, where passport.serializeUser is called, and user exists in req , and I also have access to the mongoDb object?

+5
source share
1 answer

Since you are using a custom authentication callback, you are responsible for establishing a session.

Note that when using a custom callback, it becomes responsible for creating the session (by calling req.login() ) and send a response.

req.login() assigns the user object to the req request object as req.user after the login operation completes.

You can see, for example, that in the documentation, req.login() explicitly called in a user callback:

 app.get('/login', function(req, res, next) { passport.authenticate('local', function(err, user, info) { if (err) { return next(err); } if (!user) { return res.redirect('/login'); } req.logIn(user, function(err) { if (err) { return next(err); } return res.redirect('/users/' + user.username); }); })(req, res, next); }); 
+11
source

Source: https://habr.com/ru/post/1246803/


All Articles