blob: 62836623fd2528c9d350f72eba08be5aa4406117 [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
10user to a service or API. Credentials can be obtained with two different types
11of accounts: *service accounts* and *user accounts*.
12
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
24Obtaining credentials
25---------------------
26
27.. _application-default:
28
29Application default credentials
30+++++++++++++++++++++++++++++++
31
32`Google Application Default Credentials`_ abstracts authentication across the
33different Google Cloud Platform hosting environments. When running on any Google
34Cloud hosting environment or when running locally with the `Google Cloud SDK`_
35installed, :func:`default` can automatically determine the credentials from the
36environment::
37
38 import google.auth
39
40 credentials, project = google.auth.default()
41
42If your application requires specific scopes::
43
44 credentials, project = google.auth.default(
45 scopes=['https://www.googleapis.com/auth/cloud-platform'])
46
47.. _Google Application Default Credentials:
48 https://developers.google.com/identity/protocols/
49 application-default-credentials
50.. _Google Cloud SDK: https://cloud.google.com/sdk
51
52
53Service account private key files
54+++++++++++++++++++++++++++++++++
55
56A service account private key file can be used to obtain credentials for a
57service account. You can create a private key using the `Credentials page of the
58Google Cloud Console`_. Once you have a private key you can either obtain
59credentials one of two ways:
60
611. Set the ``GOOGLE_APPLICATION_CREDENTIALS`` environment variable to the full
62 path to your service account private key file
63
64 .. code-block:: bash
65
66 $ export GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json
67
68 Then, use :ref:`application default credentials <application-default>`.
69 :func:`default` checks for the ``GOOGLE_APPLICATION_CREDENTIALS``
70 environment variable before all other checks, so this will always use the
71 credentials you explicitly specify.
72
732. Use :meth:`service_account.Credentials.from_service_account_file
74 <google.oauth2.service_account.Credentials.from_service_account_file>`::
75
76 from google.oauth2 import service_account
77
78 credentials = service_account.Credentials.from_service_account_file(
79 '/path/to/key.json')
80
81 scoped_credentials = credentials.with_scopes(
82 ['https://www.googleapis.com/auth/cloud-platform'])
83
84.. warning:: Private keys must be kept secret. If you expose your private key it
85 is recommended to revoke it immediately from the Google Cloud Console.
86
87.. _Credentials page of the Google Cloud Console:
88 https://console.cloud.google.com/apis/credentials
89
90Compute Engine, Container Engine, and the App Engine flexible environment
91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
92
93Applications running on `Compute Engine`_, `Container Engine`_, or the `App
94Engine flexible environment`_ can obtain credentials provided by `Compute
95Engine service accounts`_. When running on these platforms you can obtain
96credentials for the service account one of two ways:
97
981. Use :ref:`application default credentials <application-default>`.
99 :func:`default` will automatically detect if these credentials are available.
100
1012. Use :class:`compute_engine.Credentials`::
102
103 from google.auth import compute_engine
104
105 credentials = compute_engine.Credentials()
106
107.. _Compute Engine: https://cloud.google.com/compute
108.. _Container Engine: https://cloud.google.com/container-engine
109.. _App Engine flexible environment:
110 https://cloud.google.com/appengine/docs/flexible/
111.. _Compute Engine service accounts:
112 https://cloud.google.com/compute/docs/access/service-accounts
113
114The App Engine standard environment
115+++++++++++++++++++++++++++++++++++
116
117Applications running on the `App Engine standard environment`_ can obtain
118credentials provided by the `App Engine App Identity API`_. You can obtain
119credentials one of two ways:
120
1211. Use :ref:`application default credentials <application-default>`.
122 :func:`default` will automatically detect if these credentials are available.
123
1242. Use :class:`app_engine.Credentials`::
125
126 from google.auth import app_engine
127
128 credentials = app_engine.Credentials()
129
Hiranya Jayathilaka22d90942017-07-17 09:08:49 -0700130In order to make authenticated requests in the App Engine environment using the
131credentials and transports provided by this library, you need to follow a few
132additional steps:
133
134#. If you are using the :mod:`google.auth.transport.requests` transport, vendor
Rohan Talipb61cecd2018-05-29 08:48:25 -0700135 in the `requests-toolbelt`_ library into your app, and enable the App Engine
Hiranya Jayathilaka22d90942017-07-17 09:08:49 -0700136 monkeypatch. Refer `App Engine documentation`_ for more details on this.
Rohan Talipb61cecd2018-05-29 08:48:25 -0700137#. To make HTTPS calls, enable the ``ssl`` library for your app by adding the
Hiranya Jayathilaka22d90942017-07-17 09:08:49 -0700138 following configuration to the ``app.yaml`` file::
139
140 libraries:
141 - name: ssl
142 version: latest
143
Rohan Talipb61cecd2018-05-29 08:48:25 -0700144#. Enable billing for your App Engine project. Then enable socket support for
Hiranya Jayathilaka22d90942017-07-17 09:08:49 -0700145 your app. This can be achieved by setting an environment variable in the
146 ``app.yaml`` file::
147
148 env_variables:
149 GAE_USE_SOCKETS_HTTPLIB : 'true'
150
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -0800151.. _App Engine standard environment:
152 https://cloud.google.com/appengine/docs/python
153.. _App Engine App Identity API:
154 https://cloud.google.com/appengine/docs/python/appidentity/
Hiranya Jayathilaka22d90942017-07-17 09:08:49 -0700155.. _requests-toolbelt:
156 https://toolbelt.readthedocs.io/en/latest/
157.. _App Engine documentation:
158 https://cloud.google.com/appengine/docs/standard/python/issue-requests
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -0800159
160User credentials
161++++++++++++++++
162
163User credentials are typically obtained via `OAuth 2.0`_. This library does not
Jon Wayne Parrott81701942017-03-01 14:03:38 -0800164provide any direct support for *obtaining* user credentials, however, you can
165use user credentials with this library. You can use libraries such as
166`oauthlib`_ to obtain the access token. After you have an access token, you
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -0800167can create a :class:`google.oauth2.credentials.Credentials` instance::
168
169 import google.oauth2.credentials
170
171 credentials = google.oauth2.credentials.Credentials(
172 'access_token')
173
174If you obtain a refresh token, you can also specify the refresh token and token
175URI to allow the credentials to be automatically refreshed::
176
177 credentials = google.oauth2.credentials.Credentials(
178 'access_token',
179 refresh_token='refresh_token',
180 token_uri='token_uri',
181 client_id='client_id',
182 client_secret='client_secret')
183
Jon Wayne Parrott81701942017-03-01 14:03:38 -0800184
Jon Wayne Parrottd47281b2017-03-22 13:45:26 -0700185There is a separate library, `google-auth-oauthlib`_, that has some helpers
186for integrating with `requests-oauthlib`_ to provide support for obtaining
187user credentials. You can use
188:func:`google_auth_oauthlib.helpers.credentials_from_session` to obtain
Jon Wayne Parrott81701942017-03-01 14:03:38 -0800189:class:`google.oauth2.credentials.Credentials` from a
190:class:`requests_oauthlib.OAuth2Session` as above::
191
Jon Wayne Parrottd47281b2017-03-22 13:45:26 -0700192 from google_auth_oauthlib.helpers import credentials_from_session
Jon Wayne Parrott81701942017-03-01 14:03:38 -0800193
Jon Wayne Parrottd47281b2017-03-22 13:45:26 -0700194 google_auth_credentials = credentials_from_session(oauth2session)
Jon Wayne Parrott81701942017-03-01 14:03:38 -0800195
Jon Wayne Parrottd47281b2017-03-22 13:45:26 -0700196You can also use :class:`google_auth_oauthlib.flow.Flow` to perform the OAuth
1972.0 Authorization Grant Flow to obtain credentials using `requests-oauthlib`_.
Jon Wayne Parrott81701942017-03-01 14:03:38 -0800198
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -0800199.. _OAuth 2.0:
200 https://developers.google.com/identity/protocols/OAuth2
201.. _oauthlib:
202 https://oauthlib.readthedocs.io/en/latest/
Jon Wayne Parrottd47281b2017-03-22 13:45:26 -0700203.. _google-auth-oauthlib:
204 https://pypi.python.org/pypi/google-auth-oauthlib
Jon Wayne Parrott81701942017-03-01 14:03:38 -0800205.. _requests-oauthlib:
206 https://requests-oauthlib.readthedocs.io/en/latest/
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -0800207
salrashid1231fbc6792018-11-09 11:05:34 -0800208Impersonated credentials
209++++++++++++++++++++++++
210
211Impersonated Credentials allows one set of credentials issued to a user or service account
Tianzi Cai40865432019-03-29 11:12:37 -0700212to impersonate another. The source credentials must be granted
213the "Service Account Token Creator" IAM role. ::
salrashid1231fbc6792018-11-09 11:05:34 -0800214
215 from google.auth import impersonated_credentials
216
217 target_scopes = ['https://www.googleapis.com/auth/devstorage.read_only']
218 source_credentials = service_account.Credentials.from_service_account_file(
219 '/path/to/svc_account.json',
220 scopes=target_scopes)
221
222 target_credentials = impersonated_credentials.Credentials(
223 source_credentials=source_credentials,
224 target_principal='impersonated-account@_project_.iam.gserviceaccount.com',
225 target_scopes=target_scopes,
226 lifetime=500)
227 client = storage.Client(credentials=target_credentials)
228 buckets = client.list_buckets(project='your_project')
229 for bucket in buckets:
230 print bucket.name
231
232
233In the example above `source_credentials` does not have direct access to list buckets
234in the target project. Using `ImpersonatedCredentials` will allow the source_credentials
Tianzi Cai40865432019-03-29 11:12:37 -0700235to assume the identity of a target_principal that does have access.
salrashid1231fbc6792018-11-09 11:05:34 -0800236
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -0800237Making authenticated requests
238-----------------------------
239
240Once you have credentials you can attach them to a *transport*. You can then
241use this transport to make authenticated requests to APIs. google-auth supports
242several different transports. Typically, it's up to your application or an
243opinionated client library to decide which transport to use.
244
245Requests
246++++++++
247
248The recommended HTTP transport is :mod:`google.auth.transport.requests` which
249uses the `Requests`_ library. To make authenticated requests using Requests
250you use a custom `Session`_ object::
251
252 from google.auth.transport.requests import AuthorizedSession
253
254 authed_session = AuthorizedSession(credentials)
255
256 response = authed_session.get(
257 'https://www.googleapis.com/storage/v1/b')
258
259.. _Requests: http://docs.python-requests.org/en/master/
260.. _Session: http://docs.python-requests.org/en/master/user/advanced/#session-objects
261
262urllib3
263+++++++
264
265:mod:`urllib3` is the underlying HTTP library used by Requests and can also be
266used with google-auth. urllib3's interface isn't as high-level as Requests but
267it can be useful in situations where you need more control over how HTTP
268requests are made. To make authenticated requests using urllib3 create an
269instance of :class:`google.auth.transport.urllib3.AuthorizedHttp`::
270
271 from google.auth.transport.urllib3 import AuthorizedHttp
272
273 authed_http = AuthorizedHttp(credentials)
274
275 response = authed_http.request(
276 'GET', 'https://www.googleapis.com/storage/v1/b')
277
278You can also construct your own :class:`urllib3.PoolManager` instance and pass
279it to :class:`~google.auth.transport.urllib3.AuthorizedHttp`::
280
281 import urllib3
282
283 http = urllib3.PoolManager()
284 authed_http = AuthorizedHttp(credentials, http)
285
286gRPC
287++++
288
289`gRPC`_ is an RPC framework that uses `Protocol Buffers`_ over `HTTP 2.0`_.
290google-auth can provide `Call Credentials`_ for gRPC. The easiest way to do
291this is to use google-auth to create the gRPC channel::
292
293 import google.auth.transport.grpc
294 import google.auth.transport.requests
295
296 http_request = google.auth.transport.requests.Request()
297
298 channel = google.auth.transport.grpc.secure_authorized_channel(
Jon Wayne Parrott840b3ac2016-11-10 12:07:51 -0800299 credentials, http_request, 'pubsub.googleapis.com:443')
Jon Wayne Parrott53c7b172016-11-10 10:44:30 -0800300
301.. note:: Even though gRPC is its own transport, you still need to use one of
302 the other HTTP transports with gRPC. The reason is that most credential
303 types need to make HTTP requests in order to refresh their access token.
304 The sample above uses the Requests transport, but any HTTP transport can
305 be used. Additionally, if you know that your credentials do not need to
306 make HTTP requests in order to refresh (as is the case with
307 :class:`jwt.Credentials`) then you can specify ``None``.
308
309Alternatively, you can create the channel yourself and use
310:class:`google.auth.transport.grpc.AuthMetadataPlugin`::
311
312 import grpc
313
314 metadata_plugin = AuthMetadataPlugin(credentials, http_request)
315
316 # Create a set of grpc.CallCredentials using the metadata plugin.
317 google_auth_credentials = grpc.metadata_call_credentials(
318 metadata_plugin)
319
320 # Create SSL channel credentials.
321 ssl_credentials = grpc.ssl_channel_credentials()
322
323 # Combine the ssl credentials and the authorization credentials.
324 composite_credentials = grpc.composite_channel_credentials(
325 ssl_credentials, google_auth_credentials)
326
327 channel = grpc.secure_channel(
328 'pubsub.googleapis.com:443', composite_credentials)
329
330You can use this channel to make a gRPC stub that makes authenticated requests
331to a gRPC service::
332
333 from google.pubsub.v1 import pubsub_pb2
334
335 pubsub = pubsub_pb2.PublisherStub(channel)
336
337 response = pubsub.ListTopics(
338 pubsub_pb2.ListTopicsRequest(project='your-project'))
339
340
341.. _gRPC: http://www.grpc.io/
342.. _Protocol Buffers:
343 https://developers.google.com/protocol-buffers/docs/overview
344.. _HTTP 2.0:
345 http://www.grpc.io/docs/guides/wire.html
346.. _Call Credentials:
347 http://www.grpc.io/docs/guides/auth.html