{"library":"middy-middleware-jwt-auth","title":"Middy JWT Authorization Middleware","description":"middy-middleware-jwt-auth is a specialized middleware designed for the Middy.js framework, enabling JSON Web Token (JWT) authorization for AWS Lambda functions. Inspired by `express-jwt`, it simplifies the process of verifying JWTs and injecting the decoded payload into the Lambda `event.auth` object. The current stable version is `6.3.0`. The library follows the Middy.js release cadence, frequently updating to support new major versions of `@middy/core`. Key differentiators include its tight integration with the Middy ecosystem, robust type definitions for TypeScript users, and customizable token extraction and verification options, including support for various encryption algorithms and asynchronous secret retrieval. It aims to provide a reliable and easy-to-use solution for securing serverless API endpoints with JWTs.","language":"javascript","status":"active","last_verified":"Thu Apr 23","install":{"commands":["npm install middy-middleware-jwt-auth"],"cli":null},"imports":["import JWTAuthMiddleware from 'middy-middleware-jwt-auth';","import { EncryptionAlgorithms } from 'middy-middleware-jwt-auth';","import { IAuthorizedEvent } from 'middy-middleware-jwt-auth';"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import createHttpError from \"http-errors\";\nimport middy from \"@middy/core\";\nimport httpErrorHandler from \"@middy/http-error-handler\";\nimport httpHeaderNormalizer from \"@middy/http-header-normalizer\";\nimport JWTAuthMiddleware, {\n  EncryptionAlgorithms,\n  IAuthorizedEvent,\n} from \"middy-middleware-jwt-auth\";\n\n// Define the token payload structure expected from your JWT\ninterface ITokenPayload {\n  permissions: string[];\n}\n\n// Type guard for the token payload to ensure runtime safety\nfunction isTokenPayload(token: any): token is ITokenPayload {\n  return (\n    token != null &&\n    Array.isArray(token.permissions) &&\n    token.permissions.every((permission: any) => typeof permission === \"string\")\n  );\n}\n\n// Your AWS Lambda handler function\nconst helloWorld = async (event: IAuthorizedEvent<ITokenPayload>) => {\n  // Access the authenticated payload from event.auth\n  if (!event.auth || !isTokenPayload(event.auth.payload)) {\n    throw createHttpError(401, \"Unauthorized: Invalid token payload\");\n  }\n\n  // Perform authorization check based on permissions in the token\n  if (event.auth.payload.permissions.indexOf(\"helloWorld\") === -1) {\n    throw createHttpError(\n      403,\n      `User not authorized for helloWorld, only found permissions [${event.auth.payload.permissions.join(\", \")}]`,\n      {\n        type: \"NotAuthorized\",\n      },\n    );\n  }\n\n  return {\n    body: JSON.stringify({\n      data: `Hello world! Here's your token: ${event.auth.token}`,\n      userId: event.auth.payload.sub // Assuming 'sub' is in your token\n    }),\n    statusCode: 200,\n  };\n};\n\n// 'Middyfy' your handler and attach the JWT authorization middleware\nexport const handler = middy(helloWorld)\n  .use(httpHeaderNormalizer()) // Ensures Authorization header is consistently cased\n  .use(httpErrorHandler())    // Catches errors thrown by JWTAuthMiddleware and returns appropriate HTTP responses\n  .use(\n    JWTAuthMiddleware({\n      algorithm: EncryptionAlgorithms.HS256,\n      credentialsRequired: true, // Set to true to make a missing or invalid token result in a 401\n      secretOrPublicKey: process.env.JWT_SECRET ?? 'supersecretkey',\n      // You can also specify an async function for secretOrPublicKey or tokenSource since v6.3.0\n      // secretOrPublicKey: async (header, payload, done) => { /* fetch secret */ done(null, 'secret'); },\n      // tokenSource: (event) => event.headers['x-custom-token'],\n    }),\n  );","lang":"typescript","description":"This quickstart demonstrates how to set up a Middy handler with `middy-middleware-jwt-auth` to enforce JWT authentication, extract the token payload, and perform fine-grained authorization checks based on the decoded token's content.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}