Verifying roles & authentication with Passport.js

前端 未结 3 1049
慢半拍i
慢半拍i 2021-02-01 22:58

So I\'d like to make some routes in an API that will show different data based on the user role, defined in MongoDB. Here\'s a sampling of what I have right now, it works...

相关标签:
3条回答
  • 2021-02-01 23:29

    I would suggest that you use HTTP status codes and an error object, this is a common API convention and it allows your API users to know what's happening and why:

    app.get('/premium-resource', function(req, res, next) {
      passport.authenticate('bearer', function(err, user) {
        if (user){
          if (user.role === 'premium'){
            return res.send(200,{userContent:'you are a premium user'});
          }else{
            return res.send(403,{
              'status': 403,
              'code': 1, // custom code that makes sense for your application
              'message': 'You are not a premium user',
              'moreInfo': 'https://myawesomeapi.io/upgrade'
            });
          }
        }else{
          return res.send(401,{
            'status': 401,
            'code': 2, // custom code that makes sense for your application
            'message': 'You are not authenticated.',
            'moreInfo': 'https://myawesomeapi.io/docs'
          });
        }
      })(req, res, next);
    });
    

    Disclaimer: I work at Stormpath and we put a lot of thought into API authentication and design, we have a really presentation on the topic:

    https://stormpath.com/blog/designing-rest-json-apis/

    0 讨论(0)
  • 2021-02-01 23:38

    The solution I've found to my answer is to use an adaptation of the Passportjs.org documentation.

    In the routes I need to return data, whether a user is logged in or not I can use something like:

    // Test to check for authentication
    app.get('/login', function(req, res, next) {
      passport.authenticate('bearer', function(err, user, info) {
        if (user)
            // check user's role for premium or not
            if (user.role == "premium")
                return res.send('user is premium')
            else
                return res.send('user is not premium');
        else
            // return items even if no authentication is present, instead of 401 response
                return res.send('not logged in');
      })(req, res, next);
    });
    
    0 讨论(0)
  • 2021-02-01 23:45

    The solution is to limit the content in the view rather than the route.

    router.get('/test', authenticationMiddleware, function(req, res){
        var premiumFlag = req.user.role;
        res.send('premiumontent', {role: premiumFlag});
    });
    

    premiumContent.jade

    p This content is visible to all users
    
    - if role === "premium"
        p this content is only visible to premium users
    
    0 讨论(0)
提交回复
热议问题