Express JWT Permissions
Middleware that checks JWT tokens for permissions, recommended to be used in conjunction with express-jwt.
npm install express-jwt-permissions --save
This middleware assumes you already have a JWT authentication middleware such as express-jwt.
The middleware will check a decoded JWT token to see if a token has permissions to make a certain request.
Permissions should be described as an array of strings inside the JWT token, or as a space-delimited OAuth 2.0 Access Token Scope string.
"scope": "status user:read user:write"
If your JWT structure looks different you should map or reduce the results to produce a simple Array or String of permissions.
Using permission Array
To verify a permission for all routes using an array:
var guard =app
If you require different permissions per route, you can set the middleware per route.
var guard =appapp
Logical combinations of required permissions can be made using nested arrays.
// Required: "admin"app
Array of strings
// Required: "read" AND "write"app
Array of arrays of strings
// Required: "read" OR "write"app// Required: "admin" OR ("read" AND "write")app
To set where the module can find the user property (default
req.user) you can set the
To set where the module can find the permissions property inside the
requestProperty object (default
permissions), set the
Consider you've set your permissions as
req.identity, your JWT structure looks like:
"scope": "user:read user:write"
You can pass the configuration into the module:
var guard =requestProperty: 'identity'permissionsProperty: 'scope'app
The default behavior is to throw an error when the token is invalid, so you can add your custom logic to manage unauthorized access as follows:
Note that your error handling middleware should be defined after the jwt-permissions middleware.
const checkForPermissions = guardapp
$ npm install $ npm test
This project is licensed under the MIT license. See the LICENSE file for more info.