jwt-scope
Checks if JWT contains required scope(s)
to access to an endpoint
Install
$ npm install jwt-scope
Peer dependency:
express@^4.0.0
Usage
Use together with express-jwt to validate JWT(JsonWebTokens) and sets req.user
const jwt = ;const jwtScope = ; let options = {};app;
Allow if any of scope
, looks like this:
app; // This user will have accesslet user = scope: 'read:users';
To require that all scopes are provided, use the requireAll: true
option:
app; // This user will have accessconst authorizedUser = scope: 'read:users write:users'; // This user will NOT have accessconst unauthorizedUser = scope: 'read:users';
Input types
String (space separated)
"write:users read:users"
jwtScope("write:users read:users")
Array
["write:users", "read:users"]
jwtScope(["write:users", "read:users"])
Options
scopeKey
: The user property name to check for the scope(s).- Default value:
'scope'
=> req.user['scope']. - Ex:
'permission'
=> req.user['permission']
- Default value:
requireAll
:true
=> Requires all scopes to be provided.- Default value:
false
- Default value:
errorToNext
:true
=> Forward errors to expressnext()
, instead of ending the response directly.- Default value:
false
- Default value:
Examples
Auth0
const express = ;const app = ;const jwt = ;const jwksRsa = ;const jwtScope = ; // Authentication middleware. When used, the// Access Token must exist and be verified against// the Auth0 JSON Web Key Setconst checkJwt = ; /** Public routes goes here */// This route doesn't need authenticationapp; // This route need authenticationapp; // This route need authentication and scopeapp; /** Private routes goes here */app;app; // Enable Role-Based Access Control for APIs, to add Auth0 permissions in the access token.// See https://auth0.com/docs/dashboard/guides/apis/enable-rbaclet options = scopeKey: 'permissions';app;
License
This project is licensed under the MIT license. See the LICENSE file for more info.