_id_token_async.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. # Copyright 2020 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. """Google ID Token helpers.
  15. Provides support for verifying `OpenID Connect ID Tokens`_, especially ones
  16. generated by Google infrastructure.
  17. To parse and verify an ID Token issued by Google's OAuth 2.0 authorization
  18. server use :func:`verify_oauth2_token`. To verify an ID Token issued by
  19. Firebase, use :func:`verify_firebase_token`.
  20. A general purpose ID Token verifier is available as :func:`verify_token`.
  21. Example::
  22. from google.oauth2 import _id_token_async
  23. from google.auth.transport import aiohttp_requests
  24. request = aiohttp_requests.Request()
  25. id_info = await _id_token_async.verify_oauth2_token(
  26. token, request, 'my-client-id.example.com')
  27. if id_info['iss'] != 'https://accounts.google.com':
  28. raise ValueError('Wrong issuer.')
  29. userid = id_info['sub']
  30. By default, this will re-fetch certificates for each verification. Because
  31. Google's public keys are only changed infrequently (on the order of once per
  32. day), you may wish to take advantage of caching to reduce latency and the
  33. potential for network errors. This can be accomplished using an external
  34. library like `CacheControl`_ to create a cache-aware
  35. :class:`google.auth.transport.Request`::
  36. import cachecontrol
  37. import google.auth.transport.requests
  38. import requests
  39. session = requests.session()
  40. cached_session = cachecontrol.CacheControl(session)
  41. request = google.auth.transport.requests.Request(session=cached_session)
  42. .. _OpenID Connect ID Token:
  43. http://openid.net/specs/openid-connect-core-1_0.html#IDToken
  44. .. _CacheControl: https://cachecontrol.readthedocs.io
  45. """
  46. import http.client as http_client
  47. import json
  48. import os
  49. from google.auth import environment_vars
  50. from google.auth import exceptions
  51. from google.auth import jwt
  52. from google.auth.transport import requests
  53. from google.oauth2 import id_token as sync_id_token
  54. async def _fetch_certs(request, certs_url):
  55. """Fetches certificates.
  56. Google-style cerificate endpoints return JSON in the format of
  57. ``{'key id': 'x509 certificate'}``.
  58. Args:
  59. request (google.auth.transport.Request): The object used to make
  60. HTTP requests. This must be an aiohttp request.
  61. certs_url (str): The certificate endpoint URL.
  62. Returns:
  63. Mapping[str, str]: A mapping of public key ID to x.509 certificate
  64. data.
  65. """
  66. response = await request(certs_url, method="GET")
  67. if response.status != http_client.OK:
  68. raise exceptions.TransportError(
  69. "Could not fetch certificates at {}".format(certs_url)
  70. )
  71. data = await response.content()
  72. return json.loads(data)
  73. async def verify_token(
  74. id_token,
  75. request,
  76. audience=None,
  77. certs_url=sync_id_token._GOOGLE_OAUTH2_CERTS_URL,
  78. clock_skew_in_seconds=0,
  79. ):
  80. """Verifies an ID token and returns the decoded token.
  81. Args:
  82. id_token (Union[str, bytes]): The encoded token.
  83. request (google.auth.transport.Request): The object used to make
  84. HTTP requests. This must be an aiohttp request.
  85. audience (str): The audience that this token is intended for. If None
  86. then the audience is not verified.
  87. certs_url (str): The URL that specifies the certificates to use to
  88. verify the token. This URL should return JSON in the format of
  89. ``{'key id': 'x509 certificate'}``.
  90. clock_skew_in_seconds (int): The clock skew used for `iat` and `exp`
  91. validation.
  92. Returns:
  93. Mapping[str, Any]: The decoded token.
  94. """
  95. certs = await _fetch_certs(request, certs_url)
  96. return jwt.decode(
  97. id_token,
  98. certs=certs,
  99. audience=audience,
  100. clock_skew_in_seconds=clock_skew_in_seconds,
  101. )
  102. async def verify_oauth2_token(
  103. id_token, request, audience=None, clock_skew_in_seconds=0
  104. ):
  105. """Verifies an ID Token issued by Google's OAuth 2.0 authorization server.
  106. Args:
  107. id_token (Union[str, bytes]): The encoded token.
  108. request (google.auth.transport.Request): The object used to make
  109. HTTP requests. This must be an aiohttp request.
  110. audience (str): The audience that this token is intended for. This is
  111. typically your application's OAuth 2.0 client ID. If None then the
  112. audience is not verified.
  113. clock_skew_in_seconds (int): The clock skew used for `iat` and `exp`
  114. validation.
  115. Returns:
  116. Mapping[str, Any]: The decoded token.
  117. Raises:
  118. exceptions.GoogleAuthError: If the issuer is invalid.
  119. """
  120. idinfo = await verify_token(
  121. id_token,
  122. request,
  123. audience=audience,
  124. certs_url=sync_id_token._GOOGLE_OAUTH2_CERTS_URL,
  125. clock_skew_in_seconds=clock_skew_in_seconds,
  126. )
  127. if idinfo["iss"] not in sync_id_token._GOOGLE_ISSUERS:
  128. raise exceptions.GoogleAuthError(
  129. "Wrong issuer. 'iss' should be one of the following: {}".format(
  130. sync_id_token._GOOGLE_ISSUERS
  131. )
  132. )
  133. return idinfo
  134. async def verify_firebase_token(
  135. id_token, request, audience=None, clock_skew_in_seconds=0
  136. ):
  137. """Verifies an ID Token issued by Firebase Authentication.
  138. Args:
  139. id_token (Union[str, bytes]): The encoded token.
  140. request (google.auth.transport.Request): The object used to make
  141. HTTP requests. This must be an aiohttp request.
  142. audience (str): The audience that this token is intended for. This is
  143. typically your Firebase application ID. If None then the audience
  144. is not verified.
  145. clock_skew_in_seconds (int): The clock skew used for `iat` and `exp`
  146. validation.
  147. Returns:
  148. Mapping[str, Any]: The decoded token.
  149. """
  150. return await verify_token(
  151. id_token,
  152. request,
  153. audience=audience,
  154. certs_url=sync_id_token._GOOGLE_APIS_CERTS_URL,
  155. clock_skew_in_seconds=clock_skew_in_seconds,
  156. )
  157. async def fetch_id_token(request, audience):
  158. """Fetch the ID Token from the current environment.
  159. This function acquires ID token from the environment in the following order.
  160. See https://google.aip.dev/auth/4110.
  161. 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set
  162. to the path of a valid service account JSON file, then ID token is
  163. acquired using this service account credentials.
  164. 2. If the application is running in Compute Engine, App Engine or Cloud Run,
  165. then the ID token are obtained from the metadata server.
  166. 3. If metadata server doesn't exist and no valid service account credentials
  167. are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will
  168. be raised.
  169. Example::
  170. import google.oauth2._id_token_async
  171. import google.auth.transport.aiohttp_requests
  172. request = google.auth.transport.aiohttp_requests.Request()
  173. target_audience = "https://pubsub.googleapis.com"
  174. id_token = await google.oauth2._id_token_async.fetch_id_token(request, target_audience)
  175. Args:
  176. request (google.auth.transport.aiohttp_requests.Request): A callable used to make
  177. HTTP requests.
  178. audience (str): The audience that this ID token is intended for.
  179. Returns:
  180. str: The ID token.
  181. Raises:
  182. ~google.auth.exceptions.DefaultCredentialsError:
  183. If metadata server doesn't exist and no valid service account
  184. credentials are found.
  185. """
  186. # 1. Try to get credentials from the GOOGLE_APPLICATION_CREDENTIALS environment
  187. # variable.
  188. credentials_filename = os.environ.get(environment_vars.CREDENTIALS)
  189. if credentials_filename:
  190. if not (
  191. os.path.exists(credentials_filename)
  192. and os.path.isfile(credentials_filename)
  193. ):
  194. raise exceptions.DefaultCredentialsError(
  195. "GOOGLE_APPLICATION_CREDENTIALS path is either not found or invalid."
  196. )
  197. try:
  198. with open(credentials_filename, "r") as f:
  199. from google.oauth2 import _service_account_async as service_account
  200. info = json.load(f)
  201. if info.get("type") == "service_account":
  202. credentials = service_account.IDTokenCredentials.from_service_account_info(
  203. info, target_audience=audience
  204. )
  205. await credentials.refresh(request)
  206. return credentials.token
  207. except ValueError as caught_exc:
  208. new_exc = exceptions.DefaultCredentialsError(
  209. "GOOGLE_APPLICATION_CREDENTIALS is not valid service account credentials.",
  210. caught_exc,
  211. )
  212. raise new_exc from caught_exc
  213. # 2. Try to fetch ID token from metada server if it exists. The code works
  214. # for GAE and Cloud Run metadata server as well.
  215. try:
  216. from google.auth import compute_engine
  217. from google.auth.compute_engine import _metadata
  218. request_new = requests.Request()
  219. if _metadata.ping(request_new):
  220. credentials = compute_engine.IDTokenCredentials(
  221. request_new, audience, use_metadata_identity_endpoint=True
  222. )
  223. credentials.refresh(request_new)
  224. return credentials.token
  225. except (ImportError, exceptions.TransportError):
  226. pass
  227. raise exceptions.DefaultCredentialsError(
  228. "Neither metadata server or valid service account credentials are found."
  229. )