jwt.py 30 KB

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