oauth1_session.py 16 KB

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