Access authorization/role with passport

If you are trying to prevent certain users from accessing parts of a service API and need to somehow manage the roles of what a user may use or access, then you can use passport with a role twist.

The core of the logic resides on the express server, we will setup a function in the app.js file called checkRole(), whenever an authentication happens through passport we just check the role of the user as well, and decide to reject or allow them.

function checkRole(roles, passport, config) {
      return function (req, res, next) {
            passport.authenticate('jwt', config.session, function (err, user, info) {
                  if (err) {
                  } else if (!user) {
                  } else {
                        if (roles.includes(user.role)) {
                        } else
            })(req, res, next)
app.set('acl', checkRole);

We also need to modify our routes, so for example, a route that only allows admin access to GET /api/v1/users list. As you can see the declare the admin role to only access that API end point.

//Only allow the admin role to list users.
    .get(app.get('acl')(['admin'], passport, config), api.users(models.User, app.get('key')))

That is pretty much all there is too it, if you want to see the full source code, feel free to grab it from here
The example will have a vue.js application to allow you to communicate with the express service, let me know if there are any questions.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.