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

cognito-express-middleware

v1.4.8

Published

Express middleware for AWS Cognito integration.

Downloads

12

Readme

cognito-express-middleware NPM version

The Express middleware to authenticate and authorized users using AWS Cognito user pools. It validates a JWT token (either an id or access token) and populates req.user, or any other property of your choice, with its deciphered content. Simple helpers are provided to make decisions on accessibility of API endpoints for a given user.

This project is based on cognito-toolkit. It is a sister project of koa-cognito-middleware.

Examples

const express = require('express');
const getUser = require('cognito-express-middleware');

const {isAuthenticated, hasScope, hasGroup, isAllowed} = getUser;

const app = express();

// run getUser() on every request
app.use(getUser({
  region: 'us-east-1',
  userPoolId: 'us-east-1_MY_USER_POOL'
}));

// populate router1 with custom authorization rules

const router1 = express.Router();

router1.get('/a',
  (_, res) => res.send('all allowed'));

router1.get('/b', isAuthenticated,
  (_, res) => res.send('all authenticated'));

router1.post('/c', hasGroup('user-type/writers'),
  (_, res) => res.send('only a writers group'));

router1.post('/d', hasScope('writers'),
  (_, res) => res.send('only with a writers scope'));

router1.post('/user',
  (req, res) => res.json(req.user || {}));

app.use('/', router1);

// protect all routes with a single validator

const router2 = new Router();
// populate router2

const readMethods = {GET: 1, HEAD: 1, OPTIONS: 1};

const validator = async (req, groups, scopes) => {
  if (readMethods[req.method.toUpperCase()] === 1) return true;
  // only writers can use other methods (POST, PUT, PATCH, DELETE...)
  if (groups.some(g => g === 'user-type/writers')) return true;
  if (scopes.some(s => s === 'user-type/writers')) return true;
  return false;
};

app
  .use(isAllowed(validator))
  .get('/lift', (req, res) => {
    const user = req.user;
    if (user) {
      user.setAuthCookie(req, res, {domain: 'api.my-domain.com'});
    }
    res.sendStatus(204);
  })
  .use('/', router2);

// now all routes of router2 are protected by our validator

How to install

npm install --save cognito-express-middleware
# yarn add cognito-express-middleware

Documentation

All provided functions are explained below. See the examples above for usage patterns.

getUser(options [, pools])

This is the main function directly returned from the module. It populates req[getUser.stateUserProperty] (see below) with a decoded JWT or assigns it to null (cannot positively authenticate). Other helpers or a user's code uses it to authorize or reject the user for a given route.

Additionally if an authenticated user it adds the following properties:

  • _token — the original JWT.
  • setAuthCookie(req, res, options) — a function, which when called sets a cookie specified by authCookie (see below) to _token. The optional options argument is an object compatible with options for res.cookie(). By default the cookie is set with following options:
    • expires — an expiration time of a JWT.
    • domain — a value of req.host. options will overwrite/augment those values.

getUser(options [, pools]) takes options, which is an object with the following properties:

  • regionrequired string, which specifies an AWS region, such as 'us-east-1'. Default: none.
  • userPoolIdrequired string, which specifies a user pool ID, such as 'us-east-1_MY_USER_POOL'. Default: none.
  • authHeader — optional string. Default: 'Authorization'. It specifies an HTTP request header name. Its value should be a JWT supplied by AWS Cognito (id_token or access_token).
  • authCookie — optional string. Default: 'auth'. It specifies an HTTP request cookie name. Its value should be a JWT supplied by AWS Cognito (id_token or access_token).
  • source — optional function. Default: reads authHeader header and returns it, if it is not falsy, otherwise reads authCookie cookie and returns it, if it is not false, otherwise returns null. If it is a function, it is called with req argument, and can inspect a request to produce a JWT token as a string.
    • Examples:
      const getToken1 = req => req.get('x-auth-header');
      const getToken2 = req => req.cookies['auth-token'];
  • setAuthCookieOptions — optional object compatible with options for res.cookie(). If it is null (the default), a cookie is not set automatically. Otherwise, it is set every time it is not set or has a different value. When a cookie is set, setAuthCookieOptions is used to overwrite/augment the default options described above in setAuthCookie().

Optional pools, if specified, should be an object with the following properties or an array of such objects:

  • regionrequired string, which specifies an AWS region, such as 'us-east-1'. Default: none.
  • userPoolIdrequired string, which specifies a user pool ID, such as 'us-east-1_MY_USER_POOL'. Default: none.

If pools is specified region and userPoolId of options are ignored. Specifying pools is the only way to supply an array of user pools.

This function should be used before any other helpers.

getUser.stateUserProperty

This is a property name to hold a user object. It can be a string or a Symbol. Default: 'user'.

Usually it is assigned right after obtaining getUser():

const getUser = require('cognito-express-middleware');
getUser.stateUserProperty = 'cognitoUser';
const {isAuthenticated, hasScope, hasGroup, isAllowed} = getUser;

All other helper functions will use this value to inspect the state's user property.

getUser.isAuthenticated

This is a helper function, which checks if the state's user property is set. If not it rejects a request with 401 (unauthorized).

getUser.hasGroup(group)

This is a helper function, which checks if the state's user property has 'cognito:groups' array that includes a given group (as a string). If not it rejects a request with 403 (forbidden) for valid users and 401 (unauthorized) for non-authenticated users.

getUser.hasScope(scope)

This is a helper function, which checks if the state's user property has 'scope' string that includes a given scope (as a string). If not it rejects a request with 403 (forbidden) for valid users and 401 (unauthorized) for non-authenticated users.

getUser.isAllowed(validator)

This is a helper function, which checks runs a validator. If not it rejects a request with 403 (forbidden) for valid users and 401 (unauthorized) for non-authenticated users.

validator is an asynchronous function, which is called with three parameters: the original req, groups and scopes. The latter two parameters are arrays of strings listing cognito:groups and scope items respectively. validator should return a truthy value, if a user is allowed to perform an action, and a falsy value otherwise.

Versions

  • 1.4.7 The initial public release.

License

The 3-Clause BSD License