{"id":13799866,"url":"https://github.com/uhop/koa-cognito-middleware","last_synced_at":"2025-04-23T18:23:27.480Z","repository":{"id":54122617,"uuid":"182290100","full_name":"uhop/koa-cognito-middleware","owner":"uhop","description":"Koa middleware for AWS Cognito integration.","archived":false,"fork":false,"pushed_at":"2023-06-18T19:13:23.000Z","size":77,"stargazers_count":4,"open_issues_count":3,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-21T06:09:27.781Z","etag":null,"topics":["aws-cognito","jwt","koa","user-pool"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/uhop.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"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":"2019-04-19T15:57:45.000Z","updated_at":"2023-06-12T04:24:52.000Z","dependencies_parsed_at":"2024-08-04T00:14:32.070Z","dependency_job_id":null,"html_url":"https://github.com/uhop/koa-cognito-middleware","commit_stats":null,"previous_names":[],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uhop%2Fkoa-cognito-middleware","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uhop%2Fkoa-cognito-middleware/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uhop%2Fkoa-cognito-middleware/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uhop%2Fkoa-cognito-middleware/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/uhop","download_url":"https://codeload.github.com/uhop/koa-cognito-middleware/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250488274,"owners_count":21438754,"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":["aws-cognito","jwt","koa","user-pool"],"created_at":"2024-08-04T00:01:06.745Z","updated_at":"2025-04-23T18:23:27.458Z","avatar_url":"https://github.com/uhop.png","language":"JavaScript","funding_links":[],"categories":["仓库"],"sub_categories":["中间件"],"readme":"# `koa-cognito-middleware` [![NPM version][npm-img]][npm-url]\n\n[npm-img]: https://img.shields.io/npm/v/koa-cognito-middleware.svg\n[npm-url]: https://npmjs.org/package/koa-cognito-middleware\n\nThe [Koa](https://koajs.com/) middleware to authenticate and authorized users using [AWS Cognito](https://aws.amazon.com/cognito/)\n[user pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html).\nIt validates a JWT token (either an id or access token) and populates `ctx.state.user`, or any other property of your choice,\nwith its deciphered content. Simple helpers are provided to make decisions on accessibility of API endpoints for a given user.\n\nThis project is based on [cognito-toolkit](https://www.npmjs.com/package/cognito-toolkit). It is a sister project of [cognito-express-middleware](https://www.npmjs.com/package/cognito-express-middleware).\n\n# Examples\n\n```js\nconst Koa = require('koa');\nconst Router = require('koa-router');\nconst getUser = require('koa-cognito-middleware');\n\nconst {isAuthenticated, hasScope, hasGroup, isAllowed} = getUser;\n\nconst app = new Koa();\n\n// run getUser() on every request\napp.use(getUser({\n  region: 'us-east-1',\n  userPoolId: 'us-east-1_MY_USER_POOL'\n}));\n\n// populate router1 with custom authorization rules\n\nconst router1 = new Router();\n\nrouter1.get('/a',\n  ctx =\u003e (ctx.body = 'all allowed'));\n\nrouter1.get('/b', isAuthenticated,\n  ctx =\u003e (ctx.body = 'all authenticated'));\n\nrouter1.post('/c', hasGroup('user-type/writers'),\n  ctx =\u003e (ctx.body = 'only a writers group'));\n\nrouter1.post('/d', hasScope('writers'),\n  ctx =\u003e (ctx.body = 'only with a writers scope'));\n\nrouter1.post('/user',\n  ctx =\u003e (ctx.body = req.user || {}));\n\napp\n  .use(router1.routes())\n  .use(router1.allowedMethods());\n\n// protect all routes with a single validator\n\nconst router2 = new Router();\n// populate router2\n\nconst readMethods = {GET: 1, HEAD: 1, OPTIONS: 1};\n\nconst validator = async (ctx, groups, scopes) =\u003e {\n  if (readMethods[ctx.method.toUpperCase()] === 1) return true;\n  // only writers can use other methods (POST, PUT, PATCH, DELETE...)\n  if (groups.some(g =\u003e g === 'user-type/writers')) return true;\n  if (scopes.some(s =\u003e s === 'writers')) return true;\n  return false;\n};\n\napp\n  .use(isAllowed(validator))\n  .get('/lift', ctx =\u003e {\n    const user = ctx.state.user;\n    if (user) {\n      user.setAuthCookie(ctx, {domain: 'api.my-domain.com'});\n    }\n    ctx.status = 204;\n  })\n  .use(router2.routes())\n  .use(router2.allowedMethods());\n\n// now all routes of router2 are protected by our validator\n```\n\n# How to install\n\n```txt\nnpm install --save koa-cognito-middleware\n# yarn add koa-cognito-middleware\n```\n\n# Documentation\n\nAll provided functions are explained below. See the examples above for usage patterns.\n\n## `getUser(options [, pools])`\n\nThis is the main function directly returned from the module. It populates `ctx.state[getUser.stateUserProperty]` (see below)\nwith a decoded JWT or assigns it to `null` (cannot positively authenticate).\nOther helpers or a user's code uses it to authorize or reject the user for a given route.\n\nAdditionally if an authenticated user it adds the following properties:\n\n* `_token` \u0026mdash; the original JWT.\n* `setAuthCookie(ctx, options)` \u0026mdash; a function, which when called with `ctx` argument sets a cookie specified by `authCookie` (see below) to `_token`.\n  The optional `options` argument is an object compatible with [options for cookie.set()](https://github.com/pillarjs/cookies#cookiesset-name--value---options--).\n  By default the cookie is set with following options:\n    * `expires` \u0026mdash; an expiration time of a JWT.\n    * `domain` \u0026mdash; a value of `ctx.host`.\n    * `overwrite` \u0026mdash; `true`.\n  `options` will overwrite/augment those values.\n\n`getUser(options [, pools])` takes `options`, which is an object with the following properties:\n\n* `region` \u0026mdash; **required** string, which specifies an AWS region, such as `'us-east-1'`. Default: **none**.\n* `userPoolId` \u0026mdash; **required** string, which specifies a user pool ID, such as `'us-east-1_MY_USER_POOL'`. Default: **none**.\n* `authHeader` \u0026mdash; optional string. Default: `'Authorization'`. It specifies an HTTP request header name. Its value should be a JWT supplied by AWS Cognito (`id_token` or `access_token`).\n* `authCookie` \u0026mdash; optional string. Default: `'auth'`. It specifies an HTTP request cookie name. Its value should be a JWT supplied by AWS Cognito (`id_token` or `access_token`).\n* `source` \u0026mdash; optional function. Default: reads `authHeader` header and returns it, if it is not falsy, otherwise reads `authCookie` cookie and returns it, if it is not false, otherwise returns `null`.\n  If it is a function, it is called with `ctx` argument, and can inspect a request to produce a JWT token as a string.\n    * Examples:\n      ```js\n      const getToken1 = ctx =\u003e ctx.headers['x-auth-header'];\n      const getToken2 = ctx =\u003e ctx.cookies.get('auth-token');\n      ```\n* `setAuthCookieOptions` \u0026mdash; optional object compatible with [options for cookie.set()](https://github.com/pillarjs/cookies#cookiesset-name--value---options--).\n  If it is `null` (the default), a cookie is not set automatically. Otherwise, it is set every time it is not set or has a different value. When a cookie is set,\n  `setAuthCookieOptions` is used to overwrite/augment the default options described above in `setAuthCookie()`.\n\nOptional `pools`, if specified, should be an object with the following properties or an array of such objects:\n\n* `region` \u0026mdash; **required** string, which specifies an AWS region, such as `'us-east-1'`. Default: **none**.\n* `userPoolId` \u0026mdash; **required** string, which specifies a user pool ID, such as `'us-east-1_MY_USER_POOL'`. Default: **none**.\n\nIf `pools` is specified `region` and `userPoolId` of `options` are ignored. Specifying `pools` is the onl way to supply an array of user pools.\n\nThis function should be used before any other helpers.\n\n## `getUser.stateUserProperty`\n\n*(Since 1.4.4):* This is a property name to hold a user object. It can be a string or a `Symbol`. Default: `'user'`.\n\nUsually it is assigned right after obtaining `getUser()`:\n\n```js\nconst getUser = require('koa-cognito-middleware');\ngetUser.stateUserProperty = 'cognitoUser';\nconst {isAuthenticated, hasScope, hasGroup, isAllowed} = getUser;\n```\n\nAll other helper functions will use this value to inspect the state's user property.\n\n## `getUser.isAuthenticated`\n\nThis is a helper function, which checks if the state's user property is set. If not it rejects a request with 401 (unauthorized).\n\n## `getUser.hasGroup(group)`\n\nThis is a helper function, which checks if the state's user property has `'cognito:groups'` array that includes a given group (as a string).\nIf not it rejects a request with 403 (forbidden) for valid users and 401 (unauthorized) for non-authenticated users.\n\n## `getUser.hasScope(scope)`\n\nThis is a helper function, which checks if the state's user property has `'scope'` string that includes a given scope (as a string).\nIf not it rejects a request with 403 (forbidden) for valid users and 401 (unauthorized) for non-authenticated users.\n\n## `getUser.isAllowed(validator)`\n\nThis is a helper function, which checks runs a validator. If not it rejects a request with 403 (forbidden) for valid users and 401 (unauthorized) for non-authenticated users.\n\n`validator` is an asynchronous function, which is called with three parameters: the original `ctx`, `groups` and `scopes`.\nThe latter two parameters are arrays of strings listing `cognito:groups` and `scope` items respectively.\n`validator` should return a truthy value, if a user is allowed to perform an action, and a falsy value otherwise.\n\n# Versions\n\n- 1.4.7 *Updated dependencies. Fix: scope was used incorrectly. Fix: 401 was reported instead of 403.*\n- 1.4.6 *Updated dependencies.*\n- 1.4.5 *Updated dependencies.*\n- 1.4.4 *Added support for state's user property name. Thx [Mike Vosseller](https://github.com/mpvosseller)!*\n- 1.4.3 *Added support for multiple user pools.*\n- 1.4.2 *More bugfixes.*\n- 1.4.1 *Bugfixes.*\n- 1.4.0 *Added support for an auth cookie.*\n- 1.3.0 *Split off the common functionality to [cognito-toolkit](https://www.npmjs.com/package/cognito-toolkit).*\n- 1.2.0 *Added a utility to lazily retrieve an access token by client ID and a secret.*\n- 1.1.0 *Added a utility to auto-retrieve an access token by client ID and a secret.*\n- 1.0.0 *The initial public release.*\n\n# License\n\n[The 3-Clause BSD License](https://opensource.org/licenses/BSD-3-Clause)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fuhop%2Fkoa-cognito-middleware","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fuhop%2Fkoa-cognito-middleware","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fuhop%2Fkoa-cognito-middleware/lists"}