Passport authentication callback hangs

偶尔善良 提交于 2021-02-10 04:35:52

问题


After hours trying to solve this by myself I reach to SO community looking for some light.

I'm using passport for user authentication. It's already initialized in my main express.js file as per the docs:

app.use(passport.initialize());

I got a index.js file which handles facebook-passport in this manner: Index.js

'use strict';

import express from 'express';
import passport from 'passport';
import auth from '../auth.service';
let router = express.Router();

//this function is defined in the auth.service import but copied it here in case it's needed (the `signToken` is also defined in the service)
function setTokenCookie(req, res) {
  if (!req.user) return res.json(404, { message: 'Something went wrong, please try again.'});
  var token = signToken(req.user._id, req.user.role);
  res.cookie('token', JSON.stringify(token));
  res.redirect('/');
}


router
  .get('/', passport.authenticate('facebook', {
    scope: ['email', 'user_about_me'],
    failureRedirect: '/login'
  }))

.get('/callback', passport.authenticate('facebook', {
  successRedirect: '/',
  failureRedirect: '/login'
}), setTokenCookie);

module.exports = router;

And the passport.js that's being imported in the index.js in this manner:

passport.js

import passport from 'passport';
import {
  Strategy as FacebookStrategy
}
from 'passport-facebook';

exports.setup = function(User, config) {
  passport.use(new FacebookStrategy({
      clientID: config.facebook.clientID,
      clientSecret: config.facebook.clientSecret,
      callbackURL: config.facebook.callbackURL
    },
    function(accessToken, refreshToken, profile, done) {
      User.findOne({
        'facebook.id': profile.id
      }, (findErr, user) => {
        if (findErr) {
          return done(findErr);
        }
        if (!user) {
          let userToSave = new User({
            name: profile.displayName,
            email: profile.emails[0].value,
            role: 'user',
            username: profile.username,
            provider: 'facebook',
            facebook: profile._json
          });
          userToSave.save((saveErr) => {
            if (saveErr) done(saveErr);
            return done(null, user);
          });
        } else {
          return done(null, user);
        }
      });
    }
  ));
};

This is what currently happens:

  • Facebook login is prompted
  • After successful authentication in Facebook the callback (/auth/facebook/callback) IS reached with user info and token as expected.
  • User is saved in DB with expected fields

Where things get weird:

  • After saving the User, the done(null,user) does nothing. The app hangs on the callback and client keeps waiting for response.
  • The middleware setTokenCookie never gets called so the problem is definitely in the previous step.

What I've tried:

  • Wrapping the whole setup function from passport.js in a process.tick (found some people use it but didn't resolve the issue)
  • Using Mongoose with promise as in User.findOne({...}).exec().then(user => {...})

If you need additional information please don't hesitate to ask. Any help is really appreciated.

Thanks!


回答1:


If you're a noob to passport/express like me, this may help:

check if you invoke done() in your passport logic:

passport.use(new twitchStrategy({
    clientID: config.twitchID,
    clientSecret: config.twitchSecret,
    /*to be updated*/
    callbackURL: config.callbackURL,
    scope: "user_read"
  },
  function(accessToken, refreshToken, profile, done) {
    console.log(profile);
    ***return done();***
  }
));



回答2:


I see a few possible missing pieces glancing at my code. Are you using the passport.session() middleware? Also the serializeUser and deserializeUser functions?

passport.serializeUser(function(user, done) {
  //place user's id in cookie
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  //retrieve user from database by id
  User.findById(id, function(err, user) {
    done(err, user);
  });
});


来源:https://stackoverflow.com/questions/32619736/passport-authentication-callback-hangs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!