jwt.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  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.
  14. """JSON Web Tokens
  15. Provides support for creating (encoding) and verifying (decoding) JWTs,
  16. especially JWTs generated and consumed by Google infrastructure.
  17. See `rfc7519`_ for more details on JWTs.
  18. To encode a JWT use :func:`encode`::
  19. from google.auth import crypt
  20. from google.auth import jwt
  21. signer = crypt.Signer(private_key)
  22. payload = {'some': 'payload'}
  23. encoded = jwt.encode(signer, payload)
  24. To decode a JWT and verify claims use :func:`decode`::
  25. claims = jwt.decode(encoded, certs=public_certs)
  26. You can also skip verification::
  27. claims = jwt.decode(encoded, verify=False)
  28. .. _rfc7519: https://tools.ietf.org/html/rfc7519
  29. """
  30. try:
  31. from collections.abc import Mapping
  32. # Python 2.7 compatibility
  33. except ImportError: # pragma: NO COVER
  34. from collections import Mapping
  35. import copy
  36. import datetime
  37. import json
  38. import cachetools
  39. import six
  40. from six.moves import urllib
  41. from google.auth import _helpers
  42. from google.auth import _service_account_info
  43. from google.auth import crypt
  44. from google.auth import exceptions
  45. import google.auth.credentials
  46. try:
  47. from google.auth.crypt import es256
  48. except ImportError: # pragma: NO COVER
  49. es256 = None
  50. _DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
  51. _DEFAULT_MAX_CACHE_SIZE = 10
  52. _ALGORITHM_TO_VERIFIER_CLASS = {"RS256": crypt.RSAVerifier}
  53. _CRYPTOGRAPHY_BASED_ALGORITHMS = frozenset(["ES256"])
  54. if es256 is not None: # pragma: NO COVER
  55. _ALGORITHM_TO_VERIFIER_CLASS["ES256"] = es256.ES256Verifier
  56. def encode(signer, payload, header=None, key_id=None):
  57. """Make a signed JWT.
  58. Args:
  59. signer (google.auth.crypt.Signer): The signer used to sign the JWT.
  60. payload (Mapping[str, str]): The JWT payload.
  61. header (Mapping[str, str]): Additional JWT header payload.
  62. key_id (str): The key id to add to the JWT header. If the
  63. signer has a key id it will be used as the default. If this is
  64. specified it will override the signer's key id.
  65. Returns:
  66. bytes: The encoded JWT.
  67. """
  68. if header is None:
  69. header = {}
  70. if key_id is None:
  71. key_id = signer.key_id
  72. header.update({"typ": "JWT"})
  73. if "alg" not in header:
  74. if es256 is not None and isinstance(signer, es256.ES256Signer):
  75. header.update({"alg": "ES256"})
  76. else:
  77. header.update({"alg": "RS256"})
  78. if key_id is not None:
  79. header["kid"] = key_id
  80. segments = [
  81. _helpers.unpadded_urlsafe_b64encode(json.dumps(header).encode("utf-8")),
  82. _helpers.unpadded_urlsafe_b64encode(json.dumps(payload).encode("utf-8")),
  83. ]
  84. signing_input = b".".join(segments)
  85. signature = signer.sign(signing_input)
  86. segments.append(_helpers.unpadded_urlsafe_b64encode(signature))
  87. return b".".join(segments)
  88. def _decode_jwt_segment(encoded_section):
  89. """Decodes a single JWT segment."""
  90. section_bytes = _helpers.padded_urlsafe_b64decode(encoded_section)
  91. try:
  92. return json.loads(section_bytes.decode("utf-8"))
  93. except ValueError as caught_exc:
  94. new_exc = ValueError("Can't parse segment: {0}".format(section_bytes))
  95. six.raise_from(new_exc, caught_exc)
  96. def _unverified_decode(token):
  97. """Decodes a token and does no verification.
  98. Args:
  99. token (Union[str, bytes]): The encoded JWT.
  100. Returns:
  101. Tuple[str, str, str, str]: header, payload, signed_section, and
  102. signature.
  103. Raises:
  104. ValueError: if there are an incorrect amount of segments in the token.
  105. """
  106. token = _helpers.to_bytes(token)
  107. if token.count(b".") != 2:
  108. raise ValueError("Wrong number of segments in token: {0}".format(token))
  109. encoded_header, encoded_payload, signature = token.split(b".")
  110. signed_section = encoded_header + b"." + encoded_payload
  111. signature = _helpers.padded_urlsafe_b64decode(signature)
  112. # Parse segments
  113. header = _decode_jwt_segment(encoded_header)
  114. payload = _decode_jwt_segment(encoded_payload)
  115. return header, payload, signed_section, signature
  116. def decode_header(token):
  117. """Return the decoded header of a token.
  118. No verification is done. This is useful to extract the key id from
  119. the header in order to acquire the appropriate certificate to verify
  120. the token.
  121. Args:
  122. token (Union[str, bytes]): the encoded JWT.
  123. Returns:
  124. Mapping: The decoded JWT header.
  125. """
  126. header, _, _, _ = _unverified_decode(token)
  127. return header
  128. def _verify_iat_and_exp(payload):
  129. """Verifies the ``iat`` (Issued At) and ``exp`` (Expires) claims in a token
  130. payload.
  131. Args:
  132. payload (Mapping[str, str]): The JWT payload.
  133. Raises:
  134. ValueError: if any checks failed.
  135. """
  136. now = _helpers.datetime_to_secs(_helpers.utcnow())
  137. # Make sure the iat and exp claims are present.
  138. for key in ("iat", "exp"):
  139. if key not in payload:
  140. raise ValueError("Token does not contain required claim {}".format(key))
  141. # Make sure the token wasn't issued in the future.
  142. iat = payload["iat"]
  143. # Err on the side of accepting a token that is slightly early to account
  144. # for clock skew.
  145. earliest = iat - _helpers.CLOCK_SKEW_SECS
  146. if now < earliest:
  147. raise ValueError("Token used too early, {} < {}".format(now, iat))
  148. # Make sure the token wasn't issued in the past.
  149. exp = payload["exp"]
  150. # Err on the side of accepting a token that is slightly out of date
  151. # to account for clow skew.
  152. latest = exp + _helpers.CLOCK_SKEW_SECS
  153. if latest < now:
  154. raise ValueError("Token expired, {} < {}".format(latest, now))
  155. def decode(token, certs=None, verify=True, audience=None):
  156. """Decode and verify a JWT.
  157. Args:
  158. token (str): The encoded JWT.
  159. certs (Union[str, bytes, Mapping[str, Union[str, bytes]]]): The
  160. certificate used to validate the JWT signature. If bytes or string,
  161. it must the the public key certificate in PEM format. If a mapping,
  162. it must be a mapping of key IDs to public key certificates in PEM
  163. format. The mapping must contain the same key ID that's specified
  164. in the token's header.
  165. verify (bool): Whether to perform signature and claim validation.
  166. Verification is done by default.
  167. audience (str or list): The audience claim, 'aud', that this JWT should
  168. contain. Or a list of audience claims. If None then the JWT's 'aud'
  169. parameter is not verified.
  170. Returns:
  171. Mapping[str, str]: The deserialized JSON payload in the JWT.
  172. Raises:
  173. ValueError: if any verification checks failed.
  174. """
  175. header, payload, signed_section, signature = _unverified_decode(token)
  176. if not verify:
  177. return payload
  178. # Pluck the key id and algorithm from the header and make sure we have
  179. # a verifier that can support it.
  180. key_alg = header.get("alg")
  181. key_id = header.get("kid")
  182. try:
  183. verifier_cls = _ALGORITHM_TO_VERIFIER_CLASS[key_alg]
  184. except KeyError as exc:
  185. if key_alg in _CRYPTOGRAPHY_BASED_ALGORITHMS:
  186. six.raise_from(
  187. ValueError(
  188. "The key algorithm {} requires the cryptography package "
  189. "to be installed.".format(key_alg)
  190. ),
  191. exc,
  192. )
  193. else:
  194. six.raise_from(
  195. ValueError("Unsupported signature algorithm {}".format(key_alg)), exc
  196. )
  197. # If certs is specified as a dictionary of key IDs to certificates, then
  198. # use the certificate identified by the key ID in the token header.
  199. if isinstance(certs, Mapping):
  200. if key_id:
  201. if key_id not in certs:
  202. raise ValueError("Certificate for key id {} not found.".format(key_id))
  203. certs_to_check = [certs[key_id]]
  204. # If there's no key id in the header, check against all of the certs.
  205. else:
  206. certs_to_check = certs.values()
  207. else:
  208. certs_to_check = certs
  209. # Verify that the signature matches the message.
  210. if not crypt.verify_signature(
  211. signed_section, signature, certs_to_check, verifier_cls
  212. ):
  213. raise ValueError("Could not verify token signature.")
  214. # Verify the issued at and created times in the payload.
  215. _verify_iat_and_exp(payload)
  216. # Check audience.
  217. if audience is not None:
  218. claim_audience = payload.get("aud")
  219. if isinstance(audience, str):
  220. audience = [audience]
  221. if claim_audience not in audience:
  222. raise ValueError(
  223. "Token has wrong audience {}, expected one of {}".format(
  224. claim_audience, audience
  225. )
  226. )
  227. return payload
  228. class Credentials(
  229. google.auth.credentials.Signing, google.auth.credentials.CredentialsWithQuotaProject
  230. ):
  231. """Credentials that use a JWT as the bearer token.
  232. These credentials require an "audience" claim. This claim identifies the
  233. intended recipient of the bearer token.
  234. The constructor arguments determine the claims for the JWT that is
  235. sent with requests. Usually, you'll construct these credentials with
  236. one of the helper constructors as shown in the next section.
  237. To create JWT credentials using a Google service account private key
  238. JSON file::
  239. audience = 'https://pubsub.googleapis.com/google.pubsub.v1.Publisher'
  240. credentials = jwt.Credentials.from_service_account_file(
  241. 'service-account.json',
  242. audience=audience)
  243. If you already have the service account file loaded and parsed::
  244. service_account_info = json.load(open('service_account.json'))
  245. credentials = jwt.Credentials.from_service_account_info(
  246. service_account_info,
  247. audience=audience)
  248. Both helper methods pass on arguments to the constructor, so you can
  249. specify the JWT claims::
  250. credentials = jwt.Credentials.from_service_account_file(
  251. 'service-account.json',
  252. audience=audience,
  253. additional_claims={'meta': 'data'})
  254. You can also construct the credentials directly if you have a
  255. :class:`~google.auth.crypt.Signer` instance::
  256. credentials = jwt.Credentials(
  257. signer,
  258. issuer='your-issuer',
  259. subject='your-subject',
  260. audience=audience)
  261. The claims are considered immutable. If you want to modify the claims,
  262. you can easily create another instance using :meth:`with_claims`::
  263. new_audience = (
  264. 'https://pubsub.googleapis.com/google.pubsub.v1.Subscriber')
  265. new_credentials = credentials.with_claims(audience=new_audience)
  266. """
  267. def __init__(
  268. self,
  269. signer,
  270. issuer,
  271. subject,
  272. audience,
  273. additional_claims=None,
  274. token_lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
  275. quota_project_id=None,
  276. ):
  277. """
  278. Args:
  279. signer (google.auth.crypt.Signer): The signer used to sign JWTs.
  280. issuer (str): The `iss` claim.
  281. subject (str): The `sub` claim.
  282. audience (str): the `aud` claim. The intended audience for the
  283. credentials.
  284. additional_claims (Mapping[str, str]): Any additional claims for
  285. the JWT payload.
  286. token_lifetime (int): The amount of time in seconds for
  287. which the token is valid. Defaults to 1 hour.
  288. quota_project_id (Optional[str]): The project ID used for quota
  289. and billing.
  290. """
  291. super(Credentials, self).__init__()
  292. self._signer = signer
  293. self._issuer = issuer
  294. self._subject = subject
  295. self._audience = audience
  296. self._token_lifetime = token_lifetime
  297. self._quota_project_id = quota_project_id
  298. if additional_claims is None:
  299. additional_claims = {}
  300. self._additional_claims = additional_claims
  301. @classmethod
  302. def _from_signer_and_info(cls, signer, info, **kwargs):
  303. """Creates a Credentials instance from a signer and service account
  304. info.
  305. Args:
  306. signer (google.auth.crypt.Signer): The signer used to sign JWTs.
  307. info (Mapping[str, str]): The service account info.
  308. kwargs: Additional arguments to pass to the constructor.
  309. Returns:
  310. google.auth.jwt.Credentials: The constructed credentials.
  311. Raises:
  312. ValueError: If the info is not in the expected format.
  313. """
  314. kwargs.setdefault("subject", info["client_email"])
  315. kwargs.setdefault("issuer", info["client_email"])
  316. return cls(signer, **kwargs)
  317. @classmethod
  318. def from_service_account_info(cls, info, **kwargs):
  319. """Creates an Credentials instance from a dictionary.
  320. Args:
  321. info (Mapping[str, str]): The service account info in Google
  322. format.
  323. kwargs: Additional arguments to pass to the constructor.
  324. Returns:
  325. google.auth.jwt.Credentials: The constructed credentials.
  326. Raises:
  327. ValueError: If the info is not in the expected format.
  328. """
  329. signer = _service_account_info.from_dict(info, require=["client_email"])
  330. return cls._from_signer_and_info(signer, info, **kwargs)
  331. @classmethod
  332. def from_service_account_file(cls, filename, **kwargs):
  333. """Creates a Credentials instance from a service account .json file
  334. in Google format.
  335. Args:
  336. filename (str): The path to the service account .json file.
  337. kwargs: Additional arguments to pass to the constructor.
  338. Returns:
  339. google.auth.jwt.Credentials: The constructed credentials.
  340. """
  341. info, signer = _service_account_info.from_filename(
  342. filename, require=["client_email"]
  343. )
  344. return cls._from_signer_and_info(signer, info, **kwargs)
  345. @classmethod
  346. def from_signing_credentials(cls, credentials, audience, **kwargs):
  347. """Creates a new :class:`google.auth.jwt.Credentials` instance from an
  348. existing :class:`google.auth.credentials.Signing` instance.
  349. The new instance will use the same signer as the existing instance and
  350. will use the existing instance's signer email as the issuer and
  351. subject by default.
  352. Example::
  353. svc_creds = service_account.Credentials.from_service_account_file(
  354. 'service_account.json')
  355. audience = (
  356. 'https://pubsub.googleapis.com/google.pubsub.v1.Publisher')
  357. jwt_creds = jwt.Credentials.from_signing_credentials(
  358. svc_creds, audience=audience)
  359. Args:
  360. credentials (google.auth.credentials.Signing): The credentials to
  361. use to construct the new credentials.
  362. audience (str): the `aud` claim. The intended audience for the
  363. credentials.
  364. kwargs: Additional arguments to pass to the constructor.
  365. Returns:
  366. google.auth.jwt.Credentials: A new Credentials instance.
  367. """
  368. kwargs.setdefault("issuer", credentials.signer_email)
  369. kwargs.setdefault("subject", credentials.signer_email)
  370. return cls(credentials.signer, audience=audience, **kwargs)
  371. def with_claims(
  372. self, issuer=None, subject=None, audience=None, additional_claims=None
  373. ):
  374. """Returns a copy of these credentials with modified claims.
  375. Args:
  376. issuer (str): The `iss` claim. If unspecified the current issuer
  377. claim will be used.
  378. subject (str): The `sub` claim. If unspecified the current subject
  379. claim will be used.
  380. audience (str): the `aud` claim. If unspecified the current
  381. audience claim will be used.
  382. additional_claims (Mapping[str, str]): Any additional claims for
  383. the JWT payload. This will be merged with the current
  384. additional claims.
  385. Returns:
  386. google.auth.jwt.Credentials: A new credentials instance.
  387. """
  388. new_additional_claims = copy.deepcopy(self._additional_claims)
  389. new_additional_claims.update(additional_claims or {})
  390. return self.__class__(
  391. self._signer,
  392. issuer=issuer if issuer is not None else self._issuer,
  393. subject=subject if subject is not None else self._subject,
  394. audience=audience if audience is not None else self._audience,
  395. additional_claims=new_additional_claims,
  396. quota_project_id=self._quota_project_id,
  397. )
  398. @_helpers.copy_docstring(google.auth.credentials.CredentialsWithQuotaProject)
  399. def with_quota_project(self, quota_project_id):
  400. return self.__class__(
  401. self._signer,
  402. issuer=self._issuer,
  403. subject=self._subject,
  404. audience=self._audience,
  405. additional_claims=self._additional_claims,
  406. quota_project_id=quota_project_id,
  407. )
  408. def _make_jwt(self):
  409. """Make a signed JWT.
  410. Returns:
  411. Tuple[bytes, datetime]: The encoded JWT and the expiration.
  412. """
  413. now = _helpers.utcnow()
  414. lifetime = datetime.timedelta(seconds=self._token_lifetime)
  415. expiry = now + lifetime
  416. payload = {
  417. "iss": self._issuer,
  418. "sub": self._subject,
  419. "iat": _helpers.datetime_to_secs(now),
  420. "exp": _helpers.datetime_to_secs(expiry),
  421. }
  422. if self._audience:
  423. payload["aud"] = self._audience
  424. payload.update(self._additional_claims)
  425. jwt = encode(self._signer, payload)
  426. return jwt, expiry
  427. def refresh(self, request):
  428. """Refreshes the access token.
  429. Args:
  430. request (Any): Unused.
  431. """
  432. # pylint: disable=unused-argument
  433. # (pylint doesn't correctly recognize overridden methods.)
  434. self.token, self.expiry = self._make_jwt()
  435. @_helpers.copy_docstring(google.auth.credentials.Signing)
  436. def sign_bytes(self, message):
  437. return self._signer.sign(message)
  438. @property
  439. @_helpers.copy_docstring(google.auth.credentials.Signing)
  440. def signer_email(self):
  441. return self._issuer
  442. @property
  443. @_helpers.copy_docstring(google.auth.credentials.Signing)
  444. def signer(self):
  445. return self._signer
  446. class OnDemandCredentials(
  447. google.auth.credentials.Signing, google.auth.credentials.CredentialsWithQuotaProject
  448. ):
  449. """On-demand JWT credentials.
  450. Like :class:`Credentials`, this class uses a JWT as the bearer token for
  451. authentication. However, this class does not require the audience at
  452. construction time. Instead, it will generate a new token on-demand for
  453. each request using the request URI as the audience. It caches tokens
  454. so that multiple requests to the same URI do not incur the overhead
  455. of generating a new token every time.
  456. This behavior is especially useful for `gRPC`_ clients. A gRPC service may
  457. have multiple audience and gRPC clients may not know all of the audiences
  458. required for accessing a particular service. With these credentials,
  459. no knowledge of the audiences is required ahead of time.
  460. .. _grpc: http://www.grpc.io/
  461. """
  462. def __init__(
  463. self,
  464. signer,
  465. issuer,
  466. subject,
  467. additional_claims=None,
  468. token_lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
  469. max_cache_size=_DEFAULT_MAX_CACHE_SIZE,
  470. quota_project_id=None,
  471. ):
  472. """
  473. Args:
  474. signer (google.auth.crypt.Signer): The signer used to sign JWTs.
  475. issuer (str): The `iss` claim.
  476. subject (str): The `sub` claim.
  477. additional_claims (Mapping[str, str]): Any additional claims for
  478. the JWT payload.
  479. token_lifetime (int): The amount of time in seconds for
  480. which the token is valid. Defaults to 1 hour.
  481. max_cache_size (int): The maximum number of JWT tokens to keep in
  482. cache. Tokens are cached using :class:`cachetools.LRUCache`.
  483. quota_project_id (Optional[str]): The project ID used for quota
  484. and billing.
  485. """
  486. super(OnDemandCredentials, self).__init__()
  487. self._signer = signer
  488. self._issuer = issuer
  489. self._subject = subject
  490. self._token_lifetime = token_lifetime
  491. self._quota_project_id = quota_project_id
  492. if additional_claims is None:
  493. additional_claims = {}
  494. self._additional_claims = additional_claims
  495. self._cache = cachetools.LRUCache(maxsize=max_cache_size)
  496. @classmethod
  497. def _from_signer_and_info(cls, signer, info, **kwargs):
  498. """Creates an OnDemandCredentials instance from a signer and service
  499. account info.
  500. Args:
  501. signer (google.auth.crypt.Signer): The signer used to sign JWTs.
  502. info (Mapping[str, str]): The service account info.
  503. kwargs: Additional arguments to pass to the constructor.
  504. Returns:
  505. google.auth.jwt.OnDemandCredentials: The constructed credentials.
  506. Raises:
  507. ValueError: If the info is not in the expected format.
  508. """
  509. kwargs.setdefault("subject", info["client_email"])
  510. kwargs.setdefault("issuer", info["client_email"])
  511. return cls(signer, **kwargs)
  512. @classmethod
  513. def from_service_account_info(cls, info, **kwargs):
  514. """Creates an OnDemandCredentials instance from a dictionary.
  515. Args:
  516. info (Mapping[str, str]): The service account info in Google
  517. format.
  518. kwargs: Additional arguments to pass to the constructor.
  519. Returns:
  520. google.auth.jwt.OnDemandCredentials: The constructed credentials.
  521. Raises:
  522. ValueError: If the info is not in the expected format.
  523. """
  524. signer = _service_account_info.from_dict(info, require=["client_email"])
  525. return cls._from_signer_and_info(signer, info, **kwargs)
  526. @classmethod
  527. def from_service_account_file(cls, filename, **kwargs):
  528. """Creates an OnDemandCredentials instance from a service account .json
  529. file in Google format.
  530. Args:
  531. filename (str): The path to the service account .json file.
  532. kwargs: Additional arguments to pass to the constructor.
  533. Returns:
  534. google.auth.jwt.OnDemandCredentials: The constructed credentials.
  535. """
  536. info, signer = _service_account_info.from_filename(
  537. filename, require=["client_email"]
  538. )
  539. return cls._from_signer_and_info(signer, info, **kwargs)
  540. @classmethod
  541. def from_signing_credentials(cls, credentials, **kwargs):
  542. """Creates a new :class:`google.auth.jwt.OnDemandCredentials` instance
  543. from an existing :class:`google.auth.credentials.Signing` instance.
  544. The new instance will use the same signer as the existing instance and
  545. will use the existing instance's signer email as the issuer and
  546. subject by default.
  547. Example::
  548. svc_creds = service_account.Credentials.from_service_account_file(
  549. 'service_account.json')
  550. jwt_creds = jwt.OnDemandCredentials.from_signing_credentials(
  551. svc_creds)
  552. Args:
  553. credentials (google.auth.credentials.Signing): The credentials to
  554. use to construct the new credentials.
  555. kwargs: Additional arguments to pass to the constructor.
  556. Returns:
  557. google.auth.jwt.Credentials: A new Credentials instance.
  558. """
  559. kwargs.setdefault("issuer", credentials.signer_email)
  560. kwargs.setdefault("subject", credentials.signer_email)
  561. return cls(credentials.signer, **kwargs)
  562. def with_claims(self, issuer=None, subject=None, additional_claims=None):
  563. """Returns a copy of these credentials with modified claims.
  564. Args:
  565. issuer (str): The `iss` claim. If unspecified the current issuer
  566. claim will be used.
  567. subject (str): The `sub` claim. If unspecified the current subject
  568. claim will be used.
  569. additional_claims (Mapping[str, str]): Any additional claims for
  570. the JWT payload. This will be merged with the current
  571. additional claims.
  572. Returns:
  573. google.auth.jwt.OnDemandCredentials: A new credentials instance.
  574. """
  575. new_additional_claims = copy.deepcopy(self._additional_claims)
  576. new_additional_claims.update(additional_claims or {})
  577. return self.__class__(
  578. self._signer,
  579. issuer=issuer if issuer is not None else self._issuer,
  580. subject=subject if subject is not None else self._subject,
  581. additional_claims=new_additional_claims,
  582. max_cache_size=self._cache.maxsize,
  583. quota_project_id=self._quota_project_id,
  584. )
  585. @_helpers.copy_docstring(google.auth.credentials.CredentialsWithQuotaProject)
  586. def with_quota_project(self, quota_project_id):
  587. return self.__class__(
  588. self._signer,
  589. issuer=self._issuer,
  590. subject=self._subject,
  591. additional_claims=self._additional_claims,
  592. max_cache_size=self._cache.maxsize,
  593. quota_project_id=quota_project_id,
  594. )
  595. @property
  596. def valid(self):
  597. """Checks the validity of the credentials.
  598. These credentials are always valid because it generates tokens on
  599. demand.
  600. """
  601. return True
  602. def _make_jwt_for_audience(self, audience):
  603. """Make a new JWT for the given audience.
  604. Args:
  605. audience (str): The intended audience.
  606. Returns:
  607. Tuple[bytes, datetime]: The encoded JWT and the expiration.
  608. """
  609. now = _helpers.utcnow()
  610. lifetime = datetime.timedelta(seconds=self._token_lifetime)
  611. expiry = now + lifetime
  612. payload = {
  613. "iss": self._issuer,
  614. "sub": self._subject,
  615. "iat": _helpers.datetime_to_secs(now),
  616. "exp": _helpers.datetime_to_secs(expiry),
  617. "aud": audience,
  618. }
  619. payload.update(self._additional_claims)
  620. jwt = encode(self._signer, payload)
  621. return jwt, expiry
  622. def _get_jwt_for_audience(self, audience):
  623. """Get a JWT For a given audience.
  624. If there is already an existing, non-expired token in the cache for
  625. the audience, that token is used. Otherwise, a new token will be
  626. created.
  627. Args:
  628. audience (str): The intended audience.
  629. Returns:
  630. bytes: The encoded JWT.
  631. """
  632. token, expiry = self._cache.get(audience, (None, None))
  633. if token is None or expiry < _helpers.utcnow():
  634. token, expiry = self._make_jwt_for_audience(audience)
  635. self._cache[audience] = token, expiry
  636. return token
  637. def refresh(self, request):
  638. """Raises an exception, these credentials can not be directly
  639. refreshed.
  640. Args:
  641. request (Any): Unused.
  642. Raises:
  643. google.auth.RefreshError
  644. """
  645. # pylint: disable=unused-argument
  646. # (pylint doesn't correctly recognize overridden methods.)
  647. raise exceptions.RefreshError(
  648. "OnDemandCredentials can not be directly refreshed."
  649. )
  650. def before_request(self, request, method, url, headers):
  651. """Performs credential-specific before request logic.
  652. Args:
  653. request (Any): Unused. JWT credentials do not need to make an
  654. HTTP request to refresh.
  655. method (str): The request's HTTP method.
  656. url (str): The request's URI. This is used as the audience claim
  657. when generating the JWT.
  658. headers (Mapping): The request's headers.
  659. """
  660. # pylint: disable=unused-argument
  661. # (pylint doesn't correctly recognize overridden methods.)
  662. parts = urllib.parse.urlsplit(url)
  663. # Strip query string and fragment
  664. audience = urllib.parse.urlunsplit(
  665. (parts.scheme, parts.netloc, parts.path, "", "")
  666. )
  667. token = self._get_jwt_for_audience(audience)
  668. self.apply(headers, token=token)
  669. @_helpers.copy_docstring(google.auth.credentials.Signing)
  670. def sign_bytes(self, message):
  671. return self._signer.sign(message)
  672. @property
  673. @_helpers.copy_docstring(google.auth.credentials.Signing)
  674. def signer_email(self):
  675. return self._issuer
  676. @property
  677. @_helpers.copy_docstring(google.auth.credentials.Signing)
  678. def signer(self):
  679. return self._signer