passport-google-oauth2获取节点js中的gmail.users.messages.list

首先,我对护照节点js + oauth2比较陌生,所以如果您有任何困惑,请发表评论。

我已经尝试下面的身份validation谷歌从oauth2与node.js,这里是代码

var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; var google = require('googleapis'); var GOOGLE_CLIENT_ID = "---MY-CLIENT-ID"; var GOOGLE_CLIENT_SECRET = "---MY-CLIENT-SECRET"; var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.get('/', function(req, res){ res.render('index', { user: req.user }); }); app.get('/account', ensureAuthenticated, function(req, res){ res.render('account', { user: req.user }); }); app.get('/login', function(req, res){ res.render('login', { user: req.user }); }); // user back to this application at /auth/google/return app.get('/auth/google', passport.authenticate('google', { failureRedirect: '/login' }), function(req, res) { res.redirect('/'); }); // GET /auth/google/return // Use passport.authenticate() as route middleware to authenticate the // request. If authentication fails, the user will be redirected back to the // login page. Otherwise, the primary route function function will be called, // which, in this example, will redirect the user to the home page. app.get('/auth/google/return', passport.authenticate('google', { failureRedirect: '/login' }), function(req, res) { res.redirect('/'); }); app.get('/logout', function(req, res){ req.logout(); res.redirect('/'); }); app.listen(3000); // Simple route middleware to ensure user is authenticated. // Use this route middleware on any resource that needs to be protected. If // the request is authenticated (typically via a persistent login session), // the request will proceed. Otherwise, the user will be redirected to the // login page. function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next(); } res.redirect('/login') } 

最重要的是工作正常,但现在我想用这个在护照的帮助下获取gmail的邮件列表。

  var gmail = google.gmail('v1'); var profileData = gmail.users.messages.list({ userId: 'me', auth: "**AUTHORISATION OBJECT WITH ACCESSTOKEN**" }, function(err, response) { //console.log(response.messages); }); 

我如何在护照生成的访问令牌中使用它?

您需要一个OAuth2客户端:

 var gmail = google.gmail('v1'); var OAuth2 = google.auth.OAuth2; var oauth2Client = new OAuth2('<CLIENT_ID>', '<CLIENT_SECRET>', '<REDIRECT_URL>'); oauth2Client.setCredentials({ access_token: '<ACCESS_TOKEN_HERE>' }); app.get('/', function(req, res, next) { gmail.users.messages.list({ userId: 'me', auth: oauth2Client }, function(err, response) { res.send(response); }); } 

这对使用自己的凭证进行testing可以很好地工作,但是对于更多的用户,您必须将访问令牌更改为当前用户的令牌。