oauth1_session.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. from __future__ import unicode_literals
  2. try:
  3. from urlparse import urlparse
  4. except ImportError:
  5. from urllib.parse import urlparse
  6. import logging
  7. from oauthlib.common import add_params_to_uri
  8. from oauthlib.common import urldecode as _urldecode
  9. from oauthlib.oauth1 import SIGNATURE_HMAC, SIGNATURE_RSA, SIGNATURE_TYPE_AUTH_HEADER
  10. import requests
  11. from . import OAuth1
  12. log = logging.getLogger(__name__)
  13. def urldecode(body):
  14. """Parse query or json to python dictionary"""
  15. try:
  16. return _urldecode(body)
  17. except Exception:
  18. import json
  19. return json.loads(body)
  20. class TokenRequestDenied(ValueError):
  21. def __init__(self, message, response):
  22. super(TokenRequestDenied, self).__init__(message)
  23. self.response = response
  24. @property
  25. def status_code(self):
  26. """For backwards-compatibility purposes"""
  27. return self.response.status_code
  28. class TokenMissing(ValueError):
  29. def __init__(self, message, response):
  30. super(TokenMissing, self).__init__(message)
  31. self.response = response
  32. class VerifierMissing(ValueError):
  33. pass
  34. class OAuth1Session(requests.Session):
  35. """Request signing and convenience methods for the oauth dance.
  36. What is the difference between OAuth1Session and OAuth1?
  37. OAuth1Session actually uses OAuth1 internally and its purpose is to assist
  38. in the OAuth workflow through convenience methods to prepare authorization
  39. URLs and parse the various token and redirection responses. It also provide
  40. rudimentary validation of responses.
  41. An example of the OAuth workflow using a basic CLI app and Twitter.
  42. >>> # Credentials obtained during the registration.
  43. >>> client_key = 'client key'
  44. >>> client_secret = 'secret'
  45. >>> callback_uri = 'https://127.0.0.1/callback'
  46. >>>
  47. >>> # Endpoints found in the OAuth provider API documentation
  48. >>> request_token_url = 'https://api.twitter.com/oauth/request_token'
  49. >>> authorization_url = 'https://api.twitter.com/oauth/authorize'
  50. >>> access_token_url = 'https://api.twitter.com/oauth/access_token'
  51. >>>
  52. >>> oauth_session = OAuth1Session(client_key,client_secret=client_secret, callback_uri=callback_uri)
  53. >>>
  54. >>> # First step, fetch the request token.
  55. >>> oauth_session.fetch_request_token(request_token_url)
  56. {
  57. 'oauth_token': 'kjerht2309u',
  58. 'oauth_token_secret': 'lsdajfh923874',
  59. }
  60. >>>
  61. >>> # Second step. Follow this link and authorize
  62. >>> oauth_session.authorization_url(authorization_url)
  63. 'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&oauth_callback=https%3A%2F%2F127.0.0.1%2Fcallback'
  64. >>>
  65. >>> # Third step. Fetch the access token
  66. >>> redirect_response = raw_input('Paste the full redirect URL here.')
  67. >>> oauth_session.parse_authorization_response(redirect_response)
  68. {
  69. 'oauth_token: 'kjerht2309u',
  70. 'oauth_token_secret: 'lsdajfh923874',
  71. 'oauth_verifier: 'w34o8967345',
  72. }
  73. >>> oauth_session.fetch_access_token(access_token_url)
  74. {
  75. 'oauth_token': 'sdf0o9823sjdfsdf',
  76. 'oauth_token_secret': '2kjshdfp92i34asdasd',
  77. }
  78. >>> # Done. You can now make OAuth requests.
  79. >>> status_url = 'http://api.twitter.com/1/statuses/update.json'
  80. >>> new_status = {'status': 'hello world!'}
  81. >>> oauth_session.post(status_url, data=new_status)
  82. <Response [200]>
  83. """
  84. def __init__(
  85. self,
  86. client_key,
  87. client_secret=None,
  88. resource_owner_key=None,
  89. resource_owner_secret=None,
  90. callback_uri=None,
  91. signature_method=SIGNATURE_HMAC,
  92. signature_type=SIGNATURE_TYPE_AUTH_HEADER,
  93. rsa_key=None,
  94. verifier=None,
  95. client_class=None,
  96. force_include_body=False,
  97. **kwargs
  98. ):
  99. """Construct the OAuth 1 session.
  100. :param client_key: A client specific identifier.
  101. :param client_secret: A client specific secret used to create HMAC and
  102. plaintext signatures.
  103. :param resource_owner_key: A resource owner key, also referred to as
  104. request token or access token depending on
  105. when in the workflow it is used.
  106. :param resource_owner_secret: A resource owner secret obtained with
  107. either a request or access token. Often
  108. referred to as token secret.
  109. :param callback_uri: The URL the user is redirect back to after
  110. authorization.
  111. :param signature_method: Signature methods determine how the OAuth
  112. signature is created. The three options are
  113. oauthlib.oauth1.SIGNATURE_HMAC (default),
  114. oauthlib.oauth1.SIGNATURE_RSA and
  115. oauthlib.oauth1.SIGNATURE_PLAIN.
  116. :param signature_type: Signature type decides where the OAuth
  117. parameters are added. Either in the
  118. Authorization header (default) or to the URL
  119. query parameters or the request body. Defined as
  120. oauthlib.oauth1.SIGNATURE_TYPE_AUTH_HEADER,
  121. oauthlib.oauth1.SIGNATURE_TYPE_QUERY and
  122. oauthlib.oauth1.SIGNATURE_TYPE_BODY
  123. respectively.
  124. :param rsa_key: The private RSA key as a string. Can only be used with
  125. signature_method=oauthlib.oauth1.SIGNATURE_RSA.
  126. :param verifier: A verifier string to prove authorization was granted.
  127. :param client_class: A subclass of `oauthlib.oauth1.Client` to use with
  128. `requests_oauthlib.OAuth1` instead of the default
  129. :param force_include_body: Always include the request body in the
  130. signature creation.
  131. :param **kwargs: Additional keyword arguments passed to `OAuth1`
  132. """
  133. super(OAuth1Session, self).__init__()
  134. self._client = OAuth1(
  135. client_key,
  136. client_secret=client_secret,
  137. resource_owner_key=resource_owner_key,
  138. resource_owner_secret=resource_owner_secret,
  139. callback_uri=callback_uri,
  140. signature_method=signature_method,
  141. signature_type=signature_type,
  142. rsa_key=rsa_key,
  143. verifier=verifier,
  144. client_class=client_class,
  145. force_include_body=force_include_body,
  146. **kwargs
  147. )
  148. self.auth = self._client
  149. @property
  150. def token(self):
  151. oauth_token = self._client.client.resource_owner_key
  152. oauth_token_secret = self._client.client.resource_owner_secret
  153. oauth_verifier = self._client.client.verifier
  154. token_dict = {}
  155. if oauth_token:
  156. token_dict["oauth_token"] = oauth_token
  157. if oauth_token_secret:
  158. token_dict["oauth_token_secret"] = oauth_token_secret
  159. if oauth_verifier:
  160. token_dict["oauth_verifier"] = oauth_verifier
  161. return token_dict
  162. @token.setter
  163. def token(self, value):
  164. self._populate_attributes(value)
  165. @property
  166. def authorized(self):
  167. """Boolean that indicates whether this session has an OAuth token
  168. or not. If `self.authorized` is True, you can reasonably expect
  169. OAuth-protected requests to the resource to succeed. If
  170. `self.authorized` is False, you need the user to go through the OAuth
  171. authentication dance before OAuth-protected requests to the resource
  172. will succeed.
  173. """
  174. if self._client.client.signature_method == SIGNATURE_RSA:
  175. # RSA only uses resource_owner_key
  176. return bool(self._client.client.resource_owner_key)
  177. else:
  178. # other methods of authentication use all three pieces
  179. return (
  180. bool(self._client.client.client_secret)
  181. and bool(self._client.client.resource_owner_key)
  182. and bool(self._client.client.resource_owner_secret)
  183. )
  184. def authorization_url(self, url, request_token=None, **kwargs):
  185. """Create an authorization URL by appending request_token and optional
  186. kwargs to url.
  187. This is the second step in the OAuth 1 workflow. The user should be
  188. redirected to this authorization URL, grant access to you, and then
  189. be redirected back to you. The redirection back can either be specified
  190. during client registration or by supplying a callback URI per request.
  191. :param url: The authorization endpoint URL.
  192. :param request_token: The previously obtained request token.
  193. :param kwargs: Optional parameters to append to the URL.
  194. :returns: The authorization URL with new parameters embedded.
  195. An example using a registered default callback URI.
  196. >>> request_token_url = 'https://api.twitter.com/oauth/request_token'
  197. >>> authorization_url = 'https://api.twitter.com/oauth/authorize'
  198. >>> oauth_session = OAuth1Session('client-key', client_secret='secret')
  199. >>> oauth_session.fetch_request_token(request_token_url)
  200. {
  201. 'oauth_token': 'sdf0o9823sjdfsdf',
  202. 'oauth_token_secret': '2kjshdfp92i34asdasd',
  203. }
  204. >>> oauth_session.authorization_url(authorization_url)
  205. 'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf'
  206. >>> oauth_session.authorization_url(authorization_url, foo='bar')
  207. 'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&foo=bar'
  208. An example using an explicit callback URI.
  209. >>> request_token_url = 'https://api.twitter.com/oauth/request_token'
  210. >>> authorization_url = 'https://api.twitter.com/oauth/authorize'
  211. >>> oauth_session = OAuth1Session('client-key', client_secret='secret', callback_uri='https://127.0.0.1/callback')
  212. >>> oauth_session.fetch_request_token(request_token_url)
  213. {
  214. 'oauth_token': 'sdf0o9823sjdfsdf',
  215. 'oauth_token_secret': '2kjshdfp92i34asdasd',
  216. }
  217. >>> oauth_session.authorization_url(authorization_url)
  218. 'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&oauth_callback=https%3A%2F%2F127.0.0.1%2Fcallback'
  219. """
  220. kwargs["oauth_token"] = request_token or self._client.client.resource_owner_key
  221. log.debug("Adding parameters %s to url %s", kwargs, url)
  222. return add_params_to_uri(url, kwargs.items())
  223. def fetch_request_token(self, url, realm=None, **request_kwargs):
  224. r"""Fetch a request token.
  225. This is the first step in the OAuth 1 workflow. A request token is
  226. obtained by making a signed post request to url. The token is then
  227. parsed from the application/x-www-form-urlencoded response and ready
  228. to be used to construct an authorization url.
  229. :param url: The request token endpoint URL.
  230. :param realm: A list of realms to request access to.
  231. :param \*\*request_kwargs: Optional arguments passed to ''post''
  232. function in ''requests.Session''
  233. :returns: The response in dict format.
  234. Note that a previously set callback_uri will be reset for your
  235. convenience, or else signature creation will be incorrect on
  236. consecutive requests.
  237. >>> request_token_url = 'https://api.twitter.com/oauth/request_token'
  238. >>> oauth_session = OAuth1Session('client-key', client_secret='secret')
  239. >>> oauth_session.fetch_request_token(request_token_url)
  240. {
  241. 'oauth_token': 'sdf0o9823sjdfsdf',
  242. 'oauth_token_secret': '2kjshdfp92i34asdasd',
  243. }
  244. """
  245. self._client.client.realm = " ".join(realm) if realm else None
  246. token = self._fetch_token(url, **request_kwargs)
  247. log.debug("Resetting callback_uri and realm (not needed in next phase).")
  248. self._client.client.callback_uri = None
  249. self._client.client.realm = None
  250. return token
  251. def fetch_access_token(self, url, verifier=None, **request_kwargs):
  252. """Fetch an access token.
  253. This is the final step in the OAuth 1 workflow. An access token is
  254. obtained using all previously obtained credentials, including the
  255. verifier from the authorization step.
  256. Note that a previously set verifier will be reset for your
  257. convenience, or else signature creation will be incorrect on
  258. consecutive requests.
  259. >>> access_token_url = 'https://api.twitter.com/oauth/access_token'
  260. >>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345'
  261. >>> oauth_session = OAuth1Session('client-key', client_secret='secret')
  262. >>> oauth_session.parse_authorization_response(redirect_response)
  263. {
  264. 'oauth_token: 'kjerht2309u',
  265. 'oauth_token_secret: 'lsdajfh923874',
  266. 'oauth_verifier: 'w34o8967345',
  267. }
  268. >>> oauth_session.fetch_access_token(access_token_url)
  269. {
  270. 'oauth_token': 'sdf0o9823sjdfsdf',
  271. 'oauth_token_secret': '2kjshdfp92i34asdasd',
  272. }
  273. """
  274. if verifier:
  275. self._client.client.verifier = verifier
  276. if not getattr(self._client.client, "verifier", None):
  277. raise VerifierMissing("No client verifier has been set.")
  278. token = self._fetch_token(url, **request_kwargs)
  279. log.debug("Resetting verifier attribute, should not be used anymore.")
  280. self._client.client.verifier = None
  281. return token
  282. def parse_authorization_response(self, url):
  283. """Extract parameters from the post authorization redirect response URL.
  284. :param url: The full URL that resulted from the user being redirected
  285. back from the OAuth provider to you, the client.
  286. :returns: A dict of parameters extracted from the URL.
  287. >>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345'
  288. >>> oauth_session = OAuth1Session('client-key', client_secret='secret')
  289. >>> oauth_session.parse_authorization_response(redirect_response)
  290. {
  291. 'oauth_token: 'kjerht2309u',
  292. 'oauth_token_secret: 'lsdajfh923874',
  293. 'oauth_verifier: 'w34o8967345',
  294. }
  295. """
  296. log.debug("Parsing token from query part of url %s", url)
  297. token = dict(urldecode(urlparse(url).query))
  298. log.debug("Updating internal client token attribute.")
  299. self._populate_attributes(token)
  300. self.token = token
  301. return token
  302. def _populate_attributes(self, token):
  303. if "oauth_token" in token:
  304. self._client.client.resource_owner_key = token["oauth_token"]
  305. else:
  306. raise TokenMissing(
  307. "Response does not contain a token: {resp}".format(resp=token), token
  308. )
  309. if "oauth_token_secret" in token:
  310. self._client.client.resource_owner_secret = token["oauth_token_secret"]
  311. if "oauth_verifier" in token:
  312. self._client.client.verifier = token["oauth_verifier"]
  313. def _fetch_token(self, url, **request_kwargs):
  314. log.debug("Fetching token from %s using client %s", url, self._client.client)
  315. r = self.post(url, **request_kwargs)
  316. if r.status_code >= 400:
  317. error = "Token request failed with code %s, response was '%s'."
  318. raise TokenRequestDenied(error % (r.status_code, r.text), r)
  319. log.debug('Decoding token from response "%s"', r.text)
  320. try:
  321. token = dict(urldecode(r.text.strip()))
  322. except ValueError as e:
  323. error = (
  324. "Unable to decode token from token response. "
  325. "This is commonly caused by an unsuccessful request where"
  326. " a non urlencoded error message is returned. "
  327. "The decoding error was %s"
  328. "" % e
  329. )
  330. raise ValueError(error)
  331. log.debug("Obtained token %s", token)
  332. log.debug("Updating internal client attributes from token data.")
  333. self._populate_attributes(token)
  334. self.token = token
  335. return token
  336. def rebuild_auth(self, prepared_request, response):
  337. """
  338. When being redirected we should always strip Authorization
  339. header, since nonce may not be reused as per OAuth spec.
  340. """
  341. if "Authorization" in prepared_request.headers:
  342. # If we get redirected to a new host, we should strip out
  343. # any authentication headers.
  344. prepared_request.headers.pop("Authorization", True)
  345. prepared_request.prepare_auth(self.auth)
  346. return