jwt.py 30 KB

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