oauth1_session.py 17 KB

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