我尝试使用 PassportJS 登录 Google。但是当我使用自定义回调时,Google 策略从未调用回调。我究竟做错了什么?我的代码如下。
端点:
var router = express.Router();
router.get('/',
passport.authenticate('google', { scope: [
'https://www.googleapis.com/auth/plus.login',
'https://www.googleapis.com/auth/plus.profiles.read',
'https://www.googleapis.com/auth/userinfo.email'
] }
));
router.get('/callback', function (req, res) {
console.log("GOOGLE CALLBACK");
passport.authenticate('google', function (err, profile, info) {
console.log("PROFILE: ", profile);
});
});
module.exports = router;
Passport :
passport.use(new GoogleStrategy({
clientID: config.GOOGLE.CLIENT_ID,
clientSecret: config.GOOGLE.CLIENT_SECRET,
callbackURL: config.redirectURL+"/auth/google/callback",
passReqToCallback: true
},
function(request, accessToken, refreshToken, profile, done) {
process.nextTick(function () {
return done(null, profile);
});
}
));
GOOGLE CALLBACK 日志已打印,但 PROFILE 日志从未打印。
提前致谢。
最佳答案
这是一个棘手的情况......
passport.authenticate
方法返回一个函数。
如果你以这种方式使用,你必须自己调用它。
看:
router.get('/callback', function (req, res) {
console.log("GOOGLE CALLBACK");
passport.authenticate('google', function (err, profile, info) {
console.log("PROFILE: ", profile);
})(req, res); // you to call the function retuned by passport.authenticate, with is a midleware.
});
或者,你可以这样做:
router.get('/callback', passport.authenticate('google', function (err, profile, info) {
console.log("PROFILE: ", profile);
}));
passport.authenticate
是一个中间件。
希望是有帮助的。
关于node.js - 当 Passportjs 上使用 Google Auth 时,自定义回调从未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44366909/