2015-07-06 41 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

相關問題