{"id":13527601,"url":"https://github.com/auth0/express-jwt","last_synced_at":"2025-05-12T04:58:55.410Z","repository":{"id":11352562,"uuid":"13783958","full_name":"auth0/express-jwt","owner":"auth0","description":"connect/express middleware that validates a JsonWebToken (JWT) and set the req.user with the attributes","archived":false,"fork":false,"pushed_at":"2024-12-16T21:34:52.000Z","size":658,"stargazers_count":4507,"open_issues_count":62,"forks_count":440,"subscribers_count":153,"default_branch":"master","last_synced_at":"2025-05-12T02:17:20.067Z","etag":null,"topics":["express-jwt","jwt"],"latest_commit_sha":null,"homepage":null,"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/auth0.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","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":"2013-10-22T19:45:55.000Z","updated_at":"2025-05-12T00:51:44.000Z","dependencies_parsed_at":"2025-04-01T06:06:16.814Z","dependency_job_id":"1fb21b35-935f-4733-b711-cea54edc4922","html_url":"https://github.com/auth0/express-jwt","commit_stats":{"total_commits":244,"total_committers":73,"mean_commits":"3.3424657534246576","dds":"0.49590163934426235","last_synced_commit":"f42a0e99422fe85fadd0a209b8497b64995e94cf"},"previous_names":[],"tags_count":67,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/auth0%2Fexpress-jwt","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/auth0%2Fexpress-jwt/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/auth0%2Fexpress-jwt/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/auth0%2Fexpress-jwt/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/auth0","download_url":"https://codeload.github.com/auth0/express-jwt/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253669046,"owners_count":21945056,"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":["express-jwt","jwt"],"created_at":"2024-08-01T06:01:53.523Z","updated_at":"2025-05-12T04:58:55.381Z","avatar_url":"https://github.com/auth0.png","language":"TypeScript","readme":"# express-jwt\n\nThis module provides Express middleware for validating JWTs ([JSON Web Tokens](https://jwt.io)) through the [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken/) module. The decoded JWT payload is available on the request object.\n\n## Install\n\n```\n$ npm install express-jwt\n```\n\n## API\n\n`expressjwt(options)`\n\nOptions has the following parameters:\n\n- `secret: jwt.Secret | GetVerificationKey` (required): The secret as a string or a function to retrieve the secret.\n- `getToken?: TokenGetter` (optional): A function that receives the express `Request` and returns the token, by default it looks in the `Authorization` header.\n- `isRevoked?: IsRevoked` (optional): A function to verify if a token is revoked.\n- `onExpired?: ExpirationHandler` (optional): A function to handle expired tokens.\n- `credentialsRequired?: boolean` (optional): If its false, continue to the next middleware if the request does not contain a token instead of failing, defaults to true.\n- `requestProperty?: string` (optional): Name of the property in the request object where the payload is set. Default to `req.auth`.\n- Plus... all the options available in the [jsonwebtoken verify function](https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback).\n\nThe available functions have the following interface:\n\n- `GetVerificationKey = (req: express.Request, token: jwt.Jwt | undefined) =\u003e Promise\u003cjwt.Secret\u003e;`\n- `IsRevoked = (req: express.Request, token: jwt.Jwt | undefined) =\u003e Promise\u003cboolean\u003e;`\n- `TokenGetter = (req: express.Request) =\u003e string | Promise\u003cstring\u003e | undefined;`\n\n## Usage\n\nBasic usage using an HS256 secret:\n\n```javascript\nvar { expressjwt: jwt } = require(\"express-jwt\");\n// or ES6\n// import { expressjwt, ExpressJwtRequest } from \"express-jwt\";\n\napp.get(\n  \"/protected\",\n  jwt({ secret: \"shhhhhhared-secret\", algorithms: [\"HS256\"] }),\n  function (req, res) {\n    if (!req.auth.admin) return res.sendStatus(401);\n    res.sendStatus(200);\n  }\n);\n```\n\nThe decoded JWT payload is available on the request via the `auth` property.\n\n\u003e The default behavior of the module is to extract the JWT from the `Authorization` header as an [OAuth2 Bearer token](https://oauth.net/2/bearer-tokens/).\n\n### Required Parameters\n\nThe `algorithms` parameter is required to prevent potential downgrade attacks when providing third party libraries as **secrets**.\n\n:warning: **Do not mix symmetric and asymmetric (ie HS256/RS256) algorithms**: Mixing algorithms without further validation can potentially result in downgrade vulnerabilities.\n\n```javascript\njwt({\n  secret: \"shhhhhhared-secret\",\n  algorithms: [\"HS256\"],\n  //algorithms: ['RS256']\n});\n```\n\n### Additional Options\n\nYou can specify audience and/or issuer as well, which is highly recommended for security purposes:\n\n```javascript\njwt({\n  secret: \"shhhhhhared-secret\",\n  audience: \"http://myapi/protected\",\n  issuer: \"http://issuer\",\n  algorithms: [\"HS256\"],\n});\n```\n\n\u003e If the JWT has an expiration (`exp`), it will be checked.\n\nIf you are using a base64 URL-encoded secret, pass a `Buffer` with `base64` encoding as the secret instead of a string:\n\n```javascript\njwt({\n  secret: Buffer.from(\"shhhhhhared-secret\", \"base64\"),\n  algorithms: [\"RS256\"],\n});\n```\n\nTo only protect specific paths (e.g. beginning with `/api`), use [express router](https://expressjs.com/en/4x/api.html#app.use) call `use`, like so:\n\n```javascript\napp.use(\"/api\", jwt({ secret: \"shhhhhhared-secret\", algorithms: [\"HS256\"] }));\n```\n\nOr, the other way around, if you want to make some paths unprotected, call `unless` like so.\n\n```javascript\napp.use(\n  jwt({\n    secret: \"shhhhhhared-secret\",\n    algorithms: [\"HS256\"],\n  }).unless({ path: [\"/token\"] })\n);\n```\n\nThis is especially useful when applying to multiple routes. In the example above, `path` can be a string, a regexp, or an array of any of those.\n\n\u003e For more details on the `.unless` syntax including additional options, please see [express-unless](https://github.com/jfromaniello/express-unless).\n\nThis module also support tokens signed with public/private key pairs. Instead of a secret, you can specify a Buffer with the public key\n\n```javascript\nvar publicKey = fs.readFileSync(\"/path/to/public.pub\");\njwt({ secret: publicKey, algorithms: [\"RS256\"] });\n```\n\n### Customizing Token Location\n\nA custom function for extracting the token from a request can be specified with\nthe `getToken` option. This is useful if you need to pass the token through a\nquery parameter or a cookie. You can throw an error in this function and it will\nbe handled by `express-jwt`.\n\n```javascript\napp.use(\n  jwt({\n    secret: \"hello world !\",\n    algorithms: [\"HS256\"],\n    credentialsRequired: false,\n    getToken: function fromHeaderOrQuerystring(req) {\n      if (\n        req.headers.authorization \u0026\u0026\n        req.headers.authorization.split(\" \")[0] === \"Bearer\"\n      ) {\n        return req.headers.authorization.split(\" \")[1];\n      } else if (req.query \u0026\u0026 req.query.token) {\n        return req.query.token;\n      }\n      return null;\n    },\n  })\n);\n```\n\n### Retrieve key dynamically\n\nIf you need to obtain the key dynamically from other sources, you can pass a function in the `secret` parameter with the following parameters:\n\n- `req` (`Object`) - The express `request` object.\n- `token` (`Object`) - An object with the JWT payload and headers.\n\nFor example, if the secret varies based on the [issuer](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#issDef):\n\n```javascript\nvar jwt = require(\"express-jwt\");\nvar data = require(\"./data\");\nvar utilities = require(\"./utilities\");\n\nvar getSecret = async function (req, token) {\n  const issuer = token.payload.iss;\n  const tenant = await data.getTenantByIdentifier(issuer);\n  if (!tenant) {\n    throw new Error(\"missing_secret\");\n  }\n  return utilities.decrypt(tenant.secret);\n};\n\napp.get(\n  \"/protected\",\n  jwt({ secret: getSecret, algorithms: [\"HS256\"] }),\n  function (req, res) {\n    if (!req.auth.admin) return res.sendStatus(401);\n    res.sendStatus(200);\n  }\n);\n```\n\n### Secret rotation\n\nThe getSecret callback could also be used in cases where the same issuer might issue tokens with different keys at certain point:\n\n```js\nvar getSecret = async function (req, token) {\n  const { iss } = token.payload;\n  const { kid } = token.header;\n  // get the verification key by a given key-id and issuer.\n  return verificationKey;\n};\n```\n\n### Revoked tokens\n\nIt is possible that some tokens will need to be revoked so they cannot be used any longer. You can provide a function as the `isRevoked` option. The signature of the function is `function(req, payload, done)`:\n\n- `req` (`Object`) - The express `request` object.\n- `token` (`Object`) - An object with the JWT payload and headers.\n\nFor example, if the `(iss, jti)` claim pair is used to identify a JWT:\n\n```javascript\nconst jwt = require(\"express-jwt\");\nconst data = require(\"./data\");\n\nconst isRevokedCallback = async (req, token) =\u003e {\n  const issuer = token.payload.iss;\n  const tokenId = token.payload.jti;\n  const token = await data.getRevokedToken(issuer, tokenId);\n  return token !== \"undefined\";\n};\n\napp.get(\n  \"/protected\",\n  jwt({\n    secret: \"shhhhhhared-secret\",\n    algorithms: [\"HS256\"],\n    isRevoked: isRevokedCallback,\n  }),\n  function (req, res) {\n    if (!req.auth.admin) return res.sendStatus(401);\n    res.sendStatus(200);\n  }\n);\n```\n\n### Handling expired tokens\n\nYou can handle expired tokens as follows:\n\n```javascript\n  jwt({\n    secret: \"shhhhhhared-secret\",\n    algorithms: [\"HS256\"],\n    onExpired: async (req, err) =\u003e {\n      if (new Date() - err.inner.expiredAt \u003c 5000) { return;}\n      throw err;\n    },,\n  })\n```\n\n### Error handling\n\nThe default behavior is to throw an error when the token is invalid, so you can add your custom logic to manage unauthorized access as follows:\n\n```javascript\napp.use(function (err, req, res, next) {\n  if (err.name === \"UnauthorizedError\") {\n    res.status(401).send(\"invalid token...\");\n  } else {\n    next(err);\n  }\n});\n```\n\nYou might want to use this module to identify registered users while still providing access to unregistered users. You can do this by using the option `credentialsRequired`:\n\n```javascript\napp.use(\n  jwt({\n    secret: \"hello world !\",\n    algorithms: [\"HS256\"],\n    credentialsRequired: false,\n  })\n);\n```\n\n## Typescript\n\nA `Request` type is provided from `express-jwt`, which extends `express.Request` with the `auth` property. It could be aliased, like how `JWTRequest` is below.\n\n```typescript\nimport { expressjwt, Request as JWTRequest } from \"express-jwt\";\n\napp.get(\n  \"/protected\",\n  expressjwt({ secret: \"shhhhhhared-secret\", algorithms: [\"HS256\"] }),\n  function (req: JWTRequest, res: express.Response) {\n    if (!req.auth?.admin) return res.sendStatus(401);\n    res.sendStatus(200);\n  }\n);\n```\n\n## Migration from v6\n\n1. The middleware function is now available as a named import rather than a default one: import { expressjwt } from 'express-jwt'\n2. The decoded JWT payload is now available as req.auth rather than req.user\n3. The `secret` function had `(req, header, payload, cb)`, now it can return a promise and receives `(req, token)`. `token` has `header` and `payload`.\n4. The `isRevoked` function had `(req, payload, cb)`, now it can return a promise and receives `(req, token)`. `token` has `header` and `payload`.\n\n## Related Modules\n\n- [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken) — JSON Web Token sign and verification\n- [express-jwt-permissions](https://github.com/MichielDeMey/express-jwt-permissions) - Permissions middleware for JWT tokens\n\n## Tests\n\n```\n$ npm install\n$ npm test\n```\n\n## Contributors\n\nCheck them out [here](https://github.com/auth0/express-jwt/graphs/contributors)\n\n## Issue Reporting\n\nIf you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/whitehat) details the procedure for disclosing security issues.\n\n## Author\n\n[Auth0](https://auth0.com)\n\n## License\n\nThis project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info.\n","funding_links":[],"categories":["TypeScript","Libraries","Json Web Token (JWT)","中间件","\u003ca name=\"TypeScript\"\u003e\u003c/a\u003eTypeScript"],"sub_categories":["Node.js","React Components"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fauth0%2Fexpress-jwt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fauth0%2Fexpress-jwt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fauth0%2Fexpress-jwt/lists"}