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-oauth-jwt

v2.0.2

Published

Middleware for Express to secure endpoints with OAuth JWT Bearer tokens

Downloads

1,629

Readme

Securing endpoints in Express with OAuth JWT tokens

Quality Availability

This library allows you to secure your Express endpoints with JWTs. The implementation uses a JWKS endpoint of an Authorization Server to get keys required for the verification of the token signature.

Running the example

  1. Download the code and install dependencies running npm i.
  2. In settings.js in the example directory set the URI of the JWKS endpoint exposed by the Authorization Server.
  3. Start the demo server with npm run example.
  4. The server exposes endpoints /secured/token, /secured/scope and /secured/claim which present different options of securing the endpoints.

Installing the dependency

Use npm to install the library in your project:

npm install express-oauth-jwt

Usage

Preparing the Middleware

The secure middleware needs a method to obtain keys. You can use the jose-provided method, or create your own instance. The method is responsible for obtaining signature verification keys for a concrete token, and has the signature:

function(headerParameters: JWSHeaderParameters, input: FlattenedJWSInput): Promise<KeyLike | Uint8Array> | KeyLike | Uint8Array

The easiest way is to use the method provided by the jose library. The method caches the result of the JWKS endpoint request in memory to limit sending requests to the server.

const jwksService = createRemoteJWKSet(new URL(settings.jwks_uri))
const midleware = secure(jwksService)

Securing an endpoint

To secure an endpoint apply the secure middleware to it. Any endpoint with this middleware applied will require a valid JWT token sent in the Authorization header in the form Bearer <token_value>. The token, if valid, will be decoded and all its claims will be set in the request in a claims field.

If the token does not pass validation, a 403 response will be returned. If no JWT token is found in the request, a 401 response will be returned. The response will have the WWW-Authenticate header set with detailed information on the error (as specified in the RFC 6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage).

If you want the WWW-Authenticate to return a realm value, pass the middleware an options object with the realm option set.

const { secure } = require('express-oauth-jwt');
router.use(secure(jwksService, { realm: 'my-realm' }));

The WWW-Authenticate header in the error response will then might look like this:

WWW-Authenticate: Bearer realm="my-realm", error="invalid_token", error_description="..."

Authorizing the request based on scopes

In order to limit the request to given scope values pass the middleware an options object with a list of strings in the scope field:

const secure = require('express-oauth-jwt');
router.use(secure(jwksService, { scope: ["scope1", "scope2"] }));

Authorizing the request based on claims

In order to limit the request based on the presence or value of concrete claims, pass the middleware an options object with a list of claims in the claims field. Each claim should be an object with at least the name field. Optionally you can set the value field. If only the name field is set then the validator checks whether the claim exists in the token. If value is set as well, then the value of the claim in the token must also match.

const secure = require('express-oauth-jwt');
router.use(secure(jwksService, { claims: [ { name: "someClaim", value: "withValue" } ] }));

Using Opaque tokens

This middleware uses JSON Web Tokens, which can be easily decoded offline into a JSON object containing claims about the user or client sending the request. But this is not always the case that JWT tokens are used for authorization. Sometimes the Authorization Server will issue an opaque token, which is just an identifier of the user's data, and the data itself is kept safely with the Authorization Server.

If you use opaque tokens for authorization then the token needs to be exchanged for data associated with it. It cannot be decoded, as the value of the token does not contain any data. In such situation, the best approach is to use the Phantom token approach - let your API gateway exchange the opaque token for a JWT. This way your service will always receive a JWT which can be decoded with the approach shown here.

You can find out more on the Phantom token approach in the Phantom Token Pattern article.

If you're using Curity Identity Server you can learn how to enable Phantom tokens with the help of this tutorial.

Access token claims in Request object

The secure middleware adds claims obtained from the access token into the Express request object, in the claims field. You can access these claims in any other middleware which is next in chain and in the controllers.

function getLibraryData(req, res) {
    if (req.claims.myClaim == 'someValue') {
        ...
    }
    ...
}

Questions and Support

For questions and support, contact Curity AB:

Curity AB

[email protected] https://curity.io

Copyright (C) 2020 Curity AB.