简体   繁体   English

Passport身份验证回调挂起

[英]Passport authentication callback hangs

After hours trying to solve this by myself I reach to SO community looking for some light. 经过几个小时试图自己解决这个问题,我到了SO社区寻找一些亮点。

I'm using passport for user authentication. 我正在使用护照进行用户身份验证。 It's already initialized in my main express.js file as per the docs: 它已根据文档在我的主要express.js文件中初始化:

app.use(passport.initialize());

I got a index.js file which handles facebook-passport in this manner: Index.js 我有一个index.js文件以这种方式处理facebook-passport :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: 以这种方式在index.js中导入的passport.js:

passport.js 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 Facebook登录提示
  • After successful authentication in Facebook the callback (/auth/facebook/callback) IS reached with user info and token as expected. 在Facebook成功验证后,使用用户信息和令牌按预期到达回调(/ auth / facebook / callback)。
  • User is saved in DB with expected fields 用户使用预期字段保存在DB中

Where things get weird: 事情变得奇怪:

  • After saving the User, the done(null,user) does nothing. 保存用户后, done(null,user)不执行任何操作。 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. 中间件setTokenCookie永远不会被调用,因此问题肯定在上一步中。

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) 在processes.tick中包装来自passport.js的整个设置功能(发现有些人使用它但没有解决问题)
  • Using Mongoose with promise as in User.findOne({...}).exec().then(user => {...}) User.findOne({...}).exec().then(user => {...})使用带有promise的Mongoose User.findOne({...}).exec().then(user => {...})

If you need additional information please don't hesitate to ask. 如果您需要其他信息,请不要犹豫。 Any help is really appreciated. 任何帮助都非常感谢。

Thanks! 谢谢!

I see a few possible missing pieces glancing at my code. 我看到一些可能丢失的部分看了我的代码。 Are you using the passport.session() middleware? 你使用的是passport.session()中间件吗? Also the serializeUser and deserializeUser functions? serializeUserdeserializeUser函数也是?

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

If you're a noob to passport/express like me, this may help: 如果你是像我这样的护照/快递菜鸟,这可能会有所帮助:

check if you invoke done() in your passport logic: 检查你是否在护照逻辑中调用done():

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM