Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/oauth2/service_account.py: 34%
240 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-08 06:51 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-08 06:51 +0000
1# Copyright 2016 Google LLC
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
15"""Service Accounts: JSON Web Token (JWT) Profile for OAuth 2.0
17This module implements the JWT Profile for OAuth 2.0 Authorization Grants
18as defined by `RFC 7523`_ with particular support for how this RFC is
19implemented in Google's infrastructure. Google refers to these credentials
20as *Service Accounts*.
22Service accounts are used for server-to-server communication, such as
23interactions between a web application server and a Google service. The
24service account belongs to your application instead of to an individual end
25user. In contrast to other OAuth 2.0 profiles, no users are involved and your
26application "acts" as the service account.
28Typically an application uses a service account when the application uses
29Google APIs to work with its own data rather than a user's data. For example,
30an application that uses Google Cloud Datastore for data persistence would use
31a service account to authenticate its calls to the Google Cloud Datastore API.
32However, an application that needs to access a user's Drive documents would
33use the normal OAuth 2.0 profile.
35Additionally, Google Apps domain administrators can grant service accounts
36`domain-wide delegation`_ authority to access user data on behalf of users in
37the domain.
39This profile uses a JWT to acquire an OAuth 2.0 access token. The JWT is used
40in place of the usual authorization token returned during the standard
41OAuth 2.0 Authorization Code grant. The JWT is only used for this purpose, as
42the acquired access token is used as the bearer token when making requests
43using these credentials.
45This profile differs from normal OAuth 2.0 profile because no user consent
46step is required. The use of the private key allows this profile to assert
47identity directly.
49This profile also differs from the :mod:`google.auth.jwt` authentication
50because the JWT credentials use the JWT directly as the bearer token. This
51profile instead only uses the JWT to obtain an OAuth 2.0 access token. The
52obtained OAuth 2.0 access token is used as the bearer token.
54Domain-wide delegation
55----------------------
57Domain-wide delegation allows a service account to access user data on
58behalf of any user in a Google Apps domain without consent from the user.
59For example, an application that uses the Google Calendar API to add events to
60the calendars of all users in a Google Apps domain would use a service account
61to access the Google Calendar API on behalf of users.
63The Google Apps administrator must explicitly authorize the service account to
64do this. This authorization step is referred to as "delegating domain-wide
65authority" to a service account.
67You can use domain-wise delegation by creating a set of credentials with a
68specific subject using :meth:`~Credentials.with_subject`.
70.. _RFC 7523: https://tools.ietf.org/html/rfc7523
71"""
73import copy
74import datetime
76from google.auth import _helpers
77from google.auth import _service_account_info
78from google.auth import credentials
79from google.auth import exceptions
80from google.auth import jwt
81from google.auth import metrics
82from google.oauth2 import _client
84_DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
85_DEFAULT_UNIVERSE_DOMAIN = "googleapis.com"
86_GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token"
89class Credentials(
90 credentials.Signing,
91 credentials.Scoped,
92 credentials.CredentialsWithQuotaProject,
93 credentials.CredentialsWithTokenUri,
94):
95 """Service account credentials
97 Usually, you'll create these credentials with one of the helper
98 constructors. To create credentials using a Google service account
99 private key JSON file::
101 credentials = service_account.Credentials.from_service_account_file(
102 'service-account.json')
104 Or if you already have the service account file loaded::
106 service_account_info = json.load(open('service_account.json'))
107 credentials = service_account.Credentials.from_service_account_info(
108 service_account_info)
110 Both helper methods pass on arguments to the constructor, so you can
111 specify additional scopes and a subject if necessary::
113 credentials = service_account.Credentials.from_service_account_file(
114 'service-account.json',
115 scopes=['email'],
116 subject='user@example.com')
118 The credentials are considered immutable. If you want to modify the scopes
119 or the subject used for delegation, use :meth:`with_scopes` or
120 :meth:`with_subject`::
122 scoped_credentials = credentials.with_scopes(['email'])
123 delegated_credentials = credentials.with_subject(subject)
125 To add a quota project, use :meth:`with_quota_project`::
127 credentials = credentials.with_quota_project('myproject-123')
128 """
130 def __init__(
131 self,
132 signer,
133 service_account_email,
134 token_uri,
135 scopes=None,
136 default_scopes=None,
137 subject=None,
138 project_id=None,
139 quota_project_id=None,
140 additional_claims=None,
141 always_use_jwt_access=False,
142 universe_domain=_DEFAULT_UNIVERSE_DOMAIN,
143 trust_boundary=None,
144 ):
145 """
146 Args:
147 signer (google.auth.crypt.Signer): The signer used to sign JWTs.
148 service_account_email (str): The service account's email.
149 scopes (Sequence[str]): User-defined scopes to request during the
150 authorization grant.
151 default_scopes (Sequence[str]): Default scopes passed by a
152 Google client library. Use 'scopes' for user-defined scopes.
153 token_uri (str): The OAuth 2.0 Token URI.
154 subject (str): For domain-wide delegation, the email address of the
155 user to for which to request delegated access.
156 project_id (str): Project ID associated with the service account
157 credential.
158 quota_project_id (Optional[str]): The project ID used for quota and
159 billing.
160 additional_claims (Mapping[str, str]): Any additional claims for
161 the JWT assertion used in the authorization grant.
162 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
163 be always used.
164 universe_domain (str): The universe domain. The default
165 universe domain is googleapis.com. For default value self
166 signed jwt is used for token refresh.
167 trust_boundary (str): String representation of trust boundary meta.
169 .. note:: Typically one of the helper constructors
170 :meth:`from_service_account_file` or
171 :meth:`from_service_account_info` are used instead of calling the
172 constructor directly.
173 """
174 super(Credentials, self).__init__()
176 self._scopes = scopes
177 self._default_scopes = default_scopes
178 self._signer = signer
179 self._service_account_email = service_account_email
180 self._subject = subject
181 self._project_id = project_id
182 self._quota_project_id = quota_project_id
183 self._token_uri = token_uri
184 self._always_use_jwt_access = always_use_jwt_access
185 self._universe_domain = universe_domain or _DEFAULT_UNIVERSE_DOMAIN
187 if universe_domain != _DEFAULT_UNIVERSE_DOMAIN:
188 self._always_use_jwt_access = True
190 self._jwt_credentials = None
192 if additional_claims is not None:
193 self._additional_claims = additional_claims
194 else:
195 self._additional_claims = {}
196 self._trust_boundary = {"locations": [], "encoded_locations": "0x0"}
198 @classmethod
199 def _from_signer_and_info(cls, signer, info, **kwargs):
200 """Creates a Credentials instance from a signer and service account
201 info.
203 Args:
204 signer (google.auth.crypt.Signer): The signer used to sign JWTs.
205 info (Mapping[str, str]): The service account info.
206 kwargs: Additional arguments to pass to the constructor.
208 Returns:
209 google.auth.jwt.Credentials: The constructed credentials.
211 Raises:
212 ValueError: If the info is not in the expected format.
213 """
214 return cls(
215 signer,
216 service_account_email=info["client_email"],
217 token_uri=info["token_uri"],
218 project_id=info.get("project_id"),
219 universe_domain=info.get("universe_domain", _DEFAULT_UNIVERSE_DOMAIN),
220 trust_boundary=info.get("trust_boundary"),
221 **kwargs
222 )
224 @classmethod
225 def from_service_account_info(cls, info, **kwargs):
226 """Creates a Credentials instance from parsed service account info.
228 Args:
229 info (Mapping[str, str]): The service account info in Google
230 format.
231 kwargs: Additional arguments to pass to the constructor.
233 Returns:
234 google.auth.service_account.Credentials: The constructed
235 credentials.
237 Raises:
238 ValueError: If the info is not in the expected format.
239 """
240 signer = _service_account_info.from_dict(
241 info, require=["client_email", "token_uri"]
242 )
243 return cls._from_signer_and_info(signer, info, **kwargs)
245 @classmethod
246 def from_service_account_file(cls, filename, **kwargs):
247 """Creates a Credentials instance from a service account json file.
249 Args:
250 filename (str): The path to the service account json file.
251 kwargs: Additional arguments to pass to the constructor.
253 Returns:
254 google.auth.service_account.Credentials: The constructed
255 credentials.
256 """
257 info, signer = _service_account_info.from_filename(
258 filename, require=["client_email", "token_uri"]
259 )
260 return cls._from_signer_and_info(signer, info, **kwargs)
262 @property
263 def service_account_email(self):
264 """The service account email."""
265 return self._service_account_email
267 @property
268 def project_id(self):
269 """Project ID associated with this credential."""
270 return self._project_id
272 @property
273 def requires_scopes(self):
274 """Checks if the credentials requires scopes.
276 Returns:
277 bool: True if there are no scopes set otherwise False.
278 """
279 return True if not self._scopes else False
281 def _make_copy(self):
282 cred = self.__class__(
283 self._signer,
284 service_account_email=self._service_account_email,
285 scopes=copy.copy(self._scopes),
286 default_scopes=copy.copy(self._default_scopes),
287 token_uri=self._token_uri,
288 subject=self._subject,
289 project_id=self._project_id,
290 quota_project_id=self._quota_project_id,
291 additional_claims=self._additional_claims.copy(),
292 always_use_jwt_access=self._always_use_jwt_access,
293 universe_domain=self._universe_domain,
294 )
295 return cred
297 @_helpers.copy_docstring(credentials.Scoped)
298 def with_scopes(self, scopes, default_scopes=None):
299 cred = self._make_copy()
300 cred._scopes = scopes
301 cred._default_scopes = default_scopes
302 return cred
304 def with_always_use_jwt_access(self, always_use_jwt_access):
305 """Create a copy of these credentials with the specified always_use_jwt_access value.
307 Args:
308 always_use_jwt_access (bool): Whether always use self signed JWT or not.
310 Returns:
311 google.auth.service_account.Credentials: A new credentials
312 instance.
313 Raises:
314 google.auth.exceptions.InvalidValue: If the universe domain is not
315 default and always_use_jwt_access is False.
316 """
317 cred = self._make_copy()
318 if (
319 cred._universe_domain != _DEFAULT_UNIVERSE_DOMAIN
320 and not always_use_jwt_access
321 ):
322 raise exceptions.InvalidValue(
323 "always_use_jwt_access should be True for non-default universe domain"
324 )
325 cred._always_use_jwt_access = always_use_jwt_access
326 return cred
328 def with_universe_domain(self, universe_domain):
329 """Create a copy of these credentials with the given universe domain.
331 Args:
332 universe_domain (str): The universe domain value.
334 Returns:
335 google.auth.service_account.Credentials: A new credentials
336 instance.
337 """
338 cred = self._make_copy()
339 cred._universe_domain = universe_domain
340 if universe_domain != _DEFAULT_UNIVERSE_DOMAIN:
341 cred._always_use_jwt_access = True
342 return cred
344 def with_subject(self, subject):
345 """Create a copy of these credentials with the specified subject.
347 Args:
348 subject (str): The subject claim.
350 Returns:
351 google.auth.service_account.Credentials: A new credentials
352 instance.
353 """
354 cred = self._make_copy()
355 cred._subject = subject
356 return cred
358 def with_claims(self, additional_claims):
359 """Returns a copy of these credentials with modified claims.
361 Args:
362 additional_claims (Mapping[str, str]): Any additional claims for
363 the JWT payload. This will be merged with the current
364 additional claims.
366 Returns:
367 google.auth.service_account.Credentials: A new credentials
368 instance.
369 """
370 new_additional_claims = copy.deepcopy(self._additional_claims)
371 new_additional_claims.update(additional_claims or {})
372 cred = self._make_copy()
373 cred._additional_claims = new_additional_claims
374 return cred
376 @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
377 def with_quota_project(self, quota_project_id):
378 cred = self._make_copy()
379 cred._quota_project_id = quota_project_id
380 return cred
382 @_helpers.copy_docstring(credentials.CredentialsWithTokenUri)
383 def with_token_uri(self, token_uri):
384 cred = self._make_copy()
385 cred._token_uri = token_uri
386 return cred
388 def _make_authorization_grant_assertion(self):
389 """Create the OAuth 2.0 assertion.
391 This assertion is used during the OAuth 2.0 grant to acquire an
392 access token.
394 Returns:
395 bytes: The authorization grant assertion.
396 """
397 now = _helpers.utcnow()
398 lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS)
399 expiry = now + lifetime
401 payload = {
402 "iat": _helpers.datetime_to_secs(now),
403 "exp": _helpers.datetime_to_secs(expiry),
404 # The issuer must be the service account email.
405 "iss": self._service_account_email,
406 # The audience must be the auth token endpoint's URI
407 "aud": _GOOGLE_OAUTH2_TOKEN_ENDPOINT,
408 "scope": _helpers.scopes_to_string(self._scopes or ()),
409 }
411 payload.update(self._additional_claims)
413 # The subject can be a user email for domain-wide delegation.
414 if self._subject:
415 payload.setdefault("sub", self._subject)
417 token = jwt.encode(self._signer, payload)
419 return token
421 def _use_self_signed_jwt(self):
422 # Since domain wide delegation doesn't work with self signed JWT. If
423 # subject exists, then we should not use self signed JWT.
424 return self._subject is None and self._jwt_credentials is not None
426 def _metric_header_for_usage(self):
427 if self._use_self_signed_jwt():
428 return metrics.CRED_TYPE_SA_JWT
429 return metrics.CRED_TYPE_SA_ASSERTION
431 @_helpers.copy_docstring(credentials.Credentials)
432 def refresh(self, request):
433 if self._always_use_jwt_access and not self._jwt_credentials:
434 # If self signed jwt should be used but jwt credential is not
435 # created, try to create one with scopes
436 self._create_self_signed_jwt(None)
438 if self._universe_domain != _DEFAULT_UNIVERSE_DOMAIN and self._subject:
439 raise exceptions.RefreshError(
440 "domain wide delegation is not supported for non-default universe domain"
441 )
443 if self._use_self_signed_jwt():
444 self._jwt_credentials.refresh(request)
445 self.token = self._jwt_credentials.token.decode()
446 self.expiry = self._jwt_credentials.expiry
447 else:
448 assertion = self._make_authorization_grant_assertion()
449 access_token, expiry, _ = _client.jwt_grant(
450 request, self._token_uri, assertion
451 )
452 self.token = access_token
453 self.expiry = expiry
455 def _create_self_signed_jwt(self, audience):
456 """Create a self-signed JWT from the credentials if requirements are met.
458 Args:
459 audience (str): The service URL. ``https://[API_ENDPOINT]/``
460 """
461 # https://google.aip.dev/auth/4111
462 if self._always_use_jwt_access:
463 if self._scopes:
464 additional_claims = {"scope": " ".join(self._scopes)}
465 if (
466 self._jwt_credentials is None
467 or self._jwt_credentials.additional_claims != additional_claims
468 ):
469 self._jwt_credentials = jwt.Credentials.from_signing_credentials(
470 self, None, additional_claims=additional_claims
471 )
472 elif audience:
473 if (
474 self._jwt_credentials is None
475 or self._jwt_credentials._audience != audience
476 ):
478 self._jwt_credentials = jwt.Credentials.from_signing_credentials(
479 self, audience
480 )
481 elif self._default_scopes:
482 additional_claims = {"scope": " ".join(self._default_scopes)}
483 if (
484 self._jwt_credentials is None
485 or additional_claims != self._jwt_credentials.additional_claims
486 ):
487 self._jwt_credentials = jwt.Credentials.from_signing_credentials(
488 self, None, additional_claims=additional_claims
489 )
490 elif not self._scopes and audience:
491 self._jwt_credentials = jwt.Credentials.from_signing_credentials(
492 self, audience
493 )
495 @_helpers.copy_docstring(credentials.Signing)
496 def sign_bytes(self, message):
497 return self._signer.sign(message)
499 @property # type: ignore
500 @_helpers.copy_docstring(credentials.Signing)
501 def signer(self):
502 return self._signer
504 @property # type: ignore
505 @_helpers.copy_docstring(credentials.Signing)
506 def signer_email(self):
507 return self._service_account_email
510class IDTokenCredentials(
511 credentials.Signing,
512 credentials.CredentialsWithQuotaProject,
513 credentials.CredentialsWithTokenUri,
514):
515 """Open ID Connect ID Token-based service account credentials.
517 These credentials are largely similar to :class:`.Credentials`, but instead
518 of using an OAuth 2.0 Access Token as the bearer token, they use an Open
519 ID Connect ID Token as the bearer token. These credentials are useful when
520 communicating to services that require ID Tokens and can not accept access
521 tokens.
523 Usually, you'll create these credentials with one of the helper
524 constructors. To create credentials using a Google service account
525 private key JSON file::
527 credentials = (
528 service_account.IDTokenCredentials.from_service_account_file(
529 'service-account.json'))
532 Or if you already have the service account file loaded::
534 service_account_info = json.load(open('service_account.json'))
535 credentials = (
536 service_account.IDTokenCredentials.from_service_account_info(
537 service_account_info))
540 Both helper methods pass on arguments to the constructor, so you can
541 specify additional scopes and a subject if necessary::
543 credentials = (
544 service_account.IDTokenCredentials.from_service_account_file(
545 'service-account.json',
546 scopes=['email'],
547 subject='user@example.com'))
550 The credentials are considered immutable. If you want to modify the scopes
551 or the subject used for delegation, use :meth:`with_scopes` or
552 :meth:`with_subject`::
554 scoped_credentials = credentials.with_scopes(['email'])
555 delegated_credentials = credentials.with_subject(subject)
557 """
559 def __init__(
560 self,
561 signer,
562 service_account_email,
563 token_uri,
564 target_audience,
565 additional_claims=None,
566 quota_project_id=None,
567 universe_domain=_DEFAULT_UNIVERSE_DOMAIN,
568 ):
569 """
570 Args:
571 signer (google.auth.crypt.Signer): The signer used to sign JWTs.
572 service_account_email (str): The service account's email.
573 token_uri (str): The OAuth 2.0 Token URI.
574 target_audience (str): The intended audience for these credentials,
575 used when requesting the ID Token. The ID Token's ``aud`` claim
576 will be set to this string.
577 additional_claims (Mapping[str, str]): Any additional claims for
578 the JWT assertion used in the authorization grant.
579 quota_project_id (Optional[str]): The project ID used for quota and billing.
580 universe_domain (str): The universe domain. The default
581 universe domain is googleapis.com. For default value IAM ID
582 token endponint is used for token refresh. Note that
583 iam.serviceAccountTokenCreator role is required to use the IAM
584 endpoint.
585 .. note:: Typically one of the helper constructors
586 :meth:`from_service_account_file` or
587 :meth:`from_service_account_info` are used instead of calling the
588 constructor directly.
589 """
590 super(IDTokenCredentials, self).__init__()
591 self._signer = signer
592 self._service_account_email = service_account_email
593 self._token_uri = token_uri
594 self._target_audience = target_audience
595 self._quota_project_id = quota_project_id
596 self._use_iam_endpoint = False
598 if not universe_domain:
599 self._universe_domain = _DEFAULT_UNIVERSE_DOMAIN
600 else:
601 self._universe_domain = universe_domain
603 if universe_domain != _DEFAULT_UNIVERSE_DOMAIN:
604 self._use_iam_endpoint = True
606 if additional_claims is not None:
607 self._additional_claims = additional_claims
608 else:
609 self._additional_claims = {}
611 @classmethod
612 def _from_signer_and_info(cls, signer, info, **kwargs):
613 """Creates a credentials instance from a signer and service account
614 info.
616 Args:
617 signer (google.auth.crypt.Signer): The signer used to sign JWTs.
618 info (Mapping[str, str]): The service account info.
619 kwargs: Additional arguments to pass to the constructor.
621 Returns:
622 google.auth.jwt.IDTokenCredentials: The constructed credentials.
624 Raises:
625 ValueError: If the info is not in the expected format.
626 """
627 kwargs.setdefault("service_account_email", info["client_email"])
628 kwargs.setdefault("token_uri", info["token_uri"])
629 if "universe_domain" in info:
630 kwargs["universe_domain"] = info["universe_domain"]
631 return cls(signer, **kwargs)
633 @classmethod
634 def from_service_account_info(cls, info, **kwargs):
635 """Creates a credentials instance from parsed service account info.
637 Args:
638 info (Mapping[str, str]): The service account info in Google
639 format.
640 kwargs: Additional arguments to pass to the constructor.
642 Returns:
643 google.auth.service_account.IDTokenCredentials: The constructed
644 credentials.
646 Raises:
647 ValueError: If the info is not in the expected format.
648 """
649 signer = _service_account_info.from_dict(
650 info, require=["client_email", "token_uri"]
651 )
652 return cls._from_signer_and_info(signer, info, **kwargs)
654 @classmethod
655 def from_service_account_file(cls, filename, **kwargs):
656 """Creates a credentials instance from a service account json file.
658 Args:
659 filename (str): The path to the service account json file.
660 kwargs: Additional arguments to pass to the constructor.
662 Returns:
663 google.auth.service_account.IDTokenCredentials: The constructed
664 credentials.
665 """
666 info, signer = _service_account_info.from_filename(
667 filename, require=["client_email", "token_uri"]
668 )
669 return cls._from_signer_and_info(signer, info, **kwargs)
671 def _make_copy(self):
672 cred = self.__class__(
673 self._signer,
674 service_account_email=self._service_account_email,
675 token_uri=self._token_uri,
676 target_audience=self._target_audience,
677 additional_claims=self._additional_claims.copy(),
678 quota_project_id=self.quota_project_id,
679 universe_domain=self._universe_domain,
680 )
681 # _use_iam_endpoint is not exposed in the constructor
682 cred._use_iam_endpoint = self._use_iam_endpoint
683 return cred
685 def with_target_audience(self, target_audience):
686 """Create a copy of these credentials with the specified target
687 audience.
689 Args:
690 target_audience (str): The intended audience for these credentials,
691 used when requesting the ID Token.
693 Returns:
694 google.auth.service_account.IDTokenCredentials: A new credentials
695 instance.
696 """
697 cred = self._make_copy()
698 cred._target_audience = target_audience
699 return cred
701 def _with_use_iam_endpoint(self, use_iam_endpoint):
702 """Create a copy of these credentials with the use_iam_endpoint value.
704 Args:
705 use_iam_endpoint (bool): If True, IAM generateIdToken endpoint will
706 be used instead of the token_uri. Note that
707 iam.serviceAccountTokenCreator role is required to use the IAM
708 endpoint. The default value is False. This feature is currently
709 experimental and subject to change without notice.
711 Returns:
712 google.auth.service_account.IDTokenCredentials: A new credentials
713 instance.
714 Raises:
715 google.auth.exceptions.InvalidValue: If the universe domain is not
716 default and use_iam_endpoint is False.
717 """
718 cred = self._make_copy()
719 if cred._universe_domain != _DEFAULT_UNIVERSE_DOMAIN and not use_iam_endpoint:
720 raise exceptions.InvalidValue(
721 "use_iam_endpoint should be True for non-default universe domain"
722 )
723 cred._use_iam_endpoint = use_iam_endpoint
724 return cred
726 @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
727 def with_quota_project(self, quota_project_id):
728 cred = self._make_copy()
729 cred._quota_project_id = quota_project_id
730 return cred
732 @_helpers.copy_docstring(credentials.CredentialsWithTokenUri)
733 def with_token_uri(self, token_uri):
734 cred = self._make_copy()
735 cred._token_uri = token_uri
736 return cred
738 def _make_authorization_grant_assertion(self):
739 """Create the OAuth 2.0 assertion.
741 This assertion is used during the OAuth 2.0 grant to acquire an
742 ID token.
744 Returns:
745 bytes: The authorization grant assertion.
746 """
747 now = _helpers.utcnow()
748 lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS)
749 expiry = now + lifetime
751 payload = {
752 "iat": _helpers.datetime_to_secs(now),
753 "exp": _helpers.datetime_to_secs(expiry),
754 # The issuer must be the service account email.
755 "iss": self.service_account_email,
756 # The audience must be the auth token endpoint's URI
757 "aud": _GOOGLE_OAUTH2_TOKEN_ENDPOINT,
758 # The target audience specifies which service the ID token is
759 # intended for.
760 "target_audience": self._target_audience,
761 }
763 payload.update(self._additional_claims)
765 token = jwt.encode(self._signer, payload)
767 return token
769 def _refresh_with_iam_endpoint(self, request):
770 """Use IAM generateIdToken endpoint to obtain an ID token.
772 It works as follows:
774 1. First we create a self signed jwt with
775 https://www.googleapis.com/auth/iam being the scope.
777 2. Next we use the self signed jwt as the access token, and make a POST
778 request to IAM generateIdToken endpoint. The request body is:
779 {
780 "audience": self._target_audience,
781 "includeEmail": "true",
782 "useEmailAzp": "true",
783 }
785 If the request is succesfully, it will return {"token":"the ID token"},
786 and we can extract the ID token and compute its expiry.
787 """
788 jwt_credentials = jwt.Credentials.from_signing_credentials(
789 self,
790 None,
791 additional_claims={"scope": "https://www.googleapis.com/auth/iam"},
792 )
793 jwt_credentials.refresh(request)
794 self.token, self.expiry = _client.call_iam_generate_id_token_endpoint(
795 request,
796 self.signer_email,
797 self._target_audience,
798 jwt_credentials.token.decode(),
799 )
801 @_helpers.copy_docstring(credentials.Credentials)
802 def refresh(self, request):
803 if self._use_iam_endpoint:
804 self._refresh_with_iam_endpoint(request)
805 else:
806 assertion = self._make_authorization_grant_assertion()
807 access_token, expiry, _ = _client.id_token_jwt_grant(
808 request, self._token_uri, assertion
809 )
810 self.token = access_token
811 self.expiry = expiry
813 @property
814 def service_account_email(self):
815 """The service account email."""
816 return self._service_account_email
818 @_helpers.copy_docstring(credentials.Signing)
819 def sign_bytes(self, message):
820 return self._signer.sign(message)
822 @property # type: ignore
823 @_helpers.copy_docstring(credentials.Signing)
824 def signer(self):
825 return self._signer
827 @property # type: ignore
828 @_helpers.copy_docstring(credentials.Signing)
829 def signer_email(self):
830 return self._service_account_email