{"id":22796280,"url":"https://github.com/makerxstudio/express-bearer","last_synced_at":"2025-04-19T13:13:14.940Z","repository":{"id":177167772,"uuid":"530955934","full_name":"MakerXStudio/express-bearer","owner":"MakerXStudio","description":"An express middleware to decode and verify JWTs from bearer authorization headers.","archived":false,"fork":false,"pushed_at":"2024-12-23T00:57:57.000Z","size":608,"stargazers_count":0,"open_issues_count":3,"forks_count":0,"subscribers_count":13,"default_branch":"main","last_synced_at":"2025-03-29T08:11:20.175Z","etag":null,"topics":["auth","express","express-bearer","npm","package","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MakerXStudio.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-08-31T06:08:58.000Z","updated_at":"2024-12-23T00:58:01.000Z","dependencies_parsed_at":null,"dependency_job_id":"bb322a55-272a-490c-8678-03f923913e5b","html_url":"https://github.com/MakerXStudio/express-bearer","commit_stats":null,"previous_names":["makerxstudio/express-bearer"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MakerXStudio%2Fexpress-bearer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MakerXStudio%2Fexpress-bearer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MakerXStudio%2Fexpress-bearer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MakerXStudio%2Fexpress-bearer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MakerXStudio","download_url":"https://codeload.github.com/MakerXStudio/express-bearer/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249701608,"owners_count":21312757,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["auth","express","express-bearer","npm","package","typescript"],"created_at":"2024-12-12T05:11:47.154Z","updated_at":"2025-04-19T13:13:14.932Z","avatar_url":"https://github.com/MakerXStudio.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Express bearer\n\nAn express middleware to decode and verify JWTs from bearer authorization headers.\n\n## What does this do?\n\n- loads signing keys from a JWKS endpoint using [jwks-rsa](https://github.com/auth0/node-jwks-rsa#readme)\n- verifies and decodes a JWT from a Bearer authorization header using [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback)\n- sets `req.user` to the verified decoded JWT payload (claims)\n\n## Usage\n\n```ts\nimport { bearerTokenMiddleware, BearerConfig } from '@makerxstudio/express-bearer'\n\nconst app = express()\nconst config: BearerConfig = {\n  jwksUri: 'https://login.microsoftonline.com/\u003ctenant ID\u003e/discovery/v2.0/keys',\n  verifyOptions: {\n    issuer: 'https://login.microsoftonline.com/\u003ctenant ID\u003e/v2.0',\n    audience: '\u003caudience ID\u003e',\n  },\n}\n\n// add the bearer token middleware (to all routes)\napp.use(bearerTokenMiddleware({ config }))\n// or... add to a specific route\napp.post('/api/admin/*', bearerTokenMiddleware({ config }))\n// or... add to a specific route + make authentication mandatory\napp.post('/api/admin/*', bearerTokenMiddleware({ config, tokenIsRequired: true }))\n\n// access the user, check the roles claim\napp.post('/api/admin/*', (req, res, next) =\u003e {\n  const roles = (req.user?.roles as string[]) ?? []\n  if (!roles.includes('Admin')) throw new Error('Authorization failed')\n  next()\n})\n```\n\nThe middleware will:\n\n- Return `401 Unauthorized` when the JWT fails decoding / verification\n- Return `401 Unauthorized` if there is no `Bearer {token}` authorization header and `tokenIsRequired` is set to `true` (default is `false`)\n\n## Options\n\n`BearerAuthOptions`:\n\n| Option            | Description                                                                                             |\n| ----------------- | ------------------------------------------------------------------------------------------------------- |\n| `config`          | The JWT handling config \\*`BearerConfig` (or \\*`BearerConfigCallback` for per-host config).             |\n| `tokenIsRequired` | Controls whether requests with no `Bearer {token}` authorization header are rejected, default: `false`. |\n| `logger`          | Optional logger implementation to log token validation errors, handler setup info entry etc.            |\n\nJWT handling `config`:\n\n| Option                         | Description                                                                                                                                                                                                                                                                     |\n| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `jwksUri`                      | The endpoint to load signing keys via [jwks-rsa](https://github.com/auth0/node-jwks-rsa#readme)                                                                                                                                                                                 |\n| `verifyOptions`                | The options passed into [jwt.verify](https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback)                                                                                                                                              |\n| `unauthorizedResponse`         | Optional. Callback of type `(req: Request, res: Response) =\u003e Response)` which provides a way to customise the HTTP response when the bearer token is required and not present, or the validation fails.\u003cbr\u003eIf not provided, a plain text 401 Unauthorized response is returned. |\n| `explicitNoIssuerValidation`   | Optional. The default behaviour is to enforce issuer validation through `verifyOptions.issuer` to avoid security issues through misconfiguration.\u003cbr\u003eIf it's intentional to not validate the issuer of incoming tokens, set this property to `true`.                            |\n| `explicitNoAudienceValidation` | Optional. The default behaviour is to enforce audience validation through `verifyOptions.audience` to avoid security issues through misconfiguration.\u003cbr\u003eIf it's intentional to not validate the audience of incoming tokens, set this property to `true`.                      |\n\n### Multitenant apps\n\nTo specify per-host config, provide a \\*`BearerConfigCallback` in the form of `(host: string) =\u003e BearerConfig`.\n\nNote: the callback will only be called once per host (config is cached).\n\n### Apps accepting bearer tokens from multiple issuers\n\nIf your app needs to accept bearer tokens from multiple issuers (OIDC endpoints) **each with different JWKS URIs** on a single endpoint (not varied by host), `multiIssuerBearerTokenMiddleware` supports this with a different approach. It will:\n\n- decode the token without verifying it\n- use the `iss` claim to access the issuer-specific config `IssuerOptions` (or return unauthorized, if not found)\n- verify the token using the issuer-specific config (caching JwksClient instances per JWKS URI)\n\n#### Multi-issuer options\n\n```ts\nimport { IssuerOptions, multiIssuerBearerTokenMiddleware, MultiIssuerBearerAuthOptions } from '@makerxstudio/express-bearer'\n\nconst app = express()\nconst issuerOptions: Record\u003cstring, IssuerOptions\u003e = {\n  'https://example.com/oidc': {\n    jwksUri: 'https://example.com/oidc/jwks',\n    verifyOptions: {\n      audience: 'https://api.example.com',\n    },\n  },\n  'https://login.microsoftonline.com/\u003ctenant ID\u003e/v2.0': {\n    jwksUri: 'https://login.microsoftonline.com/\u003ctenant ID\u003e/discovery/v2.0/keys',\n    verifyOptions: {\n      audience: '\u003caudience ID\u003e',\n    },\n  },\n}\n\n// add the multi issuer bearer token middleware (to all routes)\napp.use(multiIssuerBearerTokenMiddleware({ issuerOptions, tokenIsRequired: true }))\n```\n\n## Logging\n\nSet the logger implementation to an object that fulfills the `Logger` definition:\n\n```ts\ntype Logger = {\n  error(message: string, ...optionalParams: unknown[]): void\n  warn(message: string, ...optionalParams: unknown[]): void\n  info(message: string, ...optionalParams: unknown[]): void\n  verbose(message: string, ...optionalParams: unknown[]): void\n  debug(message: string, ...optionalParams: unknown[]): void\n}\n```\n\nNote: this type is compatible with [winston loggers](https://github.com/winstonjs/winston).\n\nThe following example uses console logging:\n\n```ts\nconst logger: Logger = {\n  error: (message: string, ...params: unknown[]) =\u003e console.error(message, ...params),\n  warn: (message: string, ...params: unknown[]) =\u003e console.warn(message, ...params),\n  info: (message: string, ...params: unknown[]) =\u003e console.info(message, ...params),\n  verbose: (message: string, ...params: unknown[]) =\u003e console.trace(message, ...params),\n  debug: (message: string, ...params: unknown[]) =\u003e console.debug(message, ...params),\n}\n\nconst config: BearerConfig = {\n  jwksUri: ...,\n  verifyOptions: { ... },\n  logger,\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmakerxstudio%2Fexpress-bearer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmakerxstudio%2Fexpress-bearer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmakerxstudio%2Fexpress-bearer/lists"}