使用PassportJS的oAuth2访问Gmail的API,而不是返回accessstoken,refreshtoken或profile

时间:2015-07-06 02:04:09

标签: javascript oauth oauth-2.0 google-oauth passport.js

我在Node上使用PassportJS来授权我的应用通过Gmail发送/接收电子邮件。

我正在使用Passport's oAuth2 strategy, docs are here

我对成功回调函数如何与Passport一起工作感到很困惑,而且我目前没有得到我需要的数据(用户配置文件,访问令牌和刷新令牌)。

我的代码:

 app.get('/auth/gmail',
      passport.authenticate('oauth2',{ scope : ['https://www.googleapis.com/auth/gmail.modify','https://www.googleapis.com/auth/plus.me'],
                                  accessType: 'offline', approvalPrompt: 'force' }));

 passport.use(new OAuth2Strategy({
    authorizationURL: 'https://accounts.google.com/o/oauth2/auth',
    tokenURL: 'https://accounts.google.com/o/oauth2/token',
    clientID: configAuth.googleAuth.clientID,
    clientSecret: configAuth.googleAuth.clientSecret,
    callbackURL: configAuth.googleAuth.callback2
  },
  function(accessToken, refreshToken, profile, done) {
    process.nextTick(function() {

        console.log("Token is ");
        console.log(util.inspect(accessToken, false, null));

        console.log("Refresh is ");
        console.log(util.inspect(refreshToken, false, null));

        console.log("Profile is ");
        console.log(util.inspect(profile, false, null));

这给了我一个回复:

Token is 
'{access token}'
Refresh is 
undefined
Profile is
{}

也许我不能正确理解回调函数,但是当我的函数是:

 function(req, token, refreshToken, profile, done) {}

我的回答是:

Token is 
undefined
Refresh is 
{ access_token: '{an access token}',
  token_type: 'Bearer',
  expires_in: 3599,
  id_token:'{a really long string}' }
Profile is
{}

关于这里发生了什么的任何想法? Passport-oAuth2文档在这方面确实缺乏......

1 个答案:

答案 0 :(得分:0)

根据文档和代码(结果为空),您需要自己实现此方法,或使用特定于Google的现有策略:

/**
 * Retrieve user profile from service provider.
 *
 * OAuth 2.0-based authentication strategies can overrride this function in
 * order to load the user's profile from the service provider.  This assists
 * applications (and users of those applications) in the initial registration
 * process by automatically submitting required information.
 *
 * @param {String} accessToken
 * @param {Function} done
 * @api protected
 */
OAuth2Strategy.prototype.userProfile = function(accessToken, done) {
  return done(null, {});
};

更新:您可以使用此OAuth2策略:https://github.com/jaredhanson/passport-google-oauth