【发布时间】:2015-05-13 02:46:35
【问题描述】:
首先,我对带护照的 node js + oauth2 有点陌生,所以如果您有任何困惑,请发表评论。
我已经在下面尝试使用 node.js 从 oauth2 向 google 进行身份验证,这是代码
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);
});
如何在护照生成的访问令牌中使用它。
【问题讨论】:
标签: node.js google-oauth passport.js gmail-api