oauth2_session.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. from __future__ import unicode_literals
  2. import logging
  3. from oauthlib.common import generate_token, urldecode
  4. from oauthlib.oauth2 import WebApplicationClient, InsecureTransportError
  5. from oauthlib.oauth2 import LegacyApplicationClient
  6. from oauthlib.oauth2 import TokenExpiredError, is_secure_transport
  7. import requests
  8. log = logging.getLogger(__name__)
  9. class TokenUpdated(Warning):
  10. def __init__(self, token):
  11. super(TokenUpdated, self).__init__()
  12. self.token = token
  13. class OAuth2Session(requests.Session):
  14. """Versatile OAuth 2 extension to :class:`requests.Session`.
  15. Supports any grant type adhering to :class:`oauthlib.oauth2.Client` spec
  16. including the four core OAuth 2 grants.
  17. Can be used to create authorization urls, fetch tokens and access protected
  18. resources using the :class:`requests.Session` interface you are used to.
  19. - :class:`oauthlib.oauth2.WebApplicationClient` (default): Authorization Code Grant
  20. - :class:`oauthlib.oauth2.MobileApplicationClient`: Implicit Grant
  21. - :class:`oauthlib.oauth2.LegacyApplicationClient`: Password Credentials Grant
  22. - :class:`oauthlib.oauth2.BackendApplicationClient`: Client Credentials Grant
  23. Note that the only time you will be using Implicit Grant from python is if
  24. you are driving a user agent able to obtain URL fragments.
  25. """
  26. def __init__(
  27. self,
  28. client_id=None,
  29. client=None,
  30. auto_refresh_url=None,
  31. auto_refresh_kwargs=None,
  32. scope=None,
  33. redirect_uri=None,
  34. token=None,
  35. state=None,
  36. token_updater=None,
  37. **kwargs
  38. ):
  39. """Construct a new OAuth 2 client session.
  40. :param client_id: Client id obtained during registration
  41. :param client: :class:`oauthlib.oauth2.Client` to be used. Default is
  42. WebApplicationClient which is useful for any
  43. hosted application but not mobile or desktop.
  44. :param scope: List of scopes you wish to request access to
  45. :param redirect_uri: Redirect URI you registered as callback
  46. :param token: Token dictionary, must include access_token
  47. and token_type.
  48. :param state: State string used to prevent CSRF. This will be given
  49. when creating the authorization url and must be supplied
  50. when parsing the authorization response.
  51. Can be either a string or a no argument callable.
  52. :auto_refresh_url: Refresh token endpoint URL, must be HTTPS. Supply
  53. this if you wish the client to automatically refresh
  54. your access tokens.
  55. :auto_refresh_kwargs: Extra arguments to pass to the refresh token
  56. endpoint.
  57. :token_updater: Method with one argument, token, to be used to update
  58. your token database on automatic token refresh. If not
  59. set a TokenUpdated warning will be raised when a token
  60. has been refreshed. This warning will carry the token
  61. in its token argument.
  62. :param kwargs: Arguments to pass to the Session constructor.
  63. """
  64. super(OAuth2Session, self).__init__(**kwargs)
  65. self._client = client or WebApplicationClient(client_id, token=token)
  66. self.token = token or {}
  67. self.scope = scope
  68. self.redirect_uri = redirect_uri
  69. self.state = state or generate_token
  70. self._state = state
  71. self.auto_refresh_url = auto_refresh_url
  72. self.auto_refresh_kwargs = auto_refresh_kwargs or {}
  73. self.token_updater = token_updater
  74. # Ensure that requests doesn't do any automatic auth. See #278.
  75. # The default behavior can be re-enabled by setting auth to None.
  76. self.auth = lambda r: r
  77. # Allow customizations for non compliant providers through various
  78. # hooks to adjust requests and responses.
  79. self.compliance_hook = {
  80. "access_token_response": set(),
  81. "refresh_token_response": set(),
  82. "protected_request": set(),
  83. }
  84. def new_state(self):
  85. """Generates a state string to be used in authorizations."""
  86. try:
  87. self._state = self.state()
  88. log.debug("Generated new state %s.", self._state)
  89. except TypeError:
  90. self._state = self.state
  91. log.debug("Re-using previously supplied state %s.", self._state)
  92. return self._state
  93. @property
  94. def client_id(self):
  95. return getattr(self._client, "client_id", None)
  96. @client_id.setter
  97. def client_id(self, value):
  98. self._client.client_id = value
  99. @client_id.deleter
  100. def client_id(self):
  101. del self._client.client_id
  102. @property
  103. def token(self):
  104. return getattr(self._client, "token", None)
  105. @token.setter
  106. def token(self, value):
  107. self._client.token = value
  108. self._client.populate_token_attributes(value)
  109. @property
  110. def access_token(self):
  111. return getattr(self._client, "access_token", None)
  112. @access_token.setter
  113. def access_token(self, value):
  114. self._client.access_token = value
  115. @access_token.deleter
  116. def access_token(self):
  117. del self._client.access_token
  118. @property
  119. def authorized(self):
  120. """Boolean that indicates whether this session has an OAuth token
  121. or not. If `self.authorized` is True, you can reasonably expect
  122. OAuth-protected requests to the resource to succeed. If
  123. `self.authorized` is False, you need the user to go through the OAuth
  124. authentication dance before OAuth-protected requests to the resource
  125. will succeed.
  126. """
  127. return bool(self.access_token)
  128. def authorization_url(self, url, state=None, **kwargs):
  129. """Form an authorization URL.
  130. :param url: Authorization endpoint url, must be HTTPS.
  131. :param state: An optional state string for CSRF protection. If not
  132. given it will be generated for you.
  133. :param kwargs: Extra parameters to include.
  134. :return: authorization_url, state
  135. """
  136. state = state or self.new_state()
  137. return (
  138. self._client.prepare_request_uri(
  139. url,
  140. redirect_uri=self.redirect_uri,
  141. scope=self.scope,
  142. state=state,
  143. **kwargs
  144. ),
  145. state,
  146. )
  147. def fetch_token(
  148. self,
  149. token_url,
  150. code=None,
  151. authorization_response=None,
  152. body="",
  153. auth=None,
  154. username=None,
  155. password=None,
  156. method="POST",
  157. force_querystring=False,
  158. timeout=None,
  159. headers=None,
  160. verify=True,
  161. proxies=None,
  162. include_client_id=None,
  163. client_secret=None,
  164. cert=None,
  165. **kwargs
  166. ):
  167. """Generic method for fetching an access token from the token endpoint.
  168. If you are using the MobileApplicationClient you will want to use
  169. `token_from_fragment` instead of `fetch_token`.
  170. The current implementation enforces the RFC guidelines.
  171. :param token_url: Token endpoint URL, must use HTTPS.
  172. :param code: Authorization code (used by WebApplicationClients).
  173. :param authorization_response: Authorization response URL, the callback
  174. URL of the request back to you. Used by
  175. WebApplicationClients instead of code.
  176. :param body: Optional application/x-www-form-urlencoded body to add the
  177. include in the token request. Prefer kwargs over body.
  178. :param auth: An auth tuple or method as accepted by `requests`.
  179. :param username: Username required by LegacyApplicationClients to appear
  180. in the request body.
  181. :param password: Password required by LegacyApplicationClients to appear
  182. in the request body.
  183. :param method: The HTTP method used to make the request. Defaults
  184. to POST, but may also be GET. Other methods should
  185. be added as needed.
  186. :param force_querystring: If True, force the request body to be sent
  187. in the querystring instead.
  188. :param timeout: Timeout of the request in seconds.
  189. :param headers: Dict to default request headers with.
  190. :param verify: Verify SSL certificate.
  191. :param proxies: The `proxies` argument is passed onto `requests`.
  192. :param include_client_id: Should the request body include the
  193. `client_id` parameter. Default is `None`,
  194. which will attempt to autodetect. This can be
  195. forced to always include (True) or never
  196. include (False).
  197. :param client_secret: The `client_secret` paired to the `client_id`.
  198. This is generally required unless provided in the
  199. `auth` tuple. If the value is `None`, it will be
  200. omitted from the request, however if the value is
  201. an empty string, an empty string will be sent.
  202. :param cert: Client certificate to send for OAuth 2.0 Mutual-TLS Client
  203. Authentication (draft-ietf-oauth-mtls). Can either be the
  204. path of a file containing the private key and certificate or
  205. a tuple of two filenames for certificate and key.
  206. :param kwargs: Extra parameters to include in the token request.
  207. :return: A token dict
  208. """
  209. if not is_secure_transport(token_url):
  210. raise InsecureTransportError()
  211. if not code and authorization_response:
  212. self._client.parse_request_uri_response(
  213. authorization_response, state=self._state
  214. )
  215. code = self._client.code
  216. elif not code and isinstance(self._client, WebApplicationClient):
  217. code = self._client.code
  218. if not code:
  219. raise ValueError(
  220. "Please supply either code or " "authorization_response parameters."
  221. )
  222. # Earlier versions of this library build an HTTPBasicAuth header out of
  223. # `username` and `password`. The RFC states, however these attributes
  224. # must be in the request body and not the header.
  225. # If an upstream server is not spec compliant and requires them to
  226. # appear as an Authorization header, supply an explicit `auth` header
  227. # to this function.
  228. # This check will allow for empty strings, but not `None`.
  229. #
  230. # References
  231. # 4.3.2 - Resource Owner Password Credentials Grant
  232. # https://tools.ietf.org/html/rfc6749#section-4.3.2
  233. if isinstance(self._client, LegacyApplicationClient):
  234. if username is None:
  235. raise ValueError(
  236. "`LegacyApplicationClient` requires both the "
  237. "`username` and `password` parameters."
  238. )
  239. if password is None:
  240. raise ValueError(
  241. "The required parameter `username` was supplied, "
  242. "but `password` was not."
  243. )
  244. # merge username and password into kwargs for `prepare_request_body`
  245. if username is not None:
  246. kwargs["username"] = username
  247. if password is not None:
  248. kwargs["password"] = password
  249. # is an auth explicitly supplied?
  250. if auth is not None:
  251. # if we're dealing with the default of `include_client_id` (None):
  252. # we will assume the `auth` argument is for an RFC compliant server
  253. # and we should not send the `client_id` in the body.
  254. # This approach allows us to still force the client_id by submitting
  255. # `include_client_id=True` along with an `auth` object.
  256. if include_client_id is None:
  257. include_client_id = False
  258. # otherwise we may need to create an auth header
  259. else:
  260. # since we don't have an auth header, we MAY need to create one
  261. # it is possible that we want to send the `client_id` in the body
  262. # if so, `include_client_id` should be set to True
  263. # otherwise, we will generate an auth header
  264. if include_client_id is not True:
  265. client_id = self.client_id
  266. if client_id:
  267. log.debug(
  268. 'Encoding `client_id` "%s" with `client_secret` '
  269. "as Basic auth credentials.",
  270. client_id,
  271. )
  272. client_secret = client_secret if client_secret is not None else ""
  273. auth = requests.auth.HTTPBasicAuth(client_id, client_secret)
  274. if include_client_id:
  275. # this was pulled out of the params
  276. # it needs to be passed into prepare_request_body
  277. if client_secret is not None:
  278. kwargs["client_secret"] = client_secret
  279. body = self._client.prepare_request_body(
  280. code=code,
  281. body=body,
  282. redirect_uri=self.redirect_uri,
  283. include_client_id=include_client_id,
  284. **kwargs
  285. )
  286. headers = headers or {
  287. "Accept": "application/json",
  288. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  289. }
  290. self.token = {}
  291. request_kwargs = {}
  292. if method.upper() == "POST":
  293. request_kwargs["params" if force_querystring else "data"] = dict(
  294. urldecode(body)
  295. )
  296. elif method.upper() == "GET":
  297. request_kwargs["params"] = dict(urldecode(body))
  298. else:
  299. raise ValueError("The method kwarg must be POST or GET.")
  300. r = self.request(
  301. method=method,
  302. url=token_url,
  303. timeout=timeout,
  304. headers=headers,
  305. auth=auth,
  306. verify=verify,
  307. proxies=proxies,
  308. cert=cert,
  309. **request_kwargs
  310. )
  311. log.debug("Request to fetch token completed with status %s.", r.status_code)
  312. log.debug("Request url was %s", r.request.url)
  313. log.debug("Request headers were %s", r.request.headers)
  314. log.debug("Request body was %s", r.request.body)
  315. log.debug("Response headers were %s and content %s.", r.headers, r.text)
  316. log.debug(
  317. "Invoking %d token response hooks.",
  318. len(self.compliance_hook["access_token_response"]),
  319. )
  320. for hook in self.compliance_hook["access_token_response"]:
  321. log.debug("Invoking hook %s.", hook)
  322. r = hook(r)
  323. self._client.parse_request_body_response(r.text, scope=self.scope)
  324. self.token = self._client.token
  325. log.debug("Obtained token %s.", self.token)
  326. return self.token
  327. def token_from_fragment(self, authorization_response):
  328. """Parse token from the URI fragment, used by MobileApplicationClients.
  329. :param authorization_response: The full URL of the redirect back to you
  330. :return: A token dict
  331. """
  332. self._client.parse_request_uri_response(
  333. authorization_response, state=self._state
  334. )
  335. self.token = self._client.token
  336. return self.token
  337. def refresh_token(
  338. self,
  339. token_url,
  340. refresh_token=None,
  341. body="",
  342. auth=None,
  343. timeout=None,
  344. headers=None,
  345. verify=True,
  346. proxies=None,
  347. **kwargs
  348. ):
  349. """Fetch a new access token using a refresh token.
  350. :param token_url: The token endpoint, must be HTTPS.
  351. :param refresh_token: The refresh_token to use.
  352. :param body: Optional application/x-www-form-urlencoded body to add the
  353. include in the token request. Prefer kwargs over body.
  354. :param auth: An auth tuple or method as accepted by `requests`.
  355. :param timeout: Timeout of the request in seconds.
  356. :param headers: A dict of headers to be used by `requests`.
  357. :param verify: Verify SSL certificate.
  358. :param proxies: The `proxies` argument will be passed to `requests`.
  359. :param kwargs: Extra parameters to include in the token request.
  360. :return: A token dict
  361. """
  362. if not token_url:
  363. raise ValueError("No token endpoint set for auto_refresh.")
  364. if not is_secure_transport(token_url):
  365. raise InsecureTransportError()
  366. refresh_token = refresh_token or self.token.get("refresh_token")
  367. log.debug(
  368. "Adding auto refresh key word arguments %s.", self.auto_refresh_kwargs
  369. )
  370. kwargs.update(self.auto_refresh_kwargs)
  371. body = self._client.prepare_refresh_body(
  372. body=body, refresh_token=refresh_token, scope=self.scope, **kwargs
  373. )
  374. log.debug("Prepared refresh token request body %s", body)
  375. if headers is None:
  376. headers = {
  377. "Accept": "application/json",
  378. "Content-Type": ("application/x-www-form-urlencoded;charset=UTF-8"),
  379. }
  380. r = self.post(
  381. token_url,
  382. data=dict(urldecode(body)),
  383. auth=auth,
  384. timeout=timeout,
  385. headers=headers,
  386. verify=verify,
  387. withhold_token=True,
  388. proxies=proxies,
  389. )
  390. log.debug("Request to refresh token completed with status %s.", r.status_code)
  391. log.debug("Response headers were %s and content %s.", r.headers, r.text)
  392. log.debug(
  393. "Invoking %d token response hooks.",
  394. len(self.compliance_hook["refresh_token_response"]),
  395. )
  396. for hook in self.compliance_hook["refresh_token_response"]:
  397. log.debug("Invoking hook %s.", hook)
  398. r = hook(r)
  399. self.token = self._client.parse_request_body_response(r.text, scope=self.scope)
  400. if not "refresh_token" in self.token:
  401. log.debug("No new refresh token given. Re-using old.")
  402. self.token["refresh_token"] = refresh_token
  403. return self.token
  404. def request(
  405. self,
  406. method,
  407. url,
  408. data=None,
  409. headers=None,
  410. withhold_token=False,
  411. client_id=None,
  412. client_secret=None,
  413. **kwargs
  414. ):
  415. """Intercept all requests and add the OAuth 2 token if present."""
  416. if not is_secure_transport(url):
  417. raise InsecureTransportError()
  418. if self.token and not withhold_token:
  419. log.debug(
  420. "Invoking %d protected resource request hooks.",
  421. len(self.compliance_hook["protected_request"]),
  422. )
  423. for hook in self.compliance_hook["protected_request"]:
  424. log.debug("Invoking hook %s.", hook)
  425. url, headers, data = hook(url, headers, data)
  426. log.debug("Adding token %s to request.", self.token)
  427. try:
  428. url, headers, data = self._client.add_token(
  429. url, http_method=method, body=data, headers=headers
  430. )
  431. # Attempt to retrieve and save new access token if expired
  432. except TokenExpiredError:
  433. if self.auto_refresh_url:
  434. log.debug(
  435. "Auto refresh is set, attempting to refresh at %s.",
  436. self.auto_refresh_url,
  437. )
  438. # We mustn't pass auth twice.
  439. auth = kwargs.pop("auth", None)
  440. if client_id and client_secret and (auth is None):
  441. log.debug(
  442. 'Encoding client_id "%s" with client_secret as Basic auth credentials.',
  443. client_id,
  444. )
  445. auth = requests.auth.HTTPBasicAuth(client_id, client_secret)
  446. token = self.refresh_token(
  447. self.auto_refresh_url, auth=auth, **kwargs
  448. )
  449. if self.token_updater:
  450. log.debug(
  451. "Updating token to %s using %s.", token, self.token_updater
  452. )
  453. self.token_updater(token)
  454. url, headers, data = self._client.add_token(
  455. url, http_method=method, body=data, headers=headers
  456. )
  457. else:
  458. raise TokenUpdated(token)
  459. else:
  460. raise
  461. log.debug("Requesting url %s using method %s.", url, method)
  462. log.debug("Supplying headers %s and data %s", headers, data)
  463. log.debug("Passing through key word arguments %s.", kwargs)
  464. return super(OAuth2Session, self).request(
  465. method, url, headers=headers, data=data, **kwargs
  466. )
  467. def register_compliance_hook(self, hook_type, hook):
  468. """Register a hook for request/response tweaking.
  469. Available hooks are:
  470. access_token_response invoked before token parsing.
  471. refresh_token_response invoked before refresh token parsing.
  472. protected_request invoked before making a request.
  473. If you find a new hook is needed please send a GitHub PR request
  474. or open an issue.
  475. """
  476. if hook_type not in self.compliance_hook:
  477. raise ValueError(
  478. "Hook type %s is not in %s.", hook_type, self.compliance_hook
  479. )
  480. self.compliance_hook[hook_type].add(hook)