Need help on how to actually use Passport authentication strategy in Express

别等时光非礼了梦想. 提交于 2020-01-05 15:17:15

问题


Suppose I have a script like this, which uses a Passport authentication strategy with an Express backend. How would I use this script to actually make API function calls? I don't see any explicit examples in the linked project's documentation nor can I find anything in Passport.js's documentation. Thanks.


回答1:


I'm supposing that you know how to use passport, and you will figure it out what's the right Fitbit API endpoint (honestly, I'm don't know it). Said that, let me give an idea that might help you solve your problem:

// 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);
        }
);

}

The goal of this example is to show you that you need to use PassportJS to get fitbit users ID, then use that id to make API calls to fitbit.




回答2:


After passport user serialization done, every request has user field, which contains information passed to done callback of passport.serializeUser method.

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

Also, you have access to session

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

Information stored in session available in all requests, while user is authenticated

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)
    });
});


来源:https://stackoverflow.com/questions/26243219/need-help-on-how-to-actually-use-passport-authentication-strategy-in-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!