Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

middy-middleware-jwt-auth

dbartholomae3.4kMIT6.1.0TypeScript support: included

A middy JSON web token authorization middleware inspired by express-jwt.

middy, middleware, jwt, json web token

readme

middy-middleware-jwt-auth

npm version downloads open issues FOSSA Status npm bundle size debug build status codecov Libraries.io dependency status for latest release semantic release CLA Assistant

A middy JSON web token authorization middleware inspired by express-jwt.

Installation

Download node at nodejs.org and install it, if you haven't already.

npm install middy-middleware-jwt-auth --save

Documentation

There is additional documentation.

Usage

import createHttpError from "http-errors";
import middy from "@middy/core";
import httpErrorHandler from "@middy/http-error-handler";
import httpHeaderNormalizer from "@middy/http-header-normalizer";
import JWTAuthMiddleware, {
  EncryptionAlgorithms,
  IAuthorizedEvent,
} from "middy-middleware-jwt-auth";

// Optionally define the token payload you expect to receive
interface ITokenPayload {
  permissions: string[];
}

// Optionally define a type guard for the token payload
function isTokenPayload(token: any): token is ITokenPayload {
  return (
    token != null &&
    Array.isArray(token.permissions) &&
    token.permissions.every((permission: any) => typeof permission === "string")
  );
}

// This is your AWS handler
const helloWorld = async (event: IAuthorizedEvent<ITokenPayload>) => {
  // The middleware adds auth information if a valid token was added
  // If no auth was found and credentialsRequired is set to true, a 401 will be thrown. If auth exists you
  // have to check that it has the expected form.
  if (event.auth!.payload.permissions.indexOf("helloWorld") === -1) {
    throw createHttpError(
      403,
      `User not authorized for helloWorld, only found permissions [${event.auth!.permissions.join(", ")}]`,
      {
        type: "NotAuthorized",
      },
    );
  }

  return {
    body: JSON.stringify({
      data: `Hello world! Here's your token: ${event.auth!.token}`,
    }),
    statusCode: 200,
  };
};

// Let's "middyfy" our handler, then we will be able to attach middlewares to it
export const handler = middy(helloWorld)
  .use(httpHeaderNormalizer()) // Make sure authorization header is saved in lower case
  .use(httpErrorHandler()) // This middleware is needed do handle the errors thrown by the JWTAuthMiddleware
  .use(
    JWTAuthMiddleware({
      /** Algorithm to verify JSON web token signature */
      algorithm: EncryptionAlgorithms.HS256,
      /** An optional boolean that enables making authorization mandatory */
      credentialsRequired: true,
      /** An optional function that checks whether the token payload is formatted correctly */
      isPayload: isTokenPayload,
      /** A string or buffer containing either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA */
      secretOrPublicKey: "secret",
      /**
       * An optional function used to search for a token e. g. in a query string. By default, and as a fall back,
       * event.headers.authorization and event.headers.Authorization are used.
       */
      tokenSource: (event: any) => event.queryStringParameters.token,
    }),
  );

changelog

6.1.0 (2024-01-27)

Features

6.0.0 (2023-03-03)

Bug Fixes

  • release dependency update of jsonwebtoken to version 9 (eede274)

BREAKING CHANGES

5.1.1 (2022-11-27)

Bug Fixes

  • allow middy 3 as peer dependency (958486a)
  • allow middy 4 as peer dependency (9633c77)

5.1.0 (2022-04-05)

Features

  • support Websocket API requests (225a676)

5.0.0 (2021-10-10)

  • feat!: update for middy 2.x (72cbfaa)

BREAKING CHANGES

  • uses middy 2.x. This only updates the types and dependencies, so you likely don't need to do anything beyond updating your middy version. Follow middy's upgrade guide to do this.

4.1.0 (2021-10-04)

Bug Fixes

Features

  • support API Gateway HTTP APIs (72fad79)

4.0.6 (2020-08-30)

Bug Fixes

  • add tslib dependency (22c6bd5)
  • depend on stable middy packages for dev (6233456)
  • update all dependencies and remove snyk (bb6dbe5)

4.0.5 (2020-08-17)

Bug Fixes

  • package.json to reduce vulnerabilities (9541b6c)

4.0.4 (2020-08-09)

Bug Fixes

  • package.json to reduce vulnerabilities (1c94bb5)

4.0.3 (2020-06-20)

Bug Fixes

  • package.json & .snyk to reduce vulnerabilities (7fde50e)

4.0.2 (2020-06-20)

Bug Fixes

  • package.json & .snyk to reduce vulnerabilities (8aeded9)
  • package.json & .snyk to reduce vulnerabilities (677802b)
  • package.json to reduce vulnerabilities (a384060)

4.0.1 (2020-06-20)

Bug Fixes

  • package.json to reduce vulnerabilities (414d9ee)

4.0.0 (2020-04-30)

Bug Fixes

BREAKING CHANGES

3.0.4 (2020-04-18)

Bug Fixes

  • upgrade middy from 0.34.0 to 0.36.0 (6e1ff2f)

3.0.3 (2020-04-16)

Bug Fixes

  • make snyk a dev dependency (53d72e7)

3.0.2 (2020-04-10)

Bug Fixes

  • package.json & .snyk to reduce vulnerabilities (7e56ba0)
  • package.json & .snyk to reduce vulnerabilities (7598fbc)

3.0.1 (2020-03-27)

Bug Fixes

  • package.json to reduce vulnerabilities (e6269bc)

3.0.0 (2019-11-19)

Code Refactoring

  • move payload to event.auth.payload (c48a741)

Features

  • give access to token in event.auth (4ed1ef5)

BREAKING CHANGES

  • Previously the payload was found directly in event.auth, now it is in event.auth.payload to be able to put additional information into event.auth

2.4.0 (2019-07-29)

Bug Fixes

  • fix typing of before method (034b5a9)
  • log 'No authorization header found' in all cases (be87d47)

Features

  • add an option that allows making authorization mandatory (cac01c1)
  • reject unauthorized events when authorizationRequired is set (e292328)
  • update README.md (c3acb83)

2.3.0 (2019-06-07)

Features

  • build module to commonjs (a548656)

2.2.0 (2019-03-12)

Features

  • allow for tokenSources in middleware options (01197c1)
  • get token via tokenSource if it is set in the options (dc28c2d)
  • set default tokenSources (e2d5593)

2.1.1 (2019-02-16)

Bug Fixes

  • stringify JWTAuthMiddleware options in error (2f09634)

2.1.0 (2019-02-16)

Bug Fixes

  • standardize date format in TokenExpired error message (8ac46c9)

Features

  • add logging of encryption algorithm in debug mode (d4854b1)
  • allow to check token payload with a type guard (842232b)
  • throw more explicit error if token expired (50896bd)
  • throw more explicit error if token isn't valid yet (3cb1c33)

2.0.0 (2019-02-16)

Features

  • accept lower case authorization header (86d9aaa)
  • add source maps to output (74d7aab)

BREAKING CHANGES

  • Previously lowercase authorization headers were ignored. Now if both a lower case authorization and an upper case Authorization header are present, an error is thrown. Currently the middleware does not support use cases where both headers are present.

1.1.0 (2019-02-16)

Features

  • accept multivalue header format (7d30dd1)

1.0.0 (2019-02-15)

Features

  • add IAuthOptions interface (05968f2)
  • add IAuthorizedEvent type (91e785e)
  • add types to errors (af89543)
  • check if token is valid (76bd162)
  • improve error message for wrong auth format (7f40831)
  • save auth data to event.auth (48d7646)