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-scope

v1.0.0

Published

Middleware that checks validated JsonWebTokens (JWT) for scopes

Downloads

120

Readme

express-jwt-scope

NPM version

Middleware that checks validated JsonWebTokens (JWT) for scopes

Install

$ npm install express-jwt-scope

Peer dependency: express@^4.0.0

Usage

Requires : express-jwt

Use together with express-jwt to validate JWT(JsonWebTokens) and set req.auth

Example 1

const jwt = require('express-jwt');
const jwtScope = require('express-jwt-scope');

let options = {};
app.get('/users',
  jwt({ secret: 'shared_secret' }), //  Validates JWT and sets req.auth
  jwtScope('read:users', options),
  (req, res)=> res.json({message: 'Hello from /users'}));

// This user will have access
let user = { scope: 'read:users' };

Example 2

Allow if any of scope, looks like this:

const jwt = require('express-jwt');
const jwtScope = require('express-jwt-scope');
//  Validates JWT and sets req.auth
app.use(jwt({ secret: 'shared_secret'}));

app.get('/users', jwtScope('read:users write:users'), (req, res)=> {
  res.json({message: 'Hello from /users'})
});

// This user will have access
let user = { scope: 'read:users' };

To require that all scopes are provided, use the requireAll: true option:

let options = { requireAll: true };
app.post('/users', jwtScope('read:users write:users', options), (req, res)=> {
  //  Do stuff...
});

// This user will have access
const authorizedUser = { scope: 'read:users write:users' };

// This user will NOT have access
const unauthorizedUser = { scope: 'read:users' };

Custom usage

const jwt = require('express-jwt');
const jwtScope = require('express-jwt-scope');

app.use(jwt({ secret: 'shared_secret'}));

//  Checks req.auth['permission']
const checkPermissions = (permissions)=> jwtScope(permissions, { scopeKey : 'permissions', requireAll: true });
//  Checks req.auth['yourScope']
const checkYourScope = (yourScope)=> jwtScope(yourScope, { scopeKey : 'yourScope' });

app.post('/users', checkPermissions('write:users read:users'), (req, res)=> {
  //  Do stuff...
});

app.get('/yourPath', checkYourScope('your:scope'), (req, res)=> {
  res.json({message: 'Hello from /yourPath!'});
});

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.auth['scope'].
    • Ex: 'permission' => req.auth['permission']
  • requireAll: true => Requires all scopes to be provided.
    • Default value: false
  • errorToNext: true => Forward errors to express next(), instead of ending the response directly.
    • Default value: false

Examples

Full Auth0

const express = require('express');
const app = express();
const jwt = require('express-jwt');
const jwksRsa = require('jwks-rsa');
const jwtScope = require('express-jwt-scope');

// Authentication middleware. When used, the
// Access Token must exist and be verified against
// the Auth0 JSON Web Key Set
const checkJwt = jwt({
  // Dynamically provide a signing key based on the kid in the header and 
  // the signing keys provided by the JWKS endpoint.
  secret: jwksRsa.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: `https://YOUR_DOMAIN/.well-known/jwks.json`
  }),

  //  Validate the audience and the issuer.
  audience: 'YOUR_API_IDENTIFIER',
  issuer: `https://YOUR_DOMAIN/`,
  algorithms: ['RS256']
});

/**  Public routes goes here  */
// This route doesn't need authentication
app.get('/api/public', (req, res)=> {
  res.json({message: 'Hello from a public endpoint! You don\'t need to be authenticated to see this.'});
});

// This route need authentication
app.get('/api/private', checkJwt, (req, res)=> {
  res.json({message: 'Hello from a private endpoint! You need to be authenticated to see this.'});
});

// This route need authentication and scope
app.get('/api/private-scoped', checkJwt, jwtScope('read:messages'), (req, res)=> {
  res.json({message: 'Hello from a private endpoint! You need to be authenticated and have a req.auth.scope of read:messages to see this.'});
});

/** Private routes goes here  */
app.use(checkJwt);
app.get('/api/another-private-scoped', jwtScope('read:info'), (req, res)=> {
  res.json({message: 'Hello from a private endpoint! You need to be authenticated and have `read:info` included in req.auth.scope to see this.'});
});

//  Enable Role-Based Access Control for APIs, to add Auth0 permissions in the access token.
//  See https://auth0.com/docs/dashboard/guides/apis/enable-rbac
let options = {
  scopeKey: 'permissions'
};
app.get('/api/another-private-scoped', jwtScope('read:user', options), (req, res)=> {
  res.json({message: 'Hello from a private endpoint! You need to be authenticated and have `read:user` included in req.auth["permission"] to see this.'});
});

License

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