Built motion from commit 10af8726.|2.6.34
[motion2.git] / legacy-libs / google-auth-library / README.md
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"/>
2
3 # Google Auth Library
4
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]
9
10 This is Google's officially supported [node.js][node] client library for using OAuth 2.0 authorization and authentication with Google APIs.
11
12 ## Installation
13 This library is distributed on `npm`. To add it as a dependency, run the following command:
14
15 ``` sh
16 $ npm install google-auth-library
17 ```
18
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.
25
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.
28
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.
30
31 #### Download your Service Account Credentials JSON file
32
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.
34
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.
37
38 Once downloaded, store the path to this file in the `GOOGLE_APPLICATION_CREDENTIALS` environment variable.
39
40 #### Enable the API you want to use
41
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`.
43
44
45 #### Choosing the correct credential type automatically
46
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.
48
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.
50
51 The code below shows how to retrieve a default credential type, depending upon the runtime environment.
52
53 ```js
54 const {auth} = require('google-auth-library');
55
56 /**
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.
59  */
60 async function main() {
61   const client = await auth.getClient({
62     scopes: 'https://www.googleapis.com/auth/cloud-platform'
63   });
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);
68 }
69
70 main().catch(console.error);
71 ```
72
73 ## OAuth2
74
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].
76
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.
78
79 For more information about OAuth2 and how it works, [see here][oauth].
80
81 #### A complete OAuth2 example
82
83 Let's take a look at a complete example.
84
85 ``` js
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');
91
92 // Download your OAuth2 configuration from the Google
93 const keys = require('./oauth2.keys.json');
94
95 /**
96  * Start by acquiring a pre-authenticated oAuth2 client.
97  */
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);
105
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
110   );
111   console.log(tokenInfo);
112 }
113
114 /**
115  * Create a new OAuth2Client, and go through the OAuth2 content
116  * workflow.  Return the full client to the callback.
117  */
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(
123       keys.web.client_id,
124       keys.web.client_secret,
125       keys.web.redirect_uris[0]
126     );
127
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',
132     });
133
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>
136     const server = http
137       .createServer(async (req, res) => {
138         try {
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')
142               .searchParams;
143             const code = qs.get('code');
144             console.log(`Code is ${code}`);
145             res.end('Authentication successful! Please return to the console.');
146             server.destroy();
147
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);
154           }
155         } catch (e) {
156           reject(e);
157         }
158       })
159       .listen(3000, () => {
160         // open the browser to the authorize url to start the workflow
161         opn(authorizeUrl, {wait: false}).then(cp => cp.unref());
162       });
163     destroyer(server);
164   });
165 }
166
167 main().catch(console.error);
168 ```
169
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:
172
173 ```js
174 const client = await auth.getClient();
175
176 client.on('tokens', (tokens) => {
177   if (tokens.refresh_token) {
178     // store the refresh_token in my database!
179     console.log(tokens.refresh_token);
180   }
181   console.log(tokens.access_token);
182 });
183
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
187 ```
188
189 #### Retrieve access token
190 With the code returned, you can ask for an access token as shown below:
191
192 ``` js
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);
196 ```
197
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`:
200
201 ```js
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.
212   prompt: 'consent'
213 });
214 ```
215
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:
219
220 ```js
221 // after acquiring an oAuth2Client...
222 const tokenInfo = await oAuth2Client.getTokenInfo('my-access-token');
223
224 // take a look at the scopes originally provisioned for the access token
225 console.log(tokenInfo.scopes);
226 ```
227
228 This method will throw if the token is invalid.
229
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]:
232
233 ![application type][apptype]
234
235 If using the `iOS` type, when creating the OAuth2 client you won't need to pass a `client_secret` into the constructor:
236 ```js
237 const oAuth2Client = new OAuth2Client({
238   clientId: <your_client_id>,
239   redirectUri: <your_redirect_uri>
240 });
241 ```
242
243 ## JSON Web Tokens
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.
245
246 ``` js
247 const {JWT} = require('google-auth-library');
248 const keys = require('./jwt.keys.json');
249
250 async function main() {
251   const client = new JWT(
252     keys.client_email,
253     null,
254     keys.private_key,
255     ['https://www.googleapis.com/auth/cloud-platform'],
256   );
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);
260 }
261
262 main().catch(console.error);
263 ```
264
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).
266
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).
269
270 Start by exporting your credentials:
271
272 ```
273 $ export CREDS='{
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"
284 }'
285 ```
286 Now you can create a new client from the credentials:
287
288 ```js
289 const {auth} = require('google-auth-library');
290
291 // load the environment variable with our keys
292 const keysEnvVar = process.env['CREDS'];
293 if (!keysEnvVar) {
294   throw new Error('The $CREDS environment variable was not found!');
295 }
296 const keys = JSON.parse(keysEnvVar);
297
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);
305 }
306
307 main().catch(console.error);
308 ```
309
310 #### Using a Proxy
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.
312
313 ## Compute
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.
315
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.
317
318 ``` js
319 const {auth, Compute} = require('google-auth-library');
320
321 async function main() {
322   const client = new Compute({
323     // Specifying the service account email is optional.
324     serviceAccountEmail: 'my-service-account@example.com'
325   });
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);
330 }
331
332 main().catch(console.error);
333 ```
334
335 ## Questions/problems?
336
337 * Ask your development related questions on [Stack Overflow][stackoverflow].
338 * If you've found an bug/issue, please [file it on GitHub][bugs].
339
340 ## Contributing
341
342 See [CONTRIBUTING][contributing].
343
344 ## License
345
346 This library is licensed under Apache 2.0. Full license text is available in [LICENSE][copying].
347
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