我在 Facebook 和 Google 身份验证中都使用了 passport.js。Facebook auth 策略运行良好,回调中的 res.redirect 仅被调用一次。但是对于谷歌身份验证我很茫然,因为它被调用了两次。我花了几个小时试图调试它并查看护照源代码,但找不到错误。
我的 Google 身份验证只是从 Gmail 中获取一些联系人。
app.get('/contacts/google',
passport.authenticate('google', { session: false, scope: ['profile', 'email', 'https://www.googleapis.com/auth/contacts.readonly'] })
);
app.get('/login/google/callback',
passport.authenticate('google', { session: false, failureRedirect: '/' }),
function(req, res, next) {
process.nextTick(function() {
console.log("Right before the googletoken call", req.user);
res.redirect("/users/" + '?googletoken=' + req.user.access_token );
});
}
);
谷歌战略
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var googleConfig = require('./googlekeys.js');
module.exports = function(passport) {
passport.use('google', new GoogleStrategy({
clientID : googleConfig.appID,
clientSecret : googleConfig.appSecret,
callbackURL : googleConfig.callbackUrl,
profileFields: ['email','profile']
},
// google will send back the tokens and profile
function(access_token, refresh_token, profile, done) {
process.nextTick(function() {
//we send the token we receive back so we can use it to get the contacts
console.log("Before calling the token callback");
var user = {};
user.access_token = access_token;
return done(null, user);
});
}
));
};
从控制台这里 - 问题是 /users/?googletoken 调用被调用了两次,即使之前的 console.log 只调用了一次。
GET /contacts/google 302 2.739 ms - 0
At the beginning
Before calling the token callback
Right before the googletoken call { access_token: '[GOOGLE TOKEN]' }
GET /login/google/callback?code=[CODE] 302 485.728 ms - 348
GET /users/?googletoken=[GOOGLE TOKEN THAT WAS RECEIVED BACK] 200 2.812 ms - 7791
GET /users/?googletoken=[GOOGLE TOKEN THAT WAS RECEIVED BACK] 304 1.575 ms - -