npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

express-jwt-authorization

v1.3.0

Published

Express middleware for handling JWT permissions

Downloads

14

Readme

Express JWT Authorization

Build Status Code Style

Simple middleware that allows protecting routes for a specific role or permission based on express-jwt-permissions approach.

With this module, there is no need of saving the scopes directly in the JWT. Simply set a role for a user and control all its permissions of that role in the backend.

Install

npm install express-jwt-authorization --save

Usage

This middleware has to be used in conjunction with another JWT authentication middleware that verifies and decodes the token. We reccommend express-jwt or building your own.

Configuration

Set a custom JSON with all the permissions and their roles. For example:

{
  "admin": [
    "recoverPassword",
    "generateToken",
    "changePassword",
    "changeEmail",
    "deleteUser",
    "getUserData"
  ],
  "user": ["recoverPassword", "changePassword", "changeEmail"]
}

Then, call the constructor in the following way:

var jwtAuth = require('express-jwt-authorization');
jwtAuth = new jwtAuth({
  admin: [
    'recoverPassword',
    'generateToken',
    'changePassword',
    'changeEmail',
    'deleteUser',
    'getUserData',
  ],
  user: ['recoverPassword', 'changePassword', 'changeEmail'],
});

If you have stored the information of the token in a different property you can set the userParameter option.

If the role field is different from the default, just set the roleParameter option.

As an example, if the user data can be accessed within req.custom_user and the role property is called custom_role, you need to pass the following configuration as the second argument:

new jwtAuth(
  {
    admin: ['recoverPassword', 'generateToken'],
    user: ['recoverPassword', 'changePassword'],
  },
  { userParameter: 'custom_user', roleParameter: 'custom_role' },
);

In case you've built your own JWT verificator, pass the function using getDecodedPayload parameter.

new jwtAuth(
  {
    admin: ['recoverPassword', 'generateToken'],
    user: ['recoverPassword', 'changePassword'],
  },
  {
    getDecodedPayload: function(req) {
      const token = req.headers.authorization.split(' ')[1];
      return decodeJWT(token);
    },
  },
);

getDecodedPayload should return the payload. The library will automatically add it in the request object. If the token is not specified or is incorrect, the function should return null.

All the errors that can occur will be passed to Express default error handler.

Main usage

Check if a role is allowed to access a particular resource

// Only users with the role admin are allowed
app.use(jwtAuth.checkRole('admin'));

Check if a user has particular permissions based on role

Of course, a permission can be set for different roles. If you need to distinguish between roles for a particular use, just check the req.user.role variable.

Allow guest

If you have a route that allows both non authenticated and authenticated users, use the decode function and check if it's logged using isAuth.

router.get('/', jwtAuth.decode(), (req, res) => {
  if (jwtAuth.isAuth(req, 'user'))
    return res.status(200).send('You are a logged user!');
  else
    return res.status(200).send('You are a guest!');
});
  • Simple string
// Only roles with the permission 'generateToken' are allowed
app.use(jwtAuth.checkPermission('generateToken'));

This library allows to do logical combination of permissions using nested arrays.

  • Array of strings
// 'modify' AND 'delete' permissions are needed
router.get(
  '/resource',
  jwtAuth.checkPermission(['modify', 'delete']),
  (req, res) => {
    return res.status(200).json({ status: 'OK' });
  },
);
  • Array of arrays of strings
// 'modify' OR 'delete' permissions are needed
app.use(jwtAuth.checkPermission([['modify'], ['delete']]));

// 'delete' OR ('modify' AND 'read') permissions are needed
app.use(jwtAuth.checkPermission([['delete'], ['modify', 'read']]));

Error handling

When the error is due to a bad configuration of the module, a standard Error object is thrown. In the other cases, an 'UnauthorizedError' object is thrown.

You can add your custom logic in a middleware with four arguments as Express recommends in the following way:

app.use(function(err, req, res, next) {
  if (err.name === 'UnauthorizedError') {
    if (err.code === 'permission_not_allowed') {
      return res.status(403).send('not allowed');
    }
  }
});

Check err.code for additional information of the error.

Related Modules

Tests

$ npm install
$ npm test

License

This project is licensed under the MIT license. See the LICENSE file for more info.