_client.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. """OAuth 2.0 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 json
  23. import six
  24. from six.moves import http_client
  25. from six.moves import urllib
  26. from google.auth import _helpers
  27. from google.auth import exceptions
  28. from google.auth import jwt
  29. _URLENCODED_CONTENT_TYPE = "application/x-www-form-urlencoded"
  30. _JSON_CONTENT_TYPE = "application/json"
  31. _JWT_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"
  32. _REFRESH_GRANT_TYPE = "refresh_token"
  33. def _handle_error_response(response_data):
  34. """Translates an error response into an exception.
  35. Args:
  36. response_data (Mapping): The decoded response data.
  37. Raises:
  38. google.auth.exceptions.RefreshError: The errors contained in response_data.
  39. """
  40. try:
  41. error_details = "{}: {}".format(
  42. response_data["error"], response_data.get("error_description")
  43. )
  44. # If no details could be extracted, use the response data.
  45. except (KeyError, ValueError):
  46. error_details = json.dumps(response_data)
  47. raise exceptions.RefreshError(error_details, response_data)
  48. def _parse_expiry(response_data):
  49. """Parses the expiry field from a response into a datetime.
  50. Args:
  51. response_data (Mapping): The JSON-parsed response data.
  52. Returns:
  53. Optional[datetime]: The expiration or ``None`` if no expiration was
  54. specified.
  55. """
  56. expires_in = response_data.get("expires_in", None)
  57. if expires_in is not None:
  58. return _helpers.utcnow() + datetime.timedelta(seconds=expires_in)
  59. else:
  60. return None
  61. def _token_endpoint_request_no_throw(
  62. request, token_uri, body, access_token=None, use_json=False
  63. ):
  64. """Makes a request to the OAuth 2.0 authorization server's token endpoint.
  65. This function doesn't throw on response errors.
  66. Args:
  67. request (google.auth.transport.Request): A callable used to make
  68. HTTP requests.
  69. token_uri (str): The OAuth 2.0 authorizations server's token endpoint
  70. URI.
  71. body (Mapping[str, str]): The parameters to send in the request body.
  72. access_token (Optional(str)): The access token needed to make the request.
  73. use_json (Optional(bool)): Use urlencoded format or json format for the
  74. content type. The default value is False.
  75. Returns:
  76. Tuple(bool, Mapping[str, str]): A boolean indicating if the request is
  77. successful, and a mapping for the JSON-decoded response data.
  78. """
  79. if use_json:
  80. headers = {"Content-Type": _JSON_CONTENT_TYPE}
  81. body = json.dumps(body).encode("utf-8")
  82. else:
  83. headers = {"Content-Type": _URLENCODED_CONTENT_TYPE}
  84. body = urllib.parse.urlencode(body).encode("utf-8")
  85. if access_token:
  86. headers["Authorization"] = "Bearer {}".format(access_token)
  87. retry = 0
  88. # retry to fetch token for maximum of two times if any internal failure
  89. # occurs.
  90. while True:
  91. response = request(method="POST", url=token_uri, headers=headers, body=body)
  92. response_body = (
  93. response.data.decode("utf-8")
  94. if hasattr(response.data, "decode")
  95. else response.data
  96. )
  97. response_data = json.loads(response_body)
  98. if response.status == http_client.OK:
  99. break
  100. else:
  101. error_desc = response_data.get("error_description") or ""
  102. error_code = response_data.get("error") or ""
  103. if (
  104. any(e == "internal_failure" for e in (error_code, error_desc))
  105. and retry < 1
  106. ):
  107. retry += 1
  108. continue
  109. return response.status == http_client.OK, response_data
  110. return response.status == http_client.OK, response_data
  111. def _token_endpoint_request(
  112. request, token_uri, body, access_token=None, use_json=False
  113. ):
  114. """Makes a request to the OAuth 2.0 authorization server's token endpoint.
  115. Args:
  116. request (google.auth.transport.Request): A callable used to make
  117. HTTP requests.
  118. token_uri (str): The OAuth 2.0 authorizations server's token endpoint
  119. URI.
  120. body (Mapping[str, str]): The parameters to send in the request body.
  121. access_token (Optional(str)): The access token needed to make the request.
  122. use_json (Optional(bool)): Use urlencoded format or json format for the
  123. content type. The default value is False.
  124. Returns:
  125. Mapping[str, str]: The JSON-decoded response data.
  126. Raises:
  127. google.auth.exceptions.RefreshError: If the token endpoint returned
  128. an error.
  129. """
  130. response_status_ok, response_data = _token_endpoint_request_no_throw(
  131. request, token_uri, body, access_token=access_token, use_json=use_json
  132. )
  133. if not response_status_ok:
  134. _handle_error_response(response_data)
  135. return response_data
  136. def jwt_grant(request, token_uri, assertion):
  137. """Implements the JWT Profile for OAuth 2.0 Authorization Grants.
  138. For more details, see `rfc7523 section 4`_.
  139. Args:
  140. request (google.auth.transport.Request): A callable used to make
  141. HTTP requests.
  142. token_uri (str): The OAuth 2.0 authorizations server's token endpoint
  143. URI.
  144. assertion (str): The OAuth 2.0 assertion.
  145. Returns:
  146. Tuple[str, Optional[datetime], Mapping[str, str]]: The access token,
  147. expiration, and additional data returned by the token endpoint.
  148. Raises:
  149. google.auth.exceptions.RefreshError: If the token endpoint returned
  150. an error.
  151. .. _rfc7523 section 4: https://tools.ietf.org/html/rfc7523#section-4
  152. """
  153. body = {"assertion": assertion, "grant_type": _JWT_GRANT_TYPE}
  154. response_data = _token_endpoint_request(request, token_uri, body)
  155. try:
  156. access_token = response_data["access_token"]
  157. except KeyError as caught_exc:
  158. new_exc = exceptions.RefreshError("No access token in response.", response_data)
  159. six.raise_from(new_exc, caught_exc)
  160. expiry = _parse_expiry(response_data)
  161. return access_token, expiry, response_data
  162. def id_token_jwt_grant(request, token_uri, assertion):
  163. """Implements the JWT Profile for OAuth 2.0 Authorization Grants, but
  164. requests an OpenID Connect ID Token instead of an access token.
  165. This is a variant on the standard JWT Profile that is currently unique
  166. to Google. This was added for the benefit of authenticating to services
  167. that require ID Tokens instead of access tokens or JWT bearer tokens.
  168. Args:
  169. request (google.auth.transport.Request): A callable used to make
  170. HTTP requests.
  171. token_uri (str): The OAuth 2.0 authorization server's token endpoint
  172. URI.
  173. assertion (str): JWT token signed by a service account. The token's
  174. payload must include a ``target_audience`` claim.
  175. Returns:
  176. Tuple[str, Optional[datetime], Mapping[str, str]]:
  177. The (encoded) Open ID Connect ID Token, expiration, and additional
  178. data returned by the endpoint.
  179. Raises:
  180. google.auth.exceptions.RefreshError: If the token endpoint returned
  181. an error.
  182. """
  183. body = {"assertion": assertion, "grant_type": _JWT_GRANT_TYPE}
  184. response_data = _token_endpoint_request(request, token_uri, body)
  185. try:
  186. id_token = response_data["id_token"]
  187. except KeyError as caught_exc:
  188. new_exc = exceptions.RefreshError("No ID token in response.", response_data)
  189. six.raise_from(new_exc, caught_exc)
  190. payload = jwt.decode(id_token, verify=False)
  191. expiry = datetime.datetime.utcfromtimestamp(payload["exp"])
  192. return id_token, expiry, response_data
  193. def _handle_refresh_grant_response(response_data, refresh_token):
  194. """Extract tokens from refresh grant response.
  195. Args:
  196. response_data (Mapping[str, str]): Refresh grant response data.
  197. refresh_token (str): Current refresh token.
  198. Returns:
  199. Tuple[str, str, Optional[datetime], Mapping[str, str]]: The access token,
  200. refresh token, expiration, and additional data returned by the token
  201. endpoint. If response_data doesn't have refresh token, then the current
  202. refresh token will be returned.
  203. Raises:
  204. google.auth.exceptions.RefreshError: If the token endpoint returned
  205. an error.
  206. """
  207. try:
  208. access_token = response_data["access_token"]
  209. except KeyError as caught_exc:
  210. new_exc = exceptions.RefreshError("No access token in response.", response_data)
  211. six.raise_from(new_exc, caught_exc)
  212. refresh_token = response_data.get("refresh_token", refresh_token)
  213. expiry = _parse_expiry(response_data)
  214. return access_token, refresh_token, expiry, response_data
  215. def refresh_grant(
  216. request,
  217. token_uri,
  218. refresh_token,
  219. client_id,
  220. client_secret,
  221. scopes=None,
  222. rapt_token=None,
  223. ):
  224. """Implements the OAuth 2.0 refresh token grant.
  225. For more details, see `rfc678 section 6`_.
  226. Args:
  227. request (google.auth.transport.Request): A callable used to make
  228. HTTP requests.
  229. token_uri (str): The OAuth 2.0 authorizations server's token endpoint
  230. URI.
  231. refresh_token (str): The refresh token to use to get a new access
  232. token.
  233. client_id (str): The OAuth 2.0 application's client ID.
  234. client_secret (str): The Oauth 2.0 appliaction's client secret.
  235. scopes (Optional(Sequence[str])): Scopes to request. If present, all
  236. scopes must be authorized for the refresh token. Useful if refresh
  237. token has a wild card scope (e.g.
  238. 'https://www.googleapis.com/auth/any-api').
  239. rapt_token (Optional(str)): The reauth Proof Token.
  240. Returns:
  241. Tuple[str, str, Optional[datetime], Mapping[str, str]]: The access
  242. token, new or current refresh token, expiration, and additional data
  243. returned by the token endpoint.
  244. Raises:
  245. google.auth.exceptions.RefreshError: If the token endpoint returned
  246. an error.
  247. .. _rfc6748 section 6: https://tools.ietf.org/html/rfc6749#section-6
  248. """
  249. body = {
  250. "grant_type": _REFRESH_GRANT_TYPE,
  251. "client_id": client_id,
  252. "client_secret": client_secret,
  253. "refresh_token": refresh_token,
  254. }
  255. if scopes:
  256. body["scope"] = " ".join(scopes)
  257. if rapt_token:
  258. body["rapt"] = rapt_token
  259. response_data = _token_endpoint_request(request, token_uri, body)
  260. return _handle_refresh_grant_response(response_data, refresh_token)