_client_async.py 10 KB

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