passport-google-oauth2用于在节点js中获取gmail.users.messages.list

时间:2015-03-11 10:45:04

标签: node.js google-oauth passport.js gmail-api

首先,我对使用护照的节点js + oauth2有点新意,所以如果您有任何疑惑,请发表评论。

我在下面尝试使用google从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);
  });

如何在护照生成的访问令牌中使用此功能。

1 个答案:

答案 0 :(得分:1)

您需要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);
    });
}

这适用于使用您自己的凭据进行测试,但是对于更多用户,您必须将访问令牌更改为当前用户的令牌。

相关问题