1 <img src="https://avatars0.githubusercontent.com/u/1342004?v=3&s=96" alt="Google Inc. logo" title="Google" align="right" height="96" width="96"/>
5 [![npm version][npmimg]][npm]
6 [![codecov][codecov-image]][codecov-url]
7 [![Dependencies][david-dm-img]][david-dm]
8 [![Known Vulnerabilities][snyk-image]][snyk-url]
10 This is Google's officially supported [node.js][node] client library for using OAuth 2.0 authorization and authentication with Google APIs.
13 This library is distributed on `npm`. To add it as a dependency, run the following command:
16 $ npm install google-auth-library
19 ## Ways to authenticate
20 This library provides a variety of ways to authenticate to your Google services.
21 - [Application Default Credentials](#choosing-the-correct-credential-type-automatically) - Use Application Default Credentials when you use a single identity for all users in your application. Especially useful for applications running on Google Cloud.
22 - [OAuth 2](#oauth2) - Use OAuth2 when you need to perform actions on behalf of the end user.
23 - [JSON Web Tokens](#json-web-tokens) - Use JWT when you are using a single identity for all users. Especially useful for server->server or server->API communication.
24 - [Google Compute](#compute) - Directly use a service account on Google Cloud Platform. Useful for server->server or server->API communication.
26 ## Application Default Credentials
27 This library provides an implementation of [Application Default Credentials][] for Node.js. The [Application Default Credentials][] provide a simple way to get authorization credentials for use in calling Google APIs.
29 They are best suited for cases when the call needs to have the same identity and authorization level for the application independent of the user. This is the recommended approach to authorize calls to Cloud APIs, particularly when you're building an application that uses Google Cloud Platform.
31 #### Download your Service Account Credentials JSON file
33 To use Application Default Credentials, You first need to download a set of JSON credentials for your project. Go to **APIs & Auth** > **Credentials** in the [Google Developers Console][devconsole] and select **Service account** from the **Add credentials** dropdown.
35 > This file is your *only copy* of these credentials. It should never be
36 > committed with your source code, and should be stored securely.
38 Once downloaded, store the path to this file in the `GOOGLE_APPLICATION_CREDENTIALS` environment variable.
40 #### Enable the API you want to use
42 Before making your API call, you must be sure the API you're calling has been enabled. Go to **APIs & Auth** > **APIs** in the [Google Developers Console][devconsole] and enable the APIs you'd like to call. For the example below, you must enable the `DNS API`.
45 #### Choosing the correct credential type automatically
47 Rather than manually creating an OAuth2 client, JWT client, or Compute client, the auth library can create the correct credential type for you, depending upon the environment your code is running under.
49 For example, a JWT auth client will be created when your code is running on your local developer machine, and a Compute client will be created when the same code is running on Google Cloud Platform. If you need a specific set of scopes, you can pass those in the form of a string or an array into the `auth.getClient` method.
51 The code below shows how to retrieve a default credential type, depending upon the runtime environment.
54 const {auth} = require('google-auth-library');
57 * Instead of specifying the type of client you'd like to use (JWT, OAuth2, etc)
58 * this library will automatically choose the right client based on the environment.
60 async function main() {
61 const client = await auth.getClient({
62 scopes: 'https://www.googleapis.com/auth/cloud-platform'
64 const projectId = await auth.getProjectId();
65 const url = `https://www.googleapis.com/dns/v1/projects/${projectId}`;
66 const res = await client.request({ url });
67 console.log(res.data);
70 main().catch(console.error);
75 This library comes with an [OAuth2][oauth] client that allows you to retrieve an access token and refreshes the token and retry the request seamlessly if you also provide an `expiry_date` and the token is expired. The basics of Google's OAuth2 implementation is explained on [Google Authorization and Authentication documentation][authdocs].
77 In the following examples, you may need a `CLIENT_ID`, `CLIENT_SECRET` and `REDIRECT_URL`. You can find these pieces of information by going to the [Developer Console][devconsole], clicking your project > APIs & auth > credentials.
79 For more information about OAuth2 and how it works, [see here][oauth].
81 #### A complete OAuth2 example
83 Let's take a look at a complete example.
86 const {OAuth2Client} = require('google-auth-library');
87 const http = require('http');
88 const url = require('url');
89 const opn = require('opn');
90 const destroyer = require('server-destroy');
92 // Download your OAuth2 configuration from the Google
93 const keys = require('./oauth2.keys.json');
96 * Start by acquiring a pre-authenticated oAuth2 client.
98 async function main() {
99 const oAuth2Client = await getAuthenticatedClient();
100 // Make a simple request to the People API using our pre-authenticated client. The `request()` method
101 // takes an GaxiosOptions object. Visit https://github.com/JustinBeckwith/gaxios.
102 const url = 'https://people.googleapis.com/v1/people/me?personFields=names';
103 const res = await oAuth2Client.request({url});
104 console.log(res.data);
106 // After acquiring an access_token, you may want to check on the audience, expiration,
107 // or original scopes requested. You can do that with the `getTokenInfo` method.
108 const tokenInfo = await oAuth2Client.getTokenInfo(
109 oAuth2Client.credentials.access_token
111 console.log(tokenInfo);
115 * Create a new OAuth2Client, and go through the OAuth2 content
116 * workflow. Return the full client to the callback.
118 function getAuthenticatedClient() {
119 return new Promise((resolve, reject) => {
120 // create an oAuth client to authorize the API call. Secrets are kept in a `keys.json` file,
121 // which should be downloaded from the Google Developers Console.
122 const oAuth2Client = new OAuth2Client(
124 keys.web.client_secret,
125 keys.web.redirect_uris[0]
128 // Generate the url that will be used for the consent dialog.
129 const authorizeUrl = oAuth2Client.generateAuthUrl({
130 access_type: 'offline',
131 scope: 'https://www.googleapis.com/auth/userinfo.profile',
134 // Open an http server to accept the oauth callback. In this simple example, the
135 // only request to our webserver is to /oauth2callback?code=<code>
137 .createServer(async (req, res) => {
139 if (req.url.indexOf('/oauth2callback') > -1) {
140 // acquire the code from the querystring, and close the web server.
141 const qs = new url.URL(req.url, 'http://localhost:3000')
143 const code = qs.get('code');
144 console.log(`Code is ${code}`);
145 res.end('Authentication successful! Please return to the console.');
148 // Now that we have the code, use that to acquire tokens.
149 const r = await oAuth2Client.getToken(code);
150 // Make sure to set the credentials on the OAuth2 client.
151 oAuth2Client.setCredentials(r.tokens);
152 console.info('Tokens acquired.');
153 resolve(oAuth2Client);
159 .listen(3000, () => {
160 // open the browser to the authorize url to start the workflow
161 opn(authorizeUrl, {wait: false}).then(cp => cp.unref());
167 main().catch(console.error);
170 #### Handling token events
171 This library will automatically obtain an `access_token`, and automatically refresh the `access_token` if a `refresh_token` is present. The `refresh_token` is only returned on the [first authorization](https://github.com/googleapis/google-api-nodejs-client/issues/750#issuecomment-304521450), so if you want to make sure you store it safely. An easy way to make sure you always store the most recent tokens is to use the `tokens` event:
174 const client = await auth.getClient();
176 client.on('tokens', (tokens) => {
177 if (tokens.refresh_token) {
178 // store the refresh_token in my database!
179 console.log(tokens.refresh_token);
181 console.log(tokens.access_token);
184 const url = `https://www.googleapis.com/dns/v1/projects/${projectId}`;
185 const res = await client.request({ url });
186 // The `tokens` event would now be raised if this was the first request
189 #### Retrieve access token
190 With the code returned, you can ask for an access token as shown below:
193 const tokens = await oauth2Client.getToken(code);
194 // Now tokens contains an access_token and an optional refresh_token. Save them.
195 oauth2Client.setCredentials(tokens);
198 #### Obtaining a new Refresh Token
199 If you need to obtain a new `refresh_token`, ensure the call to `generateAuthUrl` sets the `access_type` to `offline`. The refresh token will only be returned for the first authorization by the user. To force consent, set the `prompt` property to `consent`:
202 // Generate the url that will be used for the consent dialog.
203 const authorizeUrl = oAuth2Client.generateAuthUrl({
204 // To get a refresh token, you MUST set access_type to `offline`.
205 access_type: 'offline',
206 // set the appropriate scopes
207 scope: 'https://www.googleapis.com/auth/userinfo.profile',
208 // A refresh token is only returned the first time the user
209 // consents to providing access. For illustration purposes,
210 // setting the prompt to 'consent' will force this consent
211 // every time, forcing a refresh_token to be returned.
216 #### Checking `access_token` information
217 After obtaining and storing an `access_token`, at a later time you may want to go check the expiration date,
218 original scopes, or audience for the token. To get the token info, you can use the `getTokenInfo` method:
221 // after acquiring an oAuth2Client...
222 const tokenInfo = await oAuth2Client.getTokenInfo('my-access-token');
224 // take a look at the scopes originally provisioned for the access token
225 console.log(tokenInfo.scopes);
228 This method will throw if the token is invalid.
230 #### OAuth2 with Installed Apps (Electron)
231 If you're authenticating with OAuth2 from an installed application (like Electron), you may not want to embed your `client_secret` inside of the application sources. To work around this restriction, you can choose the `iOS` application type when creating your OAuth2 credentials in the [Google Developers console][devconsole]:
233 ![application type][apptype]
235 If using the `iOS` type, when creating the OAuth2 client you won't need to pass a `client_secret` into the constructor:
237 const oAuth2Client = new OAuth2Client({
238 clientId: <your_client_id>,
239 redirectUri: <your_redirect_uri>
244 The Google Developers Console provides a `.json` file that you can use to configure a JWT auth client and authenticate your requests, for example when using a service account.
247 const {JWT} = require('google-auth-library');
248 const keys = require('./jwt.keys.json');
250 async function main() {
251 const client = new JWT(
255 ['https://www.googleapis.com/auth/cloud-platform'],
257 const url = `https://www.googleapis.com/dns/v1/projects/${keys.project_id}`;
258 const res = await client.request({url});
259 console.log(res.data);
262 main().catch(console.error);
265 The parameters for the JWT auth client including how to use it with a `.pem` file are explained in [samples/jwt.js](https://github.com/googleapis/google-auth-library-nodejs/blob/master/samples/jwt.js).
267 #### Loading credentials from environment variables
268 Instead of loading credentials from a key file, you can also provide them using an environment variable and the `GoogleAuth.fromJSON()` method. This is particularly convenient for systems that deploy directly from source control (Heroku, App Engine, etc).
270 Start by exporting your credentials:
274 "type": "service_account",
275 "project_id": "your-project-id",
276 "private_key_id": "your-private-key-id",
277 "private_key": "your-private-key",
278 "client_email": "your-client-email",
279 "client_id": "your-client-id",
280 "auth_uri": "https://accounts.google.com/o/oauth2/auth",
281 "token_uri": "https://accounts.google.com/o/oauth2/token",
282 "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
283 "client_x509_cert_url": "your-cert-url"
286 Now you can create a new client from the credentials:
289 const {auth} = require('google-auth-library');
291 // load the environment variable with our keys
292 const keysEnvVar = process.env['CREDS'];
294 throw new Error('The $CREDS environment variable was not found!');
296 const keys = JSON.parse(keysEnvVar);
298 async function main() {
299 // load the JWT or UserRefreshClient from the keys
300 const client = auth.fromJSON(keys);
301 client.scopes = ['https://www.googleapis.com/auth/cloud-platform'];
302 const url = `https://www.googleapis.com/dns/v1/projects/${keys.project_id}`;
303 const res = await client.request({url});
304 console.log(res.data);
307 main().catch(console.error);
311 You can set the `HTTPS_PROXY` or `https_proxy` environment variables to proxy HTTPS requests. When `HTTPS_PROXY` or `https_proxy` are set, they will be used to proxy SSL requests that do not have an explicit proxy configuration option present.
314 If your application is running on Google Cloud Platform, you can authenticate using the default service account or by specifying a specific service account.
316 **Note**: In most cases, you will want to use [Application Default Credentials](#choosing-the-correct-credential-type-automatically). Direct use of the `Compute` class is for very specific scenarios.
319 const {auth, Compute} = require('google-auth-library');
321 async function main() {
322 const client = new Compute({
323 // Specifying the service account email is optional.
324 serviceAccountEmail: 'my-service-account@example.com'
326 const projectId = await auth.getProjectId();
327 const url = `https://www.googleapis.com/dns/v1/projects/${project_id}`;
328 const res = await client.request({url});
329 console.log(res.data);
332 main().catch(console.error);
335 ## Questions/problems?
337 * Ask your development related questions on [Stack Overflow][stackoverflow].
338 * If you've found an bug/issue, please [file it on GitHub][bugs].
342 See [CONTRIBUTING][contributing].
346 This library is licensed under Apache 2.0. Full license text is available in [LICENSE][copying].
348 [Application Default Credentials]: https://cloud.google.com/docs/authentication/getting-started
349 [apptype]: https://user-images.githubusercontent.com/534619/36553844-3f9a863c-17b2-11e8-904a-29f6cd5f807a.png
350 [authdocs]: https://developers.google.com/accounts/docs/OAuth2Login
351 [bugs]: https://github.com/googleapis/google-auth-library-nodejs/issues
352 [codecov-image]: https://codecov.io/gh/googleapis/google-auth-library-nodejs/branch/master/graph/badge.svg
353 [codecov-url]: https://codecov.io/gh/googleapis/google-auth-library-nodejs
354 [contributing]: https://github.com/googleapis/google-auth-library-nodejs/blob/master/CONTRIBUTING.md
355 [copying]: https://github.com/googleapis/google-auth-library-nodejs/tree/master/LICENSE
356 [david-dm-img]: https://david-dm.org/googleapis/google-auth-library-nodejs/status.svg
357 [david-dm]: https://david-dm.org/googleapis/google-auth-library-nodejs
358 [node]: http://nodejs.org/
359 [npmimg]: https://img.shields.io/npm/v/google-auth-library.svg
360 [npm]: https://www.npmjs.org/package/google-auth-library
361 [oauth]: https://developers.google.com/identity/protocols/OAuth2
362 [snyk-image]: https://snyk.io/test/github/googleapis/google-auth-library-nodejs/badge.svg
363 [snyk-url]: https://snyk.io/test/github/googleapis/google-auth-library-nodejs
364 [stackoverflow]: http://stackoverflow.com/questions/tagged/google-auth-library-nodejs
365 [devconsole]: https://console.developer.google.com