{"id":13631027,"url":"https://github.com/lelylan/simple-oauth2","last_synced_at":"2025-12-26T19:32:16.930Z","repository":{"id":6496798,"uuid":"7737247","full_name":"lelylan/simple-oauth2","owner":"lelylan","description":"A simple Node.js client library for Oauth2","archived":false,"fork":false,"pushed_at":"2024-12-05T23:43:15.000Z","size":1768,"stargazers_count":1634,"open_issues_count":12,"forks_count":291,"subscribers_count":27,"default_branch":"master","last_synced_at":"2025-04-09T22:44:05.284Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"http://lelylan.github.com/simple-oauth2/","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/lelylan.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","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":"2013-01-21T17:53:23.000Z","updated_at":"2025-03-29T14:21:19.000Z","dependencies_parsed_at":"2024-06-07T23:42:45.045Z","dependency_job_id":"d18ffade-f206-4abb-b51b-6e3ad07f0902","html_url":"https://github.com/lelylan/simple-oauth2","commit_stats":{"total_commits":434,"total_committers":49,"mean_commits":8.857142857142858,"dds":0.3271889400921659,"last_synced_commit":"9dbe7d26353793c8cbdfb3a83d754120ef36ccc1"},"previous_names":[],"tags_count":39,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lelylan%2Fsimple-oauth2","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lelylan%2Fsimple-oauth2/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lelylan%2Fsimple-oauth2/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lelylan%2Fsimple-oauth2/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lelylan","download_url":"https://codeload.github.com/lelylan/simple-oauth2/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248675427,"owners_count":21143768,"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-01T22:02:07.646Z","updated_at":"2025-12-26T19:32:16.852Z","avatar_url":"https://github.com/lelylan.png","language":"JavaScript","funding_links":[],"categories":["JavaScript","Uncategorized"],"sub_categories":["Uncategorized"],"readme":"# Simple OAuth2\n\n[![NPM Package Version](https://img.shields.io/npm/v/simple-oauth2.svg?style=flat-square)](https://www.npmjs.com/package/simple-oauth2)\n[![Build Status](https://github.com/lelylan/simple-oauth2/workflows/Node.js%20CI/badge.svg)](https://github.com/lelylan/simple-oauth2/actions)\n\n[Simple OAuth2](#simple-oauth2) is a Node.js client library for the [OAuth 2.0](http://oauth.net/2/) authorization framework. [OAuth 2.0](http://oauth.net/2/) is the industry-standard protocol for authorization, enabling third-party applications to obtain limited access to an HTTP service, either on behalf of a resource owner or by allowing the third-party application to obtain access on its own behalf.\n\n## Table of Contents\n\n\u003c!-- START doctoc generated TOC please keep comment here to allow auto update --\u003e\n\u003c!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --\u003e\n\n- [Requirements](#requirements)\n- [Usage](#usage)\n  - [Supported Grant Types](#supported-grant-types)\n    - [Authorization Code Grant](#authorization-code-grant)\n    - [Resource Owner Password Credentials Grant](#resource-owner-password-credentials-grant)\n    - [Client Credentials Grant](#client-credentials-grant)\n  - [Access Token](#access-token)\n    - [Refresh an access token](#refresh-an-access-token)\n    - [Revoke an access or refresh token](#revoke-an-access-or-refresh-token)\n  - [Errors](#errors)\n- [Debugging the module](#debugging-the-module)\n- [Contributing](#contributing)\n- [Authors](#authors)\n  - [Contributors](#contributors)\n- [Changelog](#changelog)\n- [License](#license)\n- [Thanks to Open Source](#thanks-to-open-source)\n\n\u003c!-- END doctoc generated TOC please keep comment here to allow auto update --\u003e\n\n## Requirements\n\n| Version                                                                          | Node support        |\n|----------------------------------------------------------------------------------|---------------------|\n| [5.x](https://github.com/lelylan/simple-oauth2/tree/5.x)                         | Node 14.x or higher |\n| [6.x (Development)](https://github.com/lelylan/simple-oauth2/tree/master)        | Node 16.x or higher |\n\nOlder node versions are unsupported.\n\n## Usage\n\nInstall the client library using [npm](http://npmjs.org/):\n\n```bash\nnpm install --save simple-oauth2\n```\n\nWith a minimal configuration, create a client instance of any supported [grant type](#supported-grant-types).\n\n```javascript\nconst config = {\n  client: {\n    id: '\u003cclient-id\u003e',\n    secret: '\u003cclient-secret\u003e'\n  },\n  auth: {\n    tokenHost: 'https://api.oauth.com'\n  }\n};\n\nconst { ClientCredentials, ResourceOwnerPassword, AuthorizationCode } = require('simple-oauth2');\n```\n\nFor a complete reference of configuration options, see the [API Options](./API.md#options)\n\n### Supported Grant Types\n\nDepending on your use-case, any of the following supported grant types may be useful:\n\n#### Authorization Code Grant\n\nThe [Authorization Code](https://oauth.net/2/grant-types/authorization-code/) grant type is used by confidential and public clients to exchange an authorization code for an access token. After the user returns to the client via the redirect URL, the application will get the authorization code from the URL and use it to request an access token.\n\n```javascript\nasync function run() {\n  const client = new AuthorizationCode(config);\n\n  const authorizationUri = client.authorizeURL({\n    redirect_uri: 'http://localhost:3000/callback',\n    scope: '\u003cscope\u003e',\n    state: '\u003cstate\u003e',\n    \n    customParam: 'foo', // non-standard oauth params may be passed as well\n  });\n\n  // Redirect example using Express (see http://expressjs.com/api.html#res.redirect)\n  res.redirect(authorizationUri);\n\n  const tokenParams = {\n    code: '\u003ccode\u003e',\n    redirect_uri: 'http://localhost:3000/callback',\n    scope: '\u003cscope\u003e',\n  };\n\n  try {\n    const accessToken = await client.getToken(tokenParams);\n  } catch (error) {\n    console.log('Access Token Error', error.message);\n  }\n}\n\nrun();\n```\n\nSee the [API reference](./API.md#new-authorizationcodeoptions) for a complete reference of available options or any of our available examples at the [example folder](./example).\n\n#### Resource Owner Password Credentials Grant\n\nThe [Resource Owner Password Credentials](https://oauth.net/2/grant-types/password/) grant type is a way to exchange a user's credentials for an access token. Because the client application has to collect the user's password and send it to the authorization server, it is not recommended that this grant be used at all anymore.\n\n```javascript\nasync function run() {\n  const client = new ResourceOwnerPassword(config);\n\n  const tokenParams = {\n    username: 'username',\n    password: 'password',\n    scope: '\u003cscope\u003e',\n  };\n\n  try {\n    const accessToken = await client.getToken(tokenParams);\n  } catch (error) {\n    console.log('Access Token Error', error.message);\n  }\n}\n\nrun();\n```\n\nSee the [API reference](./API.md#new-resourceownerpasswordoptions) for a complete reference of available options.\n\n#### Client Credentials Grant\n\nThe [Client Credentials](https://oauth.net/2/grant-types/client-credentials/) grant type is used by clients to obtain an access token outside of the context of a user. This is typically used by clients to access resources about themselves rather than to access a user's resources.\n\n```javascript\nasync function run() {\n  const client = new ClientCredentials(config);\n\n  const tokenParams = {\n    scope: '\u003cscope\u003e',\n  };\n\n  try {\n    const accessToken = await client.getToken(tokenParams);\n  } catch (error) {\n    console.log('Access Token error', error.message);\n  }\n}\n\nrun();\n```\n\nSee the [API reference](./API.md#new-clientcredentialsoptions) for a complete reference of available options.\n\n### Access Token\n\nOn completion of any [supported grant type](#supported-grant-types), an access token will be obtained. A list of supported operations can be found below.\n\n#### Refresh an access token\n\nOn long-lived applications, it is often necessary to refresh access tokens. In such scenarios, the access token is usually persisted in an external database by first serializing it.\n\n\n```javascript\nasync function run() {\n  const accessTokenJSONString = JSON.stringify(accessToken);\n\n  await persistAccessTokenJSON(accessTokenJSONString);\n}\n\nrun();\n```\n\nBy the time we need to refresh the persistent access token, we can get back an [AccessToken](./API.md#accesstoken) instance by using the client's [.createToken](./API.md#createtokentoken--accesstoken) method.\n\n```javascript\nasync function run() {\n  const accessTokenJSONString = await getPersistedAccessTokenJSON();\n\n  let accessToken = client.createToken(JSON.parse(accessTokenJSONString));\n}\n\nrun();\n```\n\nOnce we have determined the access token needs refreshing with the [.expired()](./API.md#expiredexpirationwindowseconds--boolean) method, we can finally refresh it with a [.refresh()](./API.md#await-refreshparams--accesstoken) method call.\n\n```javascript\nasync function run() {\n  if (accessToken.expired()) {\n    try {\n      const refreshParams = {\n        scope: '\u003cscope\u003e',\n      };\n\n      accessToken = await accessToken.refresh(refreshParams);\n    } catch (error) {\n      console.log('Error refreshing access token: ', error.message);\n    }\n  }\n}\n\nrun();\n```\n\nThe [.expired()](./API.md##expiredexpirationwindowseconds--boolean) helper is useful for knowing when a token has definitively expired. However, there is a common race condition when tokens are near expiring. If an OAuth 2.0 token is issued with a `expires_in` property (as opposed to an `expires_at` property), there can be discrepancies between the time the OAuth 2.0 server issues the access token and when it is received.\n\nThese come down to factors such as network and processing latency and can be worked around by preemptively refreshing the access token:\n\n```javascript\nasync function run() {\n  const EXPIRATION_WINDOW_IN_SECONDS = 300; // Window of time before the actual expiration to refresh the token\n\n  if (accessToken.expired(EXPIRATION_WINDOW_IN_SECONDS)) {\n    try {\n      accessToken = await accessToken.refresh();\n    } catch (error) {\n      console.log('Error refreshing access token: ', error.message);\n    }\n  }\n}\n\nrun();\n```\n\n**Warning:** Tokens obtained with the Client Credentials grant may not be refreshed. Fetch a new token when it's expired.\n\nSee the [API reference](./API.md#accesstoken) for a complete reference of available options.\n\n#### Revoke an access or refresh token\n\nWhen you've done with the token or you want to log out, you can revoke both access and refresh tokens.\n\n```javascript\nasync function run() {\n  try {\n    await accessToken.revoke('access_token');\n    await accessToken.revoke('refresh_token');\n  } catch (error) {\n    console.log('Error revoking token: ', error.message);\n  }\n}\n\nrun();\n```\n\nAs a convenience method, you can also revoke both tokens in a single call:\n\n```javascript\nasync function run() {\n  try {\n    // Revokes both tokens, refresh token is only revoked if the access_token is properly revoked\n    await accessToken.revokeAll();\n  } catch (error) {\n    console.log('Error revoking token: ', error.message);\n  }\n}\n\nrun();\n```\n\nSee the [API reference](./API.md#accesstoken) for a complete reference of available options.\n\n### Errors\n\nWhenever a client or server error is produced, a [boom](https://github.com/hapijs/boom) error is thrown by the library. As such any [boom error property](https://hapi.dev/module/boom/api) is available, but the exact information may vary according to the type of error.\n\n```javascript\nasync function run() {\n  const client = new ClientCredentials(config);\n\n  try {\n    await client.getToken();\n  } catch(error) {\n    console.log(error.output);\n  }\n}\n\nrun();\n\n// { statusCode: 401,\n//   payload:\n//    { statusCode: 401,\n//      error: 'Unauthorized',\n//      message: 'Response Error: 401 Unauthorized' },\n//   headers: {} }\n```\n\n## Debugging the module\nThis module uses the [debug](https://github.com/visionmedia/debug) module to help on error diagnosis. Use the following environment variable to help in your debug journey:\n\n```\nDEBUG=*simple-oauth2*\n```\n\n## Contributing\n\nSee [CONTRIBUTING](./CONTRIBUTING.md)\n\n## Authors\n\n[Andrea Reginato](http://twitter.com/lelylan)\n\n### Contributors\n\nSpecial thanks to the following people for submitting patches.\n\n* [Jonathan Samines](https://github.com/jonathansamines)\n\n## Changelog\n\nSee [CHANGELOG](./CHANGELOG.md)\n\n## License\n\nSimple OAuth 2.0 is licensed under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)\n\n## Thanks to Open Source\n\nSimple OAuth 2.0 come to life thanks to the work I've made in Lelylan, an open source microservices architecture for the Internet of Things. If this project helped you in any way, think about giving us a \u003ca href=\"https://github.com/lelylan/lelylan\"\u003estar on GitHub\u003c/a\u003e.\n\n\u003ca href=\"https://github.com/lelylan/lelylan\"\u003e\n\u003cimg src=\"https://raw.githubusercontent.com/lelylan/lelylan/master/public/logo-lelylan.png\" data-canonical-src=\"https://raw.githubusercontent.com/lelylan/lelylan/master/public/logo-lelylan.png\" width=\"300\"/\u003e\u003c/a\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flelylan%2Fsimple-oauth2","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flelylan%2Fsimple-oauth2","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flelylan%2Fsimple-oauth2/lists"}