id_token.py 9.2 KB

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