{"id":15547291,"url":"https://github.com/uhop/cognito-toolkit","last_synced_at":"2025-04-23T18:23:17.484Z","repository":{"id":52687395,"uuid":"184778101","full_name":"uhop/cognito-toolkit","owner":"uhop","description":"Helpers for AWS Cognito to build web applications with authentication/authorization","archived":false,"fork":false,"pushed_at":"2025-02-17T08:01:02.000Z","size":83,"stargazers_count":5,"open_issues_count":8,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-19T14:18:24.586Z","etag":null,"topics":["aws-cognito","cognito-pools","user-pools"],"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-05-03T15:21:03.000Z","updated_at":"2023-06-06T18:17:42.000Z","dependencies_parsed_at":"2024-06-21T07:11:19.232Z","dependency_job_id":"bf755f3d-7963-4f21-959f-b0b826ad6b7d","html_url":"https://github.com/uhop/cognito-toolkit","commit_stats":{"total_commits":14,"total_committers":2,"mean_commits":7.0,"dds":0.1428571428571429,"last_synced_commit":"65e7117e666fdf5cb7a9aaeafe5e64316167b83b"},"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uhop%2Fcognito-toolkit","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uhop%2Fcognito-toolkit/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uhop%2Fcognito-toolkit/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/uhop%2Fcognito-toolkit/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/uhop","download_url":"https://codeload.github.com/uhop/cognito-toolkit/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250488220,"owners_count":21438742,"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","cognito-pools","user-pools"],"created_at":"2024-10-02T13:08:34.118Z","updated_at":"2025-04-23T18:23:17.457Z","avatar_url":"https://github.com/uhop.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# `cognito-toolkit` [![NPM version][npm-img]][npm-url]\n\n[npm-img]: https://img.shields.io/npm/v/cognito-toolkit.svg\n[npm-url]: https://npmjs.org/package/cognito-toolkit\n\n\nHelpers 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).\nA JWT token (either an id or access token) is validated and returned in a decrypted form.\nSimple helpers are provided to make decisions on accessibility of API endpoints for a given user.\n\n# Examples\n\n```js\nconst makeGetUser = require('cognito-toolkit');\n\n// run getUser() on every request\nconst getUser = makeGetUser({\n  region: 'us-east-1',\n  userPoolId: 'us-east-1_MY_USER_POOL'\n});\n\n// ...somewhere in our endpoint we have a context variable: ctx\n\nconst authHeader = ctx.headers.authorization;\nconst authCookie = ctx.cookies.get('auth');\n\nconst user = getUser(authHeader || authCookie);\n\nif (user) {\n  console.log('Our user:\\r\\n' + JSON.stringify(user, null, 2));\n} else {\n  console.log('User was not authenticated.');\n}\n```\n\n# How to install\n\n```txt\nnpm install --save cognito-toolkit\n# yarn add cognito-toolkit\n```\n\n# Documentation\n\nAll provided functions are explained below. See the examples above for usage patterns.\n\n## `makeGetUser(options)`\n\nThis is the main function directly returned from the main module. It returns an asynchronous function, which is used to decode a user.\n\nIt takes one argument `options`, which is 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\nThe returned function takes a token as a string (possible sources are a header or a cookie) and returns a decoded JWT token or `null` (cannot positively authenticate).\n\n## Utilities: `utils/lazyAccessToken`\n\nIt is a helper to retrieve an access token lazily on demand.\n\n### `setCredentials(url, clientId, secret)`\n\nThis synchronous function sets credentials for future authentications. It takes a URL (usually in the form of *Cognito user pool DNS*`/oauth2/token`),\nan app client ID and an app client secret (all as strings) and retrieves an access token\n(see [TOKEN Endpoint](https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html), the part on `client_credentials`).\n\n### `getToken()`\n\nThis synchronous function returns the current token whatever it is. If it was not retrieved yet, it will return `null`.\n\n### `authorize()`\n\nThis **asynchronous** function checks if there is an unexpired token and retrieves it, if required. It uses credentials set by `setCredentials()` (see above).\nAs a result it returns a token or `null`, if credentials were not set. After running this function the current token can be obtained with `getToken()` (see above).\n\nExamples:\n\n```js\nconst {setCredentials, authorize} = require('cognito-toolkit/utils/lazyAccessToken');\n\n// ...\n\nsetCredentials(\n  'https://auth.my-custom-domain/oauth2/token',\n  process.env.AUTH_CLIENT_ID,\n  process.env.AUTH_CLIENT_SECRET\n);\n\n// ...\n\nconst doIt = async () =\u003e {\n  // every time we call it, it retrieves a token from a server\n  const token = await authorize();\n  // use the token immediately: it can be changed next time you need it\n  const options = {\n    protocol: 'https',\n    hostname: 'api.my-custom-domain.com',\n    path: '/items',\n    method: 'GET',\n    headers: {\n      Accept: 'application/json',\n      Authorization: token.access_token\n    }\n  };\n  // do a call ...\n};\n```\n\n## Utilities: `utils/renewableAccessToken`\n\nIt is a helper to retrieve an access token on demand, then renew it by a timer automatically.\n\n### `retrieveToken(url, clientId, secret)`\n\nThis **asynchronous** function takes a URL (usually in the form of *Cognito user pool DNS*`/oauth2/token`), an app client ID and an app client secret (all as strings)\nand retrieves an access token (see [TOKEN Endpoint](https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html), the part on `client_credentials`).\n\nWarning: the function always uses `https` protocol, which is a default for Cognito pools.\n\nThe function schedules itself to run when a token is about to expire. The exact algorithm is `expires_in` (defined in the token structure) minus 5 minutes.\nIf the result is negative, it will run in a half of `expires_in` time.\n\nWhile the function resolves its return in a token structure, do not save it because it can be updated over time. Always use `getToken()` function (described below) before using a token.\n\nExample:\n\n```js\nconst {retrieveToken} = require('cognito-toolkit/utils/renewableAccessToken');\n\n// ...\n\nconst doIt = async () =\u003e {\n  // every time we call it, it retrieves a token from a server\n  const token = await retrieveToken(\n    'https://auth.my-custom-domain/oauth2/token',\n    process.env.AUTH_CLIENT_ID,\n    process.env.AUTH_CLIENT_SECRET\n  );\n  // use the token immediately: it can be changed next time you need it\n  const options = {\n    protocol: 'https',\n    hostname: 'api.my-custom-domain.com',\n    path: '/items',\n    method: 'GET',\n    headers: {\n      Accept: 'application/json',\n      Authorization: token.access_token\n    }\n  };\n  // do a call ...\n};\n```\n\n### `getToken()`\n\nThis synchronous function returns the current token whatever it is. If it was not retrieved yet, it will return `null`.\n\nExample:\n\n```js\n// rewriting the previous example\n\nconst {retrieveToken, getToken} = require('cognito-toolkit/utils/renewableAccessToken');\n\nconst authorize = () =\u003e {\n  // this function can be called multiple times\n  // it calls the retrieveToken() only when necessary\n  // and getToken() always returns the fresh token\n  if (!getToken()) {\n    return retrieveToken(\n      'https://auth.my-custom-domain/oauth2/token',\n      process.env.AUTH_CLIENT_ID,\n      process.env.AUTH_CLIENT_SECRET\n    );\n  }\n};\n\n// ...\n\nconst doIt = async () =\u003e {\n  await authorize(); // we can call it many times without taxing the auth system\n  const token = getToken(); // totally safe to get a token like that\n  // like in the previous example ...\n};\n```\n\n# Versions\n\n- 1.0.5 *Updated dependencies.*\n- 1.0.4 *Updated dependencies.*\n- 1.0.3 *Updated dependencies.*\n- 1.0.2 *Updated dependencies.*\n- 1.0.1 *Added support for multiple pools.*\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%2Fcognito-toolkit","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fuhop%2Fcognito-toolkit","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fuhop%2Fcognito-toolkit/lists"}