{"id":13564167,"url":"https://github.com/koajs/jwt","last_synced_at":"2025-05-14T10:08:36.232Z","repository":{"id":13653451,"uuid":"16346957","full_name":"koajs/jwt","owner":"koajs","description":"Koa middleware for validating JSON Web Tokens","archived":false,"fork":false,"pushed_at":"2024-09-10T02:34:25.000Z","size":350,"stargazers_count":1343,"open_issues_count":6,"forks_count":120,"subscribers_count":21,"default_branch":"master","last_synced_at":"2024-10-29T15:22:59.202Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","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/koajs.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":"2014-01-29T14:24:57.000Z","updated_at":"2024-10-10T02:19:23.000Z","dependencies_parsed_at":"2024-11-06T09:39:55.834Z","dependency_job_id":null,"html_url":"https://github.com/koajs/jwt","commit_stats":{"total_commits":227,"total_committers":53,"mean_commits":4.283018867924528,"dds":0.7092511013215859,"last_synced_commit":"c75adec00c4f3c0a05659b2eea28a62ed641fcc9"},"previous_names":[],"tags_count":35,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/koajs%2Fjwt","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/koajs%2Fjwt/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/koajs%2Fjwt/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/koajs%2Fjwt/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/koajs","download_url":"https://codeload.github.com/koajs/jwt/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247609761,"owners_count":20966239,"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":[],"created_at":"2024-08-01T13:01:27.448Z","updated_at":"2025-04-09T01:23:00.665Z","avatar_url":"https://github.com/koajs.png","language":"JavaScript","readme":"# [**koa-jwt**](https://github.com/koajs/jwt)\n\n\u003e Koa middleware for validating JSON Web Tokens.\n\n[![node version][node-image]][node-url]\n[![npm download][download-image]][download-url]\n[![npm stats][npm-image]][npm-url]\n[![test status][travis-image]][travis-url]\n[![coverage][coveralls-image]][coveralls-url]\n[![license][license-image]][license-url]\n\n[npm-image]: https://img.shields.io/npm/v/koa-jwt.svg?maxAge=2592000\u0026style=flat-square\n[npm-url]: https://npmjs.org/package/koa-jwt\n[travis-image]: https://img.shields.io/travis/koajs/jwt/master.svg?maxAge=3600\u0026style=flat-square\n[travis-url]: https://travis-ci.org/koajs/jwt\n[coveralls-image]: https://img.shields.io/coveralls/koajs/jwt/master.svg?maxAge=2592000\u0026style=flat-square\n[coveralls-url]: https://coveralls.io/r/koajs/jwt\n[node-image]: https://img.shields.io/node/v/koa-jwt.svg?maxAge=2592000\u0026style=flat-square\n[node-url]: http://nodejs.org/download/\n[download-image]: https://img.shields.io/npm/dm/koa-jwt.svg?maxAge=2592000\u0026style=flat-square\n[download-url]: https://npmjs.org/package/koa-jwt\n[license-image]: https://img.shields.io/npm/l/koa-jwt.svg?maxAge=2592000\u0026style=flat-square\n[license-url]: https://github.com/koajs/jwt/blob/master/LICENSE\n\n\n## Table of Contents\n\n- [koa-jwt](#koa-jwt)\n  - [Table of Contents](#table-of-contents)\n  - [Introduction](#introduction)\n  - [Install](#install)\n  - [Usage](#usage)\n    - [Retrieving the token](#retrieving-the-token)\n    - [Passing the secret](#passing-the-secret)\n    - [Checking if the token is revoked](#checking-if-the-token-is-revoked)\n  - [Example](#example)\n  - [Token Verification Exceptions](#token-verification-exceptions)\n  - [Related Modules](#related-modules)\n  - [Tests](#tests)\n  - [Author](#author)\n  - [Credits](#credits)\n  - [Contributors](#contributors)\n  - [License](#license)\n\n\n## Introduction\n\nThis module lets you authenticate HTTP requests using JSON Web Tokens\nin your [Koa](http://koajs.com/) (node.js) applications.\n\nSee [this article](https://github.com/dentarg/blog/blob/master/_posts/2014-01-07-angularjs-authentication-with-cookies-vs-token.markdown)\nfor a good introduction.\n\n* If you are using `koa` version 2+, and you have a version of node \u003c 7.6, install `koa-jwt@2`.\n* `koa-jwt` version 3+ on the [master](https://github.com/koajs/jwt) branch uses `async` / `await` and hence requires node \u003e= 7.6.\n* If you are using `koa` version 1, you need to install `koa-jwt@1` from npm. This is the code on the [koa-v1](https://github.com/koajs/jwt/tree/koa-v1) branch.\n\n\n## Install\n\n```bash\nnpm install koa-jwt\n```\n\n\n## Usage\n\nThe JWT authentication middleware authenticates callers using a JWT\ntoken. If the token is valid, `ctx.state.user` (by default) will be set\nwith the JSON object decoded to be used by later middleware for\nauthorization and access control.\n\n\n### Retrieving the token\n\nThe token is normally provided in a HTTP header (`Authorization`), but it\ncan also be provided in a cookie by setting the `opts.cookie` option\nto the name of the cookie that contains the token. Custom token retrieval\ncan also be done through the `opts.getToken` option. The provided function\nshould match the following interface:\n\n```js\n/**\n * Your custom token resolver\n * @this The ctx object passed to the middleware\n *\n * @param  {Object}      opts The middleware's options\n * @return {String|null}      The resolved token or null if not found\n */\n```\n\nopts, the middleware's options:\n\n* getToken\n* secret\n* key\n* isRevoked\n* passthrough\n* cookie\n* audience\n* issuer\n* debug\n\nThe resolution order for the token is the following. The first non-empty token resolved will be the one that is verified.\n\n* `opts.getToken` function.\n* check the cookies (if `opts.cookie` is set).\n* check the Authorization header for a bearer token.\n\n### Passing the secret\n\nOne can provide a single secret, or array of secrets in `opts.secret`. An\nalternative is to have an earlier middleware set `ctx.state.secret`,\ntypically per request. If this property exists, it will be used instead\nof `opts.secret`.\n\n### Checking if the token is revoked\n\nYou can provide a async function to jwt for it check the token is revoked.\nOnly you set the function in `opts.isRevoked`. The provided function should\nmatch the following interface:\n\n```js\n/**\n * Your custom isRevoked resolver\n *\n * @param  {object}   ctx            The ctx object passed to the middleware\n * @param  {object}   decodedToken   Content of the token\n * @param  {object}   token          token The token\n * @return {Promise}                 If the token is not revoked, the promise must resolve with false, otherwise (the promise resolve with true or error) the token is revoked\n */\n```\n\n\n## Example\n\n```js\nvar Koa = require('koa');\nvar jwt = require('koa-jwt');\n\nvar app = new Koa();\n\n// Custom 401 handling if you don't want to expose koa-jwt errors to users\napp.use(function(ctx, next){\n  return next().catch((err) =\u003e {\n    if (401 == err.status) {\n      ctx.status = 401;\n      ctx.body = 'Protected resource, use Authorization header to get access\\n';\n    } else {\n      throw err;\n    }\n  });\n});\n\n// Unprotected middleware\napp.use(function(ctx, next){\n  if (ctx.url.match(/^\\/public/)) {\n    ctx.body = 'unprotected\\n';\n  } else {\n    return next();\n  }\n});\n\n// Middleware below this line is only reached if JWT token is valid\napp.use(jwt({ secret: 'shared-secret' }));\n\n// Protected middleware\napp.use(function(ctx){\n  if (ctx.url.match(/^\\/api/)) {\n    ctx.body = 'protected\\n';\n  }\n});\n\napp.listen(3000);\n```\n\nAlternatively you can conditionally run the `jwt` middleware under certain conditions:\n\n```js\nvar Koa = require('koa');\nvar jwt = require('koa-jwt');\n\nvar app = new Koa();\n\n// Middleware below this line is only reached if JWT token is valid\n// unless the URL starts with '/public'\napp.use(jwt({ secret: 'shared-secret' }).unless({ path: [/^\\/public/] }));\n\n// Unprotected middleware\napp.use(function(ctx, next){\n  if (ctx.url.match(/^\\/public/)) {\n    ctx.body = 'unprotected\\n';\n  } else {\n    return next();\n  }\n});\n\n// Protected middleware\napp.use(function(ctx){\n  if (ctx.url.match(/^\\/api/)) {\n    ctx.body = 'protected\\n';\n  }\n});\n\napp.listen(3000);\n```\n\nFor more information on `unless` exceptions, check [koa-unless](https://github.com/Foxandxss/koa-unless).\n\nYou can also add the `passthrough` option to always yield next,\neven if no valid Authorization header was found:\n\n```js\napp.use(jwt({ secret: 'shared-secret', passthrough: true }));\n```\n\nThis lets downstream middleware make decisions based on whether `ctx.state.user` is set. You can still handle errors using  `ctx.state.jwtOriginalError`.\n\nIf you prefer to use another ctx key for the decoded data, just pass in `key`, like so:\n\n```js\napp.use(jwt({ secret: 'shared-secret', key: 'jwtdata' }));\n```\n\nThis makes the decoded data available as `ctx.state.jwtdata`.\n\nYou can specify audience and/or issuer as well:\n\n```js\napp.use(jwt({ secret:   'shared-secret',\n              audience: 'http://myapi/protected',\n              issuer:   'http://issuer' }));\n```\n\nYou can specify an array of secrets.\n\nThe token will be considered valid if it validates successfully against _any_ of the supplied secrets.\nThis allows for rolling shared secrets, for example:\n\n```js\napp.use(jwt({ secret: ['old-shared-secret', 'new-shared-secret'] }));\n```\n\n\n## Token Verification Exceptions\n\nIf the JWT has an expiration (`exp`), it will be checked.\n\nAll error codes for token verification can be found at: [https://github.com/auth0/node-jsonwebtoken#errors--codes](https://github.com/auth0/node-jsonwebtoken#errors--codes).\n\nNotifying a client of error codes (e.g token expiration) can be achieved by sending the `err.originalError.message` error code to the client. If passthrough is enabled use `ctx.state.jwtOriginalError`.\n\n```js\n// Custom 401 handling (first middleware)\napp.use(function (ctx, next) {\n  return next().catch((err) =\u003e {\n    if (err.status === 401) {\n      ctx.status = 401;\n      ctx.body = {\n        error: err.originalError ? err.originalError.message : err.message\n      };\n    } else {\n      throw err;\n    }\n  });\n});\n```\n\nIf the `tokenKey` option is present, and a valid token is found, the original raw token\nis made available to subsequent middleware as `ctx.state[opts.tokenKey]`.\n\nThis module also support tokens signed with public/private key pairs. Instead\nof a secret, you can specify a Buffer with the public key:\n\n```js\nvar publicKey = fs.readFileSync('/path/to/public.pub');\napp.use(jwt({ secret: publicKey }));\n```\n\nIf the `secret` option is a function, this function is called for each JWT received in\norder to determine which secret is used to verify the JWT.\n\nThe signature of this function should be `(header, payload) =\u003e [Promise(secret)]`, where\n`header` is the token header and `payload` is the token payload. For instance to support JWKS token header should contain `alg` and `kid`: algorithm and key id fields respectively.\n\nThis option can be used to support JWKS (JSON Web Key Set) providers by using\n[node-jwks-rsa](https://github.com/auth0/node-jwks-rsa). For example:\n\n```js\nconst { koaJwtSecret } = require('jwks-rsa');\n\napp.use(jwt({ \n  secret: koaJwtSecret({\n    jwksUri: 'https://sandrino.auth0.com/.well-known/jwks.json',\n    cache: true,\n    cacheMaxEntries: 5,\n    cacheMaxAge: ms('10h') \n  }),\n  audience: 'http://myapi/protected',\n  issuer: 'http://issuer' \n}));\n```\n\n\n## Related Modules\n\n* [jsonwebtoken](https://github.com/auth0/node-jsonwebtoken) — JSON Web Token signing and verification.\n\nNote that koa-jwt no longer exports the `sign`, `verify` and `decode` functions from `jsonwebtoken` in the koa-v2 branch.\n\n## Tests\n\n```bash\nnpm install\nnpm test\n```\n\n\n## Authors/Maintainers\n\n* [Stian Grytøyr](https://github.com/stiang) (initial author)\n* [Scott Donnelly](https://github.com/sdd) (current maintainer)\n\n## Credits\n\nThe initial code was largely based on [express-jwt](https://github.com/auth0/express-jwt).\n\n* [Auth0](http://auth0.com/)\n* [Matias Woloski](http://github.com/woloski)\n\n## Contributors\n\n* [Foxandxss](https://github.com/Foxandxss)\n* [soygul](https://github.com/soygul)\n* [tunnckoCore](https://github.com/tunnckoCore)\n* [getuliojr](https://github.com/getuliojr)\n* [cesarandreu](https://github.com/cesarandreu)\n* [michaelwestphal](https://github.com/michaelwestphal)\n* [Jackong](https://github.com/Jackong)\n* [danwkennedy](https://github.com/danwkennedy)\n* [nfantone](https://github.com/nfantone)\n* [scttcper](https://github.com/scttcper)\n* [jhnns](https://github.com/jhnns)\n* [dunnock](https://github.com/dunnock)\n* [3imed-jaberi](https://github.com/3imed-jaberi)\n\n\n## License\n\n[MIT](/LICENSE)\n","funding_links":[],"categories":["JavaScript","Middleware","Koa","仓库","Koa Middlewares"],"sub_categories":["React","中间件"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkoajs%2Fjwt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkoajs%2Fjwt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkoajs%2Fjwt/lists"}