Giter Site home page Giter Site logo

express-jwt-authorization's Introduction

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.