{"id":14385085,"url":"https://github.com/extrabacon/google-oauth-jwt","last_synced_at":"2025-04-04T22:07:00.616Z","repository":{"id":8184636,"uuid":"9611292","full_name":"extrabacon/google-oauth-jwt","owner":"extrabacon","description":"Node.js implementation of Google OAuth 2.0 for server-to-server interactions, allowing secure use of Google APIs without URL redirects and authorization prompts.","archived":false,"fork":false,"pushed_at":"2023-02-20T15:57:28.000Z","size":61,"stargazers_count":191,"open_issues_count":12,"forks_count":24,"subscribers_count":7,"default_branch":"master","last_synced_at":"2024-10-29T11:12:21.154Z","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/extrabacon.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG","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}},"created_at":"2013-04-22T23:41:31.000Z","updated_at":"2023-08-20T16:44:43.000Z","dependencies_parsed_at":"2024-01-14T20:29:48.257Z","dependency_job_id":null,"html_url":"https://github.com/extrabacon/google-oauth-jwt","commit_stats":{"total_commits":50,"total_committers":6,"mean_commits":8.333333333333334,"dds":0.12,"last_synced_commit":"9032bb3e272e7ae3f227f822dc0e708cc0c89a62"},"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/extrabacon%2Fgoogle-oauth-jwt","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/extrabacon%2Fgoogle-oauth-jwt/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/extrabacon%2Fgoogle-oauth-jwt/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/extrabacon%2Fgoogle-oauth-jwt/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/extrabacon","download_url":"https://codeload.github.com/extrabacon/google-oauth-jwt/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247256112,"owners_count":20909240,"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-28T18:01:56.263Z","updated_at":"2025-04-04T22:07:00.597Z","avatar_url":"https://github.com/extrabacon.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"# google-oauth-jwt\n\nGoogle OAuth 2.0 authentication for server-to-server applications with Node.js.\n\nThis library generates [JWT](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html) tokens to establish\nidentity for an API, without an end-user being involved. This is the preferred scenario for server-side communications.\nIt can be used to interact with Google APIs requiring access to user data (such as Google Drive, Calendar, etc.) for\nwhich URL-based callbacks and user authorization prompts are not appropriate.\n\nTokens are generated for a service account, which is created from the Google API console. Service accounts must also\nbe granted access to resources, using traditional assignation of permissions using the unique service account email\naddress.\n\nThe authentication process is implemented following the specifications found\n[here](https://developers.google.com/accounts/docs/OAuth2ServiceAccount).\n\nThis package also integrates with [request](https://github.com/mikeal/request) to seamlessly query Google RESTful APIs,\nwhich is optional. Integration with [request](https://github.com/mikeal/request) provides automatic requesting of\ntokens, as well as built-in token caching.\n\n## Documentation\n\n### Installation\n```bash\nnpm install google-oauth-jwt\n```\n\n### How does it work?\n\nWhen using Google APIs from the server (or any non-browser based application), authentication is performed through a\nService Account, which is a special account representing your application. This account has a unique email address that\ncan be used to grant permissions to. If a user wants to give access to his Google Drive to your application, he must share the files or folders with the Service Account using the supplied email address.\n\nNow that the Service Account has permission to some user resources, the application can query the API with OAuth2.\nWhen using OAuth2, authentication is performed using a token that has been obtained first by submitting a JSON Web\nToken (JWT). The JWT identifies the user as well as the scope of the data he wants access to. The JWT is also signed\nwith a cryptographic key to prevent tampering. Google generates the key and keeps only the public key for validation.\nYou must keep the private key secure with your application so that you can sign the JWT in order to guarantee its authenticity.\n\nThe application requests a token that can be used for authentication in exchange with a valid JWT. The resulting token\ncan then be used for multiple API calls, until it expires and a new token must be obtained by submitting another JWT.\n\n### Creating a Service Account using the Google Developers Console\n\n1. From the [Google Developers Console](https://cloud.google.com/console), select your project or create a new one.\n\n2. Under \"APIs \u0026 auth\", click \"Credentials\".\n\n3. Under \"OAuth\", click the \"Create new client ID\" button.\n\n4. Select \"Service account\" as the application type and click \"Create Client ID\".\n\n5. The key for your new service account should prompt for download automatically. Note that your key is protected with a password.\n   IMPORTANT: keep a secure copy of the key, as Google keeps only the public key.\n\n6. Convert the downloaded key to PEM, so we can use it from the Node [crypto](http://nodejs.org/api/crypto.html) module.\n\n   To do this, run the following in Terminal:\n   ```bash\n   openssl pkcs12 -in downloaded-key-file.p12 -out your-key-file.pem -nodes\n   ```\n\n   You will be asked for the password you received during step 5.\n\nThat's it! You now have a service account with an email address and a key that you can use from your Node application.\n\n### Granting access to resources to be requested through an API\n\nIn order to query resources using the API, access must be granted to the Service Account. Each Google application that\nhas security settings must be configured individually. Access is granted by assigning permissions to the service\naccount, using its email address found in the API console.\n\nFor example, in order to list files in Google Drive, folders and files must be shared with the service account email\naddress. Likewise, to access a calendar, the calendar must be shared with the service account.\n\n### Querying Google APIs with \"request\"\n\nIn this example, we use a modified instance of [request](https://github.com/mikeal/request) to query the\nGoogle Drive API. [request](https://github.com/mikeal/request) is a full-featured HTTP client which can be extended with Google OAuth2 capabilities by using the `requestWithJWT` method. The modified module will request and cache tokens automatically when supplied with a `jwt` setting in the options.\n\n```javascript\n// obtain a JWT-enabled version of request\nvar request = require('google-oauth-jwt').requestWithJWT();\n\nrequest({\n  url: 'https://www.googleapis.com/drive/v2/files',\n  jwt: {\n    // use the email address of the service account, as seen in the API console\n    email: 'my-service-account@developer.gserviceaccount.com',\n    // use the PEM file we generated from the downloaded key\n    keyFile: 'my-service-account-key.pem',\n    // specify the scopes you wish to access - each application has different scopes\n    scopes: ['https://www.googleapis.com/auth/drive.readonly']\n  }\n}, function (err, res, body) {\n\tconsole.log(JSON.parse(body));\n});\n```\n\nNote that the `options` object includes a `jwt` object we use to configure the JWT generation. The token will then\nautomatically be requested and inserted in the authorization header. It will also be cached and reused for subsequent calls using the same service account and scopes.\n\nIf you want to use a specific version of `request`, simply pass it to the the `requestWithJWT` method as such:\n\n```javascript\n// my version of request\nvar request = require('request');\n// my modified version of request\nrequest = require('google-oauth-jwt').requestWithJWT(request);\n```\n\n### Requesting the token manually\n\nIf you wish to simply request the token for use with a Google API, use the `authenticate` method.\n\n```javascript\nvar googleAuth = require('google-oauth-jwt');\n\ngoogleAuth.authenticate({\n  // use the email address of the service account, as seen in the API console\n  email: 'my-service-account@developer.gserviceaccount.com',\n  // use the PEM file we generated from the downloaded key\n  keyFile: 'my-service-account-key.pem',\n  // specify the scopes you wish to access\n  scopes: ['https://www.googleapis.com/auth/drive.readonly']\n}, function (err, token) {\n  console.log(token);\n});\n```\n\nIf you want to use the built-in token cache, use the `TokenCache` class. Tokens are cached using the email address and\nthe scopes as the key.\n\n```javascript\nvar TokenCache = require('google-oauth-jwt').TokenCache,\n    tokens = new TokenCache();\n\ntokens.get({\n  // use the email address of the service account, as seen in the API console\n  email: 'my-service-account@developer.gserviceaccount.com',\n  // use the PEM file we generated from the downloaded key\n  keyFile: 'my-service-account-key.pem',\n  // specify the scopes you wish to access\n  scopes: ['https://www.googleapis.com/auth/drive.readonly']\n}, function (err, token) {\n  console.log(token);\n});\n```\n\nUsing `TokenCache` will request only one token for multiple concurrent requests to `get`. A new token request will\nautomatically be issued if the token is expired.\n\n### Encoding the JWT manually\n\nIt is also possible to encode the JWT manually using the `encodeJWT` method.\n\n```javascript\nvar googleAuth = require('google-oauth-jwt');\n\ngoogleAuth.encodeJWT({\n  // use the email address of the service account, as seen in the API console\n  email: 'my-service-account@developer.gserviceaccount.com',\n  // use the PEM file we generated from the downloaded key\n  keyFile: 'my-service-account-key.pem',\n  // specify the scopes you which to access\n  scopes: ['https://www.googleapis.com/auth/drive.readonly']\n}, function (err, jwt) {\n  console.log(jwt);\n});\n```\n\n### Specifying JWT generation options\n\nThe following options can be specified in order to generate the JWT used for authentication:\n\n```javascript\nvar options = {\n\n  // the email address of the service account (required)\n  // this information is obtained via the API console\n  email: 'my-service-account@developer.gserviceaccount.com',\n\n  // an array of scopes uris to request access to (required)\n  // different scopes are available for each application, refer to the app documentation\n  // scopes are limitations applied to the API access\n  scopes: [...],\n\n  // the cryptographic key as a string, can be the contents of the PEM file\n  // the key will be used to sign the JWT and validated by Google OAuth\n  key: 'KEY_CONTENTS',\n\n  // the path to the PEM file to use for the cryptographic key (ignored if 'key' is also defined)\n  // the key will be used to sign the JWT and validated by Google OAuth\n  keyFile: 'path/to/key.pem',\n\n  // the duration of the requested token in milliseconds (optional)\n  // default is 1 hour (60 * 60 * 1000), which is the maximum allowed by Google\n  expiration: 3600000,\n\n  // if access is being granted on behalf of someone else, specifies who is impersonating the service account\n  delegationEmail: 'email_address@mycompany.com'\n\n};\n```\n\nFor more information:\n[https://developers.google.com/accounts/docs/OAuth2ServiceAccount#formingclaimset](https://developers.google.com/accounts/docs/OAuth2ServiceAccount#formingclaimset)\n\nOptions are used to encode the JWT that will be sent to Google OAuth servers in order to issue a token that can then be\nused for authentification to Google APIs. The same options are used for `authenticate`, `TokenCache.get` or the `jwt`\nsetting passed to `request` options.\n\n## Running the tests\n\nRunning the unit tests for `google-oauth-jwt` requires a valid Service Account, its encryption key and a URL to test.\n\nTo launch the tests, first configure your account in \"test/jwt-settings.json\" using the sample file. Make sure your\ntest URL also matches with the requested scopes. The tests do not make any assumption on the results from the API, so\nyou can use any OAuth2 enabled API.\n\nFor example, to run the tests by listing Google Drive files, you can use the following configuration:\n\n```javascript\n{\n  \"email\": \"my-account@developer.gserviceaccount.com\",\n  \"scopes\": [\"https://www.googleapis.com/auth/drive.readonly\"],\n  \"keyFile\": \"./test/key.pem\",\n  \"test_url\": \"https://www.googleapis.com/drive/v2/files\"\n}\n```\n\nTo run the tests:\n\n```bash\nnpm test\n```\n\nor\n\n```bash\nmocha -t 5000\n```\n\nThe 5 seconds timeout is required since some tests make multiple calls to the API. If you get timeout exceeded errors,\nyou can bump this value since not all Google APIs may respond with the same timings.\n\n## Debugging\n\nTo turn on debugging, add \"google-oauth-jwt\" to your `DEBUG` variable. Debugging events include JWT generation, token\nrequests to the OAuth server and token expirations through `TokenCache`.\n\nFor example, to turn on debugging while running the unit tests, use this:\n\n```bash\nDEBUG=google-oauth-jwt mocha -t 5000\n```\n\n## Compatibility\n\n+ Tested with Node 0.10, 0.12, 4.2, 5.5\n\n## License\n\nThe MIT License (MIT)\n\nCopyright (c) 2013, Nicolas Mercier\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fextrabacon%2Fgoogle-oauth-jwt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fextrabacon%2Fgoogle-oauth-jwt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fextrabacon%2Fgoogle-oauth-jwt/lists"}