2015-07-06 42 views
0

我在Node上使用PassportJS来授权我的应用程序通过Gmail发送/接收电子邮件。使用PassportJS的oAuth2访问Gmail的API,不返回accesstoken,refreshtoken或个人档案

我使用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文档非常缺乏这方面...

+0

在Google Developers Console中为您的项目启用Google+ API吗? –

+0

是的。我最终通过使用Passport的“Google-oAuth2”策略来实现这一目标。我假设Gmail的oAuth系统与Google +的系统不同,但如果您只是添加了正确的范围和权限(至少现在我认为它可以达到那一点),它们可以一起工作! – Jascination

回答

0

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

/** 
* 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, {}); 
}; 

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

相关问题