_client_async.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. """OAuth 2.0 async client.
  15. This is a client for interacting with an OAuth 2.0 authorization server's
  16. token endpoint.
  17. For more information about the token endpoint, see
  18. `Section 3.1 of rfc6749`_
  19. .. _Section 3.1 of rfc6749: https://tools.ietf.org/html/rfc6749#section-3.2
  20. """
  21. import datetime
  22. import http.client as http_client
  23. import json
  24. import urllib
  25. from google.auth import _exponential_backoff
  26. from google.auth import exceptions
  27. from google.auth import jwt
  28. from google.oauth2 import _client as client
  29. async def _token_endpoint_request_no_throw(
  30. request, token_uri, body, access_token=None, use_json=False, can_retry=True
  31. ):
  32. """Makes a request to the OAuth 2.0 authorization server's token endpoint.
  33. This function doesn't throw on response errors.
  34. Args:
  35. request (google.auth.transport.Request): A callable used to make
  36. HTTP requests.
  37. token_uri (str): The OAuth 2.0 authorizations server's token endpoint
  38. URI.
  39. body (Mapping[str, str]): The parameters to send in the request body.
  40. access_token (Optional(str)): The access token needed to make the request.
  41. use_json (Optional(bool)): Use urlencoded format or json format for the
  42. content type. The default value is False.
  43. can_retry (bool): Enable or disable request retry behavior.
  44. Returns:
  45. Tuple(bool, Mapping[str, str], Optional[bool]): A boolean indicating
  46. if the request is successful, a mapping for the JSON-decoded response
  47. data and in the case of an error a boolean indicating if the error
  48. is retryable.
  49. """
  50. if use_json:
  51. headers = {"Content-Type": client._JSON_CONTENT_TYPE}
  52. body = json.dumps(body).encode("utf-8")
  53. else:
  54. headers = {"Content-Type": client._URLENCODED_CONTENT_TYPE}
  55. body = urllib.parse.urlencode(body).encode("utf-8")
  56. if access_token:
  57. headers["Authorization"] = "Bearer {}".format(access_token)
  58. response_data = {}
  59. retryable_error = False
  60. retries = _exponential_backoff.ExponentialBackoff()
  61. for _ in retries:
  62. response = await request(
  63. method="POST", url=token_uri, headers=headers, body=body
  64. )
  65. # Using data.read() resulted in zlib decompression errors. This may require future investigation.
  66. response_body1 = await response.content()
  67. response_body = (
  68. response_body1.decode("utf-8")
  69. if hasattr(response_body1, "decode")
  70. else response_body1
  71. )
  72. try:
  73. response_data = json.loads(response_body)
  74. except ValueError:
  75. response_data = response_body
  76. if response.status == http_client.OK:
  77. return True, response_data, None
  78. retryable_error = client._can_retry(
  79. status_code=response.status, response_data=response_data
  80. )
  81. if not can_retry or not retryable_error:
  82. return False, response_data, retryable_error
  83. return False, response_data, retryable_error
  84. async def _token_endpoint_request(
  85. request, token_uri, body, access_token=None, use_json=False, can_retry=True
  86. ):
  87. """Makes a request to the OAuth 2.0 authorization server's token endpoint.
  88. Args:
  89. request (google.auth.transport.Request): A callable used to make
  90. HTTP requests.
  91. token_uri (str): The OAuth 2.0 authorizations server's token endpoint
  92. URI.
  93. body (Mapping[str, str]): The parameters to send in the request body.
  94. access_token (Optional(str)): The access token needed to make the request.
  95. use_json (Optional(bool)): Use urlencoded format or json format for the
  96. content type. The default value is False.
  97. can_retry (bool): Enable or disable request retry behavior.
  98. Returns:
  99. Mapping[str, str]: The JSON-decoded response data.
  100. Raises:
  101. google.auth.exceptions.RefreshError: If the token endpoint returned
  102. an error.
  103. """
  104. response_status_ok, response_data, retryable_error = await _token_endpoint_request_no_throw(
  105. request,
  106. token_uri,
  107. body,
  108. access_token=access_token,
  109. use_json=use_json,
  110. can_retry=can_retry,
  111. )
  112. if not response_status_ok:
  113. client._handle_error_response(response_data, retryable_error)
  114. return response_data
  115. async def jwt_grant(request, token_uri, assertion, can_retry=True):
  116. """Implements the JWT Profile for OAuth 2.0 Authorization Grants.
  117. For more details, see `rfc7523 section 4`_.
  118. Args:
  119. request (google.auth.transport.Request): A callable used to make
  120. HTTP requests.
  121. token_uri (str): The OAuth 2.0 authorizations server's token endpoint
  122. URI.
  123. assertion (str): The OAuth 2.0 assertion.
  124. can_retry (bool): Enable or disable request retry behavior.
  125. Returns:
  126. Tuple[str, Optional[datetime], Mapping[str, str]]: The access token,
  127. expiration, and additional data returned by the token endpoint.
  128. Raises:
  129. google.auth.exceptions.RefreshError: If the token endpoint returned
  130. an error.
  131. .. _rfc7523 section 4: https://tools.ietf.org/html/rfc7523#section-4
  132. """
  133. body = {"assertion": assertion, "grant_type": client._JWT_GRANT_TYPE}
  134. response_data = await _token_endpoint_request(
  135. request, token_uri, body, can_retry=can_retry
  136. )
  137. try:
  138. access_token = response_data["access_token"]
  139. except KeyError as caught_exc:
  140. new_exc = exceptions.RefreshError(
  141. "No access token in response.", response_data, retryable=False
  142. )
  143. raise new_exc from caught_exc
  144. expiry = client._parse_expiry(response_data)
  145. return access_token, expiry, response_data
  146. async def id_token_jwt_grant(request, token_uri, assertion, can_retry=True):
  147. """Implements the JWT Profile for OAuth 2.0 Authorization Grants, but
  148. requests an OpenID Connect ID Token instead of an access token.
  149. This is a variant on the standard JWT Profile that is currently unique
  150. to Google. This was added for the benefit of authenticating to services
  151. that require ID Tokens instead of access tokens or JWT bearer tokens.
  152. Args:
  153. request (google.auth.transport.Request): A callable used to make
  154. HTTP requests.
  155. token_uri (str): The OAuth 2.0 authorization server's token endpoint
  156. URI.
  157. assertion (str): JWT token signed by a service account. The token's
  158. payload must include a ``target_audience`` claim.
  159. can_retry (bool): Enable or disable request retry behavior.
  160. Returns:
  161. Tuple[str, Optional[datetime], Mapping[str, str]]:
  162. The (encoded) Open ID Connect ID Token, expiration, and additional
  163. data returned by the endpoint.
  164. Raises:
  165. google.auth.exceptions.RefreshError: If the token endpoint returned
  166. an error.
  167. """
  168. body = {"assertion": assertion, "grant_type": client._JWT_GRANT_TYPE}
  169. response_data = await _token_endpoint_request(
  170. request, token_uri, body, can_retry=can_retry
  171. )
  172. try:
  173. id_token = response_data["id_token"]
  174. except KeyError as caught_exc:
  175. new_exc = exceptions.RefreshError(
  176. "No ID token in response.", response_data, retryable=False
  177. )
  178. raise new_exc from caught_exc
  179. payload = jwt.decode(id_token, verify=False)
  180. expiry = datetime.datetime.utcfromtimestamp(payload["exp"])
  181. return id_token, expiry, response_data
  182. async def refresh_grant(
  183. request,
  184. token_uri,
  185. refresh_token,
  186. client_id,
  187. client_secret,
  188. scopes=None,
  189. rapt_token=None,
  190. can_retry=True,
  191. ):
  192. """Implements the OAuth 2.0 refresh token grant.
  193. For more details, see `rfc678 section 6`_.
  194. Args:
  195. request (google.auth.transport.Request): A callable used to make
  196. HTTP requests.
  197. token_uri (str): The OAuth 2.0 authorizations server's token endpoint
  198. URI.
  199. refresh_token (str): The refresh token to use to get a new access
  200. token.
  201. client_id (str): The OAuth 2.0 application's client ID.
  202. client_secret (str): The Oauth 2.0 appliaction's client secret.
  203. scopes (Optional(Sequence[str])): Scopes to request. If present, all
  204. scopes must be authorized for the refresh token. Useful if refresh
  205. token has a wild card scope (e.g.
  206. 'https://www.googleapis.com/auth/any-api').
  207. rapt_token (Optional(str)): The reauth Proof Token.
  208. can_retry (bool): Enable or disable request retry behavior.
  209. Returns:
  210. Tuple[str, Optional[str], Optional[datetime], Mapping[str, str]]: The
  211. access token, new or current refresh token, expiration, and additional data
  212. returned by the token endpoint.
  213. Raises:
  214. google.auth.exceptions.RefreshError: If the token endpoint returned
  215. an error.
  216. .. _rfc6748 section 6: https://tools.ietf.org/html/rfc6749#section-6
  217. """
  218. body = {
  219. "grant_type": client._REFRESH_GRANT_TYPE,
  220. "client_id": client_id,
  221. "client_secret": client_secret,
  222. "refresh_token": refresh_token,
  223. }
  224. if scopes:
  225. body["scope"] = " ".join(scopes)
  226. if rapt_token:
  227. body["rapt"] = rapt_token
  228. response_data = await _token_endpoint_request(
  229. request, token_uri, body, can_retry=can_retry
  230. )
  231. return client._handle_refresh_grant_response(response_data, refresh_token)