需要帮助如何在Express中实际使用Passport身份validation策略

假设我有一个像这样的脚本,它使用Express后端的Passport身份validation策略。 我将如何使用此脚本实际上进行API函数调用? 在链接的项目文档中我没有看到任何明确的示例,也不能在Passport.js的文档中find任何内容 。 谢谢。

我假设你知道如何使用护照,你会知道什么是正确的Fitbit API端点(说实话,我不知道)。 说,让我给一个想法,可能会帮助你解决你的问题:

 // An awesome npm module (https://github.com/mikeal/request) var request = require('request'); // // // // An express route. app.get('/activities', function (req, res) { if (req.user !== null) { // User is authenticated. getUserActivities(req.user.id, res); } else { // Redirect to login the user isn't authenticated. res.redirect('/login'); } }); // This function will make API calls to Fitbit // using the User ID we got from the PassportJS // authentication process. function getUserActivities(id, res) { // It will request from Fitbit User activities. request('https://api.fitbit.com/1/user/'+ id +'/activities/', function (error, response, body) { if (!error && response.statusCode == 200) { // If everything goes well. return res.send(body); } else { // If something wrong happens. return res.send(error); } ); } 

这个例子的目的是告诉你,你需要使用PassportJS来获取fitbit用户ID, 然后使用该ID来调用fitbit API调用。

在护照用户序列化完成后,每个请求都有user字段,其中包含传递给passport.serializeUser方法的donecallback的信息。

 app.get('/userID', function (req, res) { if (req.isAuthenticated()) { res.json(req.user.id); } res.redirect('/login'); } 

另外,您可以访问session

 app.get('/auth/fitbit/callback', passport.authenticate('fitbit', { failureRedirect: '/login' }), function(req, res) { req.session.loggedInAt = Date.now(); res.redirect('/'); }); 

存储在session信息可在所有请求中使用,而用户通过身份validation

 app.get('/someroute', function (req, res) { // call to another service var url = 'http://superservice.com/' + req.user.id + '/' + req.session.loggedInAt http.get(url, function (_res) { res.send(_res.data) }); });