blob: ccece57515489e2b1b4f290a1e6676b8e98e823b [file] [log] [blame]
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -08001User Guide
2==========
3
4.. currentmodule:: google.auth
5
6Credentials and account types
7-----------------------------
8
9:class:`~credentials.Credentials` are the means of identifying an application or
bojeil-googled4d7f382021-02-16 12:33:20 -080010user to a service or API. Credentials can be obtained with three different types
11of accounts: *service accounts*, *user accounts* and *external accounts*.
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -080012
13Credentials from service accounts identify a particular application. These types
14of credentials are used in server-to-server use cases, such as accessing a
15database. This library primarily focuses on service account credentials.
16
17Credentials from user accounts are obtained by asking the user to authorize
18access to their data. These types of credentials are used in cases where your
19application needs access to a user's data in another service, such as accessing
20a user's documents in Google Drive. This library provides no support for
21obtaining user credentials, but does provide limited support for using user
22credentials.
23
bojeil-googled4d7f382021-02-16 12:33:20 -080024Credentials from external accounts (workload identity federation) are used to
25identify a particular application from an on-prem or non-Google Cloud platform
26including Amazon Web Services (AWS), Microsoft Azure or any identity provider
27that supports OpenID Connect (OIDC).
28
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -080029Obtaining credentials
30---------------------
31
32.. _application-default:
33
34Application default credentials
35+++++++++++++++++++++++++++++++
36
37`Google Application Default Credentials`_ abstracts authentication across the
38different Google Cloud Platform hosting environments. When running on any Google
39Cloud hosting environment or when running locally with the `Google Cloud SDK`_
40installed, :func:`default` can automatically determine the credentials from the
41environment::
42
43 import google.auth
44
45 credentials, project = google.auth.default()
46
47If your application requires specific scopes::
48
49 credentials, project = google.auth.default(
50 scopes=['https://www.googleapis.com/auth/cloud-platform'])
51
bojeil-googled4d7f382021-02-16 12:33:20 -080052Application Default Credentials also support workload identity federation to
53access Google Cloud resources from non-Google Cloud platforms including Amazon
54Web Services (AWS), Microsoft Azure or any identity provider that supports
55OpenID Connect (OIDC). Workload identity federation is recommended for
56non-Google Cloud environments as it avoids the need to download, manage and
57store service account private keys locally.
58
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -080059.. _Google Application Default Credentials:
60 https://developers.google.com/identity/protocols/
61 application-default-credentials
62.. _Google Cloud SDK: https://cloud.google.com/sdk
63
64
65Service account private key files
66+++++++++++++++++++++++++++++++++
67
68A service account private key file can be used to obtain credentials for a
69service account. You can create a private key using the `Credentials page of the
70Google Cloud Console`_. Once you have a private key you can either obtain
Alan Yee0958d7a2019-07-25 16:22:56 -070071credentials one of three ways:
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -080072
731. Set the ``GOOGLE_APPLICATION_CREDENTIALS`` environment variable to the full
74 path to your service account private key file
75
76 .. code-block:: bash
77
78 $ export GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json
79
80 Then, use :ref:`application default credentials <application-default>`.
81 :func:`default` checks for the ``GOOGLE_APPLICATION_CREDENTIALS``
82 environment variable before all other checks, so this will always use the
83 credentials you explicitly specify.
84
852. Use :meth:`service_account.Credentials.from_service_account_file
86 <google.oauth2.service_account.Credentials.from_service_account_file>`::
87
88 from google.oauth2 import service_account
89
90 credentials = service_account.Credentials.from_service_account_file(
91 '/path/to/key.json')
92
93 scoped_credentials = credentials.with_scopes(
94 ['https://www.googleapis.com/auth/cloud-platform'])
95
Alan Yee0958d7a2019-07-25 16:22:56 -0700963. Use :meth:`service_account.Credentials.from_service_account_info
97 <google.oauth2.service_account.Credentials.from_service_account_info>`::
98
99 import json
100
101 from google.oauth2 import service_account
102
103 json_acct_info = json.loads(function_to_get_json_creds())
104 credentials = service_account.Credentials.from_service_account_info(
105 json_acct_info)
106
107 scoped_credentials = credentials.with_scopes(
108 ['https://www.googleapis.com/auth/cloud-platform'])
109
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -0800110.. warning:: Private keys must be kept secret. If you expose your private key it
111 is recommended to revoke it immediately from the Google Cloud Console.
112
113.. _Credentials page of the Google Cloud Console:
114 https://console.cloud.google.com/apis/credentials
115
116Compute Engine, Container Engine, and the App Engine flexible environment
117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
118
119Applications running on `Compute Engine`_, `Container Engine`_, or the `App
120Engine flexible environment`_ can obtain credentials provided by `Compute
121Engine service accounts`_. When running on these platforms you can obtain
122credentials for the service account one of two ways:
123
1241. Use :ref:`application default credentials <application-default>`.
125 :func:`default` will automatically detect if these credentials are available.
126
1272. Use :class:`compute_engine.Credentials`::
128
129 from google.auth import compute_engine
130
131 credentials = compute_engine.Credentials()
132
133.. _Compute Engine: https://cloud.google.com/compute
134.. _Container Engine: https://cloud.google.com/container-engine
135.. _App Engine flexible environment:
136 https://cloud.google.com/appengine/docs/flexible/
137.. _Compute Engine service accounts:
138 https://cloud.google.com/compute/docs/access/service-accounts
139
140The App Engine standard environment
141+++++++++++++++++++++++++++++++++++
142
143Applications running on the `App Engine standard environment`_ can obtain
144credentials provided by the `App Engine App Identity API`_. You can obtain
145credentials one of two ways:
146
1471. Use :ref:`application default credentials <application-default>`.
148 :func:`default` will automatically detect if these credentials are available.
149
1502. Use :class:`app_engine.Credentials`::
151
152 from google.auth import app_engine
153
154 credentials = app_engine.Credentials()
155
Hiranya Jayathilaka22d90942017-07-17 09:08:49 -0700156In order to make authenticated requests in the App Engine environment using the
157credentials and transports provided by this library, you need to follow a few
158additional steps:
159
160#. If you are using the :mod:`google.auth.transport.requests` transport, vendor
Rohan Talipb61cecd2018-05-29 08:48:25 -0700161 in the `requests-toolbelt`_ library into your app, and enable the App Engine
Hiranya Jayathilaka22d90942017-07-17 09:08:49 -0700162 monkeypatch. Refer `App Engine documentation`_ for more details on this.
Rohan Talipb61cecd2018-05-29 08:48:25 -0700163#. To make HTTPS calls, enable the ``ssl`` library for your app by adding the
Hiranya Jayathilaka22d90942017-07-17 09:08:49 -0700164 following configuration to the ``app.yaml`` file::
165
166 libraries:
167 - name: ssl
168 version: latest
169
Rohan Talipb61cecd2018-05-29 08:48:25 -0700170#. Enable billing for your App Engine project. Then enable socket support for
Hiranya Jayathilaka22d90942017-07-17 09:08:49 -0700171 your app. This can be achieved by setting an environment variable in the
172 ``app.yaml`` file::
173
174 env_variables:
175 GAE_USE_SOCKETS_HTTPLIB : 'true'
176
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -0800177.. _App Engine standard environment:
178 https://cloud.google.com/appengine/docs/python
179.. _App Engine App Identity API:
180 https://cloud.google.com/appengine/docs/python/appidentity/
Hiranya Jayathilaka22d90942017-07-17 09:08:49 -0700181.. _requests-toolbelt:
182 https://toolbelt.readthedocs.io/en/latest/
183.. _App Engine documentation:
184 https://cloud.google.com/appengine/docs/standard/python/issue-requests
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -0800185
186User credentials
187++++++++++++++++
188
189User credentials are typically obtained via `OAuth 2.0`_. This library does not
Jon Wayne Parrott81701942017-03-01 14:03:38 -0800190provide any direct support for *obtaining* user credentials, however, you can
191use user credentials with this library. You can use libraries such as
192`oauthlib`_ to obtain the access token. After you have an access token, you
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -0800193can create a :class:`google.oauth2.credentials.Credentials` instance::
194
195 import google.oauth2.credentials
196
197 credentials = google.oauth2.credentials.Credentials(
198 'access_token')
199
200If you obtain a refresh token, you can also specify the refresh token and token
201URI to allow the credentials to be automatically refreshed::
202
203 credentials = google.oauth2.credentials.Credentials(
204 'access_token',
205 refresh_token='refresh_token',
206 token_uri='token_uri',
207 client_id='client_id',
208 client_secret='client_secret')
209
Jon Wayne Parrott81701942017-03-01 14:03:38 -0800210
Jon Wayne Parrottd47281b2017-03-22 13:45:26 -0700211There is a separate library, `google-auth-oauthlib`_, that has some helpers
212for integrating with `requests-oauthlib`_ to provide support for obtaining
213user credentials. You can use
214:func:`google_auth_oauthlib.helpers.credentials_from_session` to obtain
Jon Wayne Parrott81701942017-03-01 14:03:38 -0800215:class:`google.oauth2.credentials.Credentials` from a
216:class:`requests_oauthlib.OAuth2Session` as above::
217
Jon Wayne Parrottd47281b2017-03-22 13:45:26 -0700218 from google_auth_oauthlib.helpers import credentials_from_session
Jon Wayne Parrott81701942017-03-01 14:03:38 -0800219
Jon Wayne Parrottd47281b2017-03-22 13:45:26 -0700220 google_auth_credentials = credentials_from_session(oauth2session)
Jon Wayne Parrott81701942017-03-01 14:03:38 -0800221
Jon Wayne Parrottd47281b2017-03-22 13:45:26 -0700222You can also use :class:`google_auth_oauthlib.flow.Flow` to perform the OAuth
2232.0 Authorization Grant Flow to obtain credentials using `requests-oauthlib`_.
Jon Wayne Parrott81701942017-03-01 14:03:38 -0800224
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -0800225.. _OAuth 2.0:
226 https://developers.google.com/identity/protocols/OAuth2
227.. _oauthlib:
228 https://oauthlib.readthedocs.io/en/latest/
Jon Wayne Parrottd47281b2017-03-22 13:45:26 -0700229.. _google-auth-oauthlib:
230 https://pypi.python.org/pypi/google-auth-oauthlib
Jon Wayne Parrott81701942017-03-01 14:03:38 -0800231.. _requests-oauthlib:
232 https://requests-oauthlib.readthedocs.io/en/latest/
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -0800233
bojeil-googled4d7f382021-02-16 12:33:20 -0800234External credentials (Workload identity federation)
235+++++++++++++++++++++++++++++++++++++++++++++++++++
236
237Using workload identity federation, your application can access Google Cloud
238resources from Amazon Web Services (AWS), Microsoft Azure or any identity
239provider that supports OpenID Connect (OIDC).
240
241Traditionally, applications running outside Google Cloud have used service
242account keys to access Google Cloud resources. Using identity federation,
243you can allow your workload to impersonate a service account.
244This lets you access Google Cloud resources directly, eliminating the
245maintenance and security burden associated with service account keys.
246
247Accessing resources from AWS
248~~~~~~~~~~~~~~~~~~~~~~~~~~~~
249
250In order to access Google Cloud resources from Amazon Web Services (AWS), the
251following requirements are needed:
252
253- A workload identity pool needs to be created.
254- AWS needs to be added as an identity provider in the workload identity pool
255 (The Google organization policy needs to allow federation from AWS).
256- Permission to impersonate a service account needs to be granted to the
257 external identity.
258- A credential configuration file needs to be generated. Unlike service account
259 credential files, the generated credential configuration file will only
260 contain non-sensitive metadata to instruct the library on how to retrieve
261 external subject tokens and exchange them for service account access tokens.
262
263Follow the detailed instructions on how to
264`Configure Workload Identity Federation from AWS`_.
265
266.. _Configure Workload Identity Federation from AWS:
267 https://cloud.google.com/iam/docs/access-resources-aws
268
269Accessing resources from Microsoft Azure
270~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
271
272In order to access Google Cloud resources from Microsoft Azure, the following
273requirements are needed:
274
275- A workload identity pool needs to be created.
276- Azure needs to be added as an identity provider in the workload identity pool
277 (The Google organization policy needs to allow federation from Azure).
278- The Azure tenant needs to be configured for identity federation.
279- Permission to impersonate a service account needs to be granted to the
280 external identity.
281- A credential configuration file needs to be generated. Unlike service account
282 credential files, the generated credential configuration file will only
283 contain non-sensitive metadata to instruct the library on how to retrieve
284 external subject tokens and exchange them for service account access tokens.
285
286Follow the detailed instructions on how to
287`Configure Workload Identity Federation from Microsoft Azure`_.
288
289.. _Configure Workload Identity Federation from Microsoft Azure:
290 https://cloud.google.com/iam/docs/access-resources-azure
291
292Accessing resources from an OIDC identity provider
293~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
294
295In order to access Google Cloud resources from an identity provider that
296supports `OpenID Connect (OIDC)`_, the following requirements are needed:
297
298- A workload identity pool needs to be created.
299- An OIDC identity provider needs to be added in the workload identity pool
300 (The Google organization policy needs to allow federation from the identity
301 provider).
302- Permission to impersonate a service account needs to be granted to the
303 external identity.
304- A credential configuration file needs to be generated. Unlike service account
305 credential files, the generated credential configuration file will only
306 contain non-sensitive metadata to instruct the library on how to retrieve
307 external subject tokens and exchange them for service account access tokens.
308
309For OIDC providers, the Auth library can retrieve OIDC tokens either from a
310local file location (file-sourced credentials) or from a local server
311(URL-sourced credentials).
312
313- For file-sourced credentials, a background process needs to be continuously
314 refreshing the file location with a new OIDC token prior to expiration.
315 For tokens with one hour lifetimes, the token needs to be updated in the file
316 every hour. The token can be stored directly as plain text or in JSON format.
317- For URL-sourced credentials, a local server needs to host a GET endpoint to
318 return the OIDC token. The response can be in plain text or JSON.
319 Additional required request headers can also be specified.
320
321Follow the detailed instructions on how to
322`Configure Workload Identity Federation from an OIDC identity provider`_.
323
324.. _OpenID Connect (OIDC):
325 https://openid.net/connect/
326.. _Configure Workload Identity Federation from an OIDC identity provider:
327 https://cloud.google.com/iam/docs/access-resources-oidc
328
329Using External Identities
330~~~~~~~~~~~~~~~~~~~~~~~~~
331
332External identities (AWS, Azure and OIDC identity providers) can be used with
333Application Default Credentials.
334In order to use external identities with Application Default Credentials, you
335need to generate the JSON credentials configuration file for your external
336identity.
337Once generated, store the path to this file in the
338``GOOGLE_APPLICATION_CREDENTIALS`` environment variable.
339
340.. code-block:: bash
341
342 $ export GOOGLE_APPLICATION_CREDENTIALS=/path/to/config.json
343
344The library can now automatically choose the right type of client and initialize
345credentials from the context provided in the configuration file::
346
347 import google.auth
348
349 credentials, project = google.auth.default()
350
351When using external identities with Application Default Credentials,
352the ``roles/browser`` role needs to be granted to the service account.
353The ``Cloud Resource Manager API`` should also be enabled on the project.
354This is needed since :func:`default` will try to auto-discover the project ID
355from the current environment using the impersonated credential.
356Otherwise, the project ID will resolve to ``None``. You can override the project
357detection by setting the ``GOOGLE_CLOUD_PROJECT`` environment variable.
358
359You can also explicitly initialize external account clients using the generated
360configuration file.
361
362For Azure and OIDC providers, use :meth:`identity_pool.Credentials.from_info
363<google.auth.identity_pool.Credentials.from_info>` or
364:meth:`identity_pool.Credentials.from_file
365<google.auth.identity_pool.Credentials.from_file>`::
366
367 import json
368
369 from google.auth import identity_pool
370
371 json_config_info = json.loads(function_to_get_json_config())
372 credentials = identity_pool.Credentials.from_info(json_config_info)
373 scoped_credentials = credentials.with_scopes(
374 ['https://www.googleapis.com/auth/cloud-platform'])
375
376For AWS providers, use :meth:`aws.Credentials.from_info
377<google.auth.aws.Credentials.from_info>` or
378:meth:`aws.Credentials.from_file
379<google.auth.aws.Credentials.from_file>`::
380
381 import json
382
383 from google.auth import aws
384
385 json_config_info = json.loads(function_to_get_json_config())
386 credentials = aws.Credentials.from_info(json_config_info)
387 scoped_credentials = credentials.with_scopes(
388 ['https://www.googleapis.com/auth/cloud-platform'])
389
390
salrashid1231fbc6792018-11-09 11:05:34 -0800391Impersonated credentials
392++++++++++++++++++++++++
393
394Impersonated Credentials allows one set of credentials issued to a user or service account
Tianzi Cai40865432019-03-29 11:12:37 -0700395to impersonate another. The source credentials must be granted
396the "Service Account Token Creator" IAM role. ::
salrashid1231fbc6792018-11-09 11:05:34 -0800397
398 from google.auth import impersonated_credentials
399
400 target_scopes = ['https://www.googleapis.com/auth/devstorage.read_only']
401 source_credentials = service_account.Credentials.from_service_account_file(
402 '/path/to/svc_account.json',
403 scopes=target_scopes)
404
405 target_credentials = impersonated_credentials.Credentials(
406 source_credentials=source_credentials,
407 target_principal='impersonated-account@_project_.iam.gserviceaccount.com',
408 target_scopes=target_scopes,
409 lifetime=500)
410 client = storage.Client(credentials=target_credentials)
411 buckets = client.list_buckets(project='your_project')
412 for bucket in buckets:
salrashid1237a8641a2019-08-07 14:31:33 -0700413 print(bucket.name)
salrashid1231fbc6792018-11-09 11:05:34 -0800414
415
416In the example above `source_credentials` does not have direct access to list buckets
417in the target project. Using `ImpersonatedCredentials` will allow the source_credentials
Tianzi Cai40865432019-03-29 11:12:37 -0700418to assume the identity of a target_principal that does have access.
salrashid1231fbc6792018-11-09 11:05:34 -0800419
bojeil-googled1840dc2021-08-06 12:51:22 -0700420
421Downscoped credentials
422++++++++++++++++++++++
423
424`Downscoping with Credential Access Boundaries`_ is used to restrict the
425Identity and Access Management (IAM) permissions that a short-lived credential
426can use.
427
428To downscope permissions of a source credential, a `Credential Access Boundary`
429that specifies which resources the new credential can access, as well as
430an upper bound on the permissions that are available on each resource, has to
431be defined. A downscoped credential can then be instantiated using the
432`source_credential` and the `Credential Access Boundary`.
433
434The common pattern of usage is to have a token broker with elevated access
435generate these downscoped credentials from higher access source credentials and
436pass the downscoped short-lived access tokens to a token consumer via some
437secure authenticated channel for limited access to Google Cloud Storage
438resources.
439
440.. _Downscoping with Credential Access Boundaries: https://cloud.google.com/iam/docs/downscoping-short-lived-credentials
441
442Token broker ::
443
444 import google.auth
445
446 from google.auth import downscoped
447 from google.auth.transport import requests
448
449 # Initialize the credential access boundary rules.
450 available_resource = '//storage.googleapis.com/projects/_/buckets/bucket-123'
451 available_permissions = ['inRole:roles/storage.objectViewer']
452 availability_expression = (
453 "resource.name.startsWith('projects/_/buckets/bucket-123/objects/customer-a')"
454 )
455
456 availability_condition = downscoped.AvailabilityCondition(
457 availability_expression)
458 rule = downscoped.AccessBoundaryRule(
459 available_resource=available_resource,
460 available_permissions=available_permissions,
461 availability_condition=availability_condition)
462 credential_access_boundary = downscoped.CredentialAccessBoundary(
463 rules=[rule])
464
465 # Retrieve the source credentials via ADC.
466 source_credentials, _ = google.auth.default()
467
468 # Create the downscoped credentials.
469 downscoped_credentials = downscoped.Credentials(
470 source_credentials=source_credentials,
471 credential_access_boundary=credential_access_boundary)
472
473 # Refresh the tokens.
474 downscoped_credentials.refresh(requests.Request())
475
476 # These values will need to be passed to the Token Consumer.
477 access_token = downscoped_credentials.token
478 expiry = downscoped_credentials.expiry
479
480
481For example, a token broker can be set up on a server in a private network.
482Various workloads (token consumers) in the same network will send authenticated
483requests to that broker for downscoped tokens to access or modify specific google
484cloud storage buckets.
485
486The broker will instantiate downscoped credentials instances that can be used to
487generate short lived downscoped access tokens that can be passed to the token
488consumer. These downscoped access tokens can be injected by the consumer into
489`google.oauth2.Credentials` and used to initialize a storage client instance to
490access Google Cloud Storage resources with restricted access.
491
492Token Consumer ::
493
494 import google.oauth2
495
496 from google.auth.transport import requests
497 from google.cloud import storage
498
499 # Downscoped token retrieved from token broker.
500 # The `get_token_from_broker` callable requests a token and an expiry
501 # from the token broker.
502 downscoped_token, expiry = get_token_from_broker(
503 requests.Request(),
504 scopes=['https://www.googleapis.com/auth/cloud-platform'])
505
506 # Create the OAuth credentials from the downscoped token and pass a
507 # refresh handler to handle token expiration. Passing the original
508 # downscoped token or the expiry here is optional, as the refresh_handler
509 # will generate the downscoped token on demand.
bojeil-googleda8bb132021-08-09 21:23:25 -0700510 credentials = google.oauth2.credentials.Credentials(
bojeil-googled1840dc2021-08-06 12:51:22 -0700511 downscoped_token,
512 expiry=expiry,
513 scopes=['https://www.googleapis.com/auth/cloud-platform'],
514 refresh_handler=get_token_from_broker)
515
516 # Initialize a storage client with the oauth2 credentials.
517 storage_client = storage.Client(
518 project='my_project_id', credentials=credentials)
519 # Call GCS APIs.
520 # The token broker has readonly access to objects starting with "customer-a"
521 # in bucket "bucket-123".
522 bucket = storage_client.bucket('bucket-123')
523 blob = bucket.blob('customer-a-data.txt')
bojeil-googleda8bb132021-08-09 21:23:25 -0700524 print(blob.download_as_bytes().decode("utf-8"))
bojeil-googled1840dc2021-08-06 12:51:22 -0700525
526
527Another reason to use downscoped credentials is to ensure tokens in flight
528always have the least privileges, e.g. Principle of Least Privilege. ::
529
530 # Create the downscoped credentials.
531 downscoped_credentials = downscoped.Credentials(
532 # source_credentials have elevated access but only a subset of
533 # these permissions are needed here.
534 source_credentials=source_credentials,
535 credential_access_boundary=credential_access_boundary)
536
537 # Pass the token directly.
538 storage_client = storage.Client(
539 project='my_project_id', credentials=downscoped_credentials)
540 # If the source credentials have elevated levels of access, the
541 # token in flight here will have limited readonly access to objects
542 # starting with "customer-a" in bucket "bucket-123".
543 bucket = storage_client.bucket('bucket-123')
544 blob = bucket.blob('customer-a-data.txt')
545 print(blob.download_as_string())
546
547
548Note: Only Cloud Storage supports Credential Access Boundaries. Other Google
549Cloud services do not support this feature.
550
551
salrashid1237a8641a2019-08-07 14:31:33 -0700552Identity Tokens
553+++++++++++++++
554
DanielLearner684457a2021-02-11 14:20:03 -0600555`Google OpenID Connect`_ tokens are available through :mod:`Service Account <google.oauth2.service_account>`,
salrashid1237a8641a2019-08-07 14:31:33 -0700556:mod:`Impersonated <google.auth.impersonated_credentials>`,
557and :mod:`Compute Engine <google.auth.compute_engine>`. These tokens can be used to
558authenticate against `Cloud Functions`_, `Cloud Run`_, a user service behind
559`Identity Aware Proxy`_ or any other service capable of verifying a `Google ID Token`_.
560
561ServiceAccount ::
562
563 from google.oauth2 import service_account
564
565 target_audience = 'https://example.com'
566
567 creds = service_account.IDTokenCredentials.from_service_account_file(
568 '/path/to/svc.json',
569 target_audience=target_audience)
570
571
572Compute ::
573
574 from google.auth import compute_engine
575 import google.auth.transport.requests
576
577 target_audience = 'https://example.com'
578
579 request = google.auth.transport.requests.Request()
580 creds = compute_engine.IDTokenCredentials(request,
581 target_audience=target_audience)
582
583Impersonated ::
584
585 from google.auth import impersonated_credentials
586
587 # get target_credentials from a source_credential
588
589 target_audience = 'https://example.com'
590
591 creds = impersonated_credentials.IDTokenCredentials(
592 target_credentials,
593 target_audience=target_audience)
594
arithmetic1728506c5652020-04-01 10:34:37 -0700595If your application runs on `App Engine`_, `Cloud Run`_, `Compute Engine`_, or
596has application default credentials set via `GOOGLE_APPLICATION_CREDENTIALS`
597environment variable, you can also use `google.oauth2.id_token.fetch_id_token`
598to obtain an ID token from your current running environment. The following is an
599example ::
600
601 import google.oauth2.id_token
602 import google.auth.transport.requests
603
604 request = google.auth.transport.requests.Request()
605 target_audience = "https://pubsub.googleapis.com"
606
607 id_token = google.oauth2.id_token.fetch_id_token(request, target_audience)
608
Thea Flowerse290a3d2020-04-01 10:11:42 -0700609IDToken verification can be done for various type of IDTokens using the
610:class:`google.oauth2.id_token` module. It supports ID token signed with RS256
611and ES256 algorithms. However, ES256 algorithm won't be available unless
612`cryptography` dependency of version at least 1.4.0 is installed. You can check
613the dependency with `pip freeze` or try `from google.auth.crypt import es256`.
Matt Seymour4fd84bd2021-07-08 18:33:42 +0100614The following is an example of verifying ID tokens ::
Thea Flowerse290a3d2020-04-01 10:11:42 -0700615
616 from google.auth2 import id_token
617
618 request = google.auth.transport.requests.Request()
619
620 try:
Matt Seymour4fd84bd2021-07-08 18:33:42 +0100621 decoded_token = id_token.verify_token(token_to_verify,request)
Thea Flowerse290a3d2020-04-01 10:11:42 -0700622 except ValueError:
Matt Seymour4fd84bd2021-07-08 18:33:42 +0100623 # Verification failed.
salrashid1237a8641a2019-08-07 14:31:33 -0700624
625A sample end-to-end flow using an ID Token against a Cloud Run endpoint maybe ::
626
627 from google.oauth2 import id_token
628 from google.oauth2 import service_account
629 import google.auth
630 import google.auth.transport.requests
631 from google.auth.transport.requests import AuthorizedSession
632
633 target_audience = 'https://your-cloud-run-app.a.run.app'
634 url = 'https://your-cloud-run-app.a.run.app'
635
636 creds = service_account.IDTokenCredentials.from_service_account_file(
637 '/path/to/svc.json', target_audience=target_audience)
638
639 authed_session = AuthorizedSession(creds)
640
641 # make authenticated request and print the response, status_code
642 resp = authed_session.get(url)
643 print(resp.status_code)
644 print(resp.text)
645
646 # to verify an ID Token
647 request = google.auth.transport.requests.Request()
648 token = creds.token
649 print(token)
650 print(id_token.verify_token(token,request))
651
arithmetic1728506c5652020-04-01 10:34:37 -0700652.. _App Engine: https://cloud.google.com/appengine/
salrashid1237a8641a2019-08-07 14:31:33 -0700653.. _Cloud Functions: https://cloud.google.com/functions/
654.. _Cloud Run: https://cloud.google.com/run/
655.. _Identity Aware Proxy: https://cloud.google.com/iap/
656.. _Google OpenID Connect: https://developers.google.com/identity/protocols/OpenIDConnect
657.. _Google ID Token: https://developers.google.com/identity/protocols/OpenIDConnect#validatinganidtoken
658
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -0800659Making authenticated requests
660-----------------------------
661
662Once you have credentials you can attach them to a *transport*. You can then
663use this transport to make authenticated requests to APIs. google-auth supports
664several different transports. Typically, it's up to your application or an
665opinionated client library to decide which transport to use.
666
667Requests
668++++++++
669
670The recommended HTTP transport is :mod:`google.auth.transport.requests` which
671uses the `Requests`_ library. To make authenticated requests using Requests
672you use a custom `Session`_ object::
673
674 from google.auth.transport.requests import AuthorizedSession
675
676 authed_session = AuthorizedSession(credentials)
677
678 response = authed_session.get(
679 'https://www.googleapis.com/storage/v1/b')
680
681.. _Requests: http://docs.python-requests.org/en/master/
682.. _Session: http://docs.python-requests.org/en/master/user/advanced/#session-objects
683
684urllib3
685+++++++
686
687:mod:`urllib3` is the underlying HTTP library used by Requests and can also be
688used with google-auth. urllib3's interface isn't as high-level as Requests but
689it can be useful in situations where you need more control over how HTTP
690requests are made. To make authenticated requests using urllib3 create an
691instance of :class:`google.auth.transport.urllib3.AuthorizedHttp`::
692
693 from google.auth.transport.urllib3 import AuthorizedHttp
694
695 authed_http = AuthorizedHttp(credentials)
696
697 response = authed_http.request(
698 'GET', 'https://www.googleapis.com/storage/v1/b')
699
700You can also construct your own :class:`urllib3.PoolManager` instance and pass
701it to :class:`~google.auth.transport.urllib3.AuthorizedHttp`::
702
703 import urllib3
704
705 http = urllib3.PoolManager()
706 authed_http = AuthorizedHttp(credentials, http)
707
708gRPC
709++++
710
711`gRPC`_ is an RPC framework that uses `Protocol Buffers`_ over `HTTP 2.0`_.
712google-auth can provide `Call Credentials`_ for gRPC. The easiest way to do
713this is to use google-auth to create the gRPC channel::
714
715 import google.auth.transport.grpc
716 import google.auth.transport.requests
717
718 http_request = google.auth.transport.requests.Request()
719
720 channel = google.auth.transport.grpc.secure_authorized_channel(
Jon Wayne Parrott840b3ac2016-11-10 12:07:51 -0800721 credentials, http_request, 'pubsub.googleapis.com:443')
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -0800722
723.. note:: Even though gRPC is its own transport, you still need to use one of
724 the other HTTP transports with gRPC. The reason is that most credential
725 types need to make HTTP requests in order to refresh their access token.
726 The sample above uses the Requests transport, but any HTTP transport can
727 be used. Additionally, if you know that your credentials do not need to
728 make HTTP requests in order to refresh (as is the case with
729 :class:`jwt.Credentials`) then you can specify ``None``.
730
731Alternatively, you can create the channel yourself and use
732:class:`google.auth.transport.grpc.AuthMetadataPlugin`::
733
734 import grpc
735
736 metadata_plugin = AuthMetadataPlugin(credentials, http_request)
737
738 # Create a set of grpc.CallCredentials using the metadata plugin.
739 google_auth_credentials = grpc.metadata_call_credentials(
740 metadata_plugin)
741
742 # Create SSL channel credentials.
743 ssl_credentials = grpc.ssl_channel_credentials()
744
745 # Combine the ssl credentials and the authorization credentials.
746 composite_credentials = grpc.composite_channel_credentials(
747 ssl_credentials, google_auth_credentials)
748
749 channel = grpc.secure_channel(
750 'pubsub.googleapis.com:443', composite_credentials)
751
752You can use this channel to make a gRPC stub that makes authenticated requests
753to a gRPC service::
754
755 from google.pubsub.v1 import pubsub_pb2
756
757 pubsub = pubsub_pb2.PublisherStub(channel)
758
759 response = pubsub.ListTopics(
760 pubsub_pb2.ListTopicsRequest(project='your-project'))
761
762
763.. _gRPC: http://www.grpc.io/
764.. _Protocol Buffers:
765 https://developers.google.com/protocol-buffers/docs/overview
766.. _HTTP 2.0:
767 http://www.grpc.io/docs/guides/wire.html
768.. _Call Credentials:
769 http://www.grpc.io/docs/guides/auth.html