Search code examples
node.jsexpressauthorizationcasl

How to perform role based authorisations on nodejs express server with a good npm module?


I am working on a solution for authorization on a nodejs express server. I am fetching the role information of the logged in user by checking if the user has access to a specific access group by checking the ID Token value and see if that group name is present. I have to perform authorisations based on the role of the user by allowing certain user role to hit a specific endpoint.

What are the best authorization npm modules or techniques by which this can be achieved?

I have searched for a lot of them like casl, etc. but there seem to be a lot of way and this is just shooting up the confusion bar. Any help would be greatly appreciated!


Solution

  • Any kind of permission management is about what user can do with data stored in db.

    That’s why, I would recommend define permissions on resources/models/tables. You can group multiple permissions under one role. This is how you will get RBAC.

    To get more details check this examples:

    If this is too confusing, just use http keywords (get/post/etc) as actions and req.url as subject. So, eventually you will have something like:

    app.use((req, res, next) => {
      const ability = defineUserAbility(req.user);
      
      if (ability.can(req.method, req.url)) {
        next()
      } else {
        res.status(403).end()
      }
    })