1 from __future__ import unicode_literals
4 from urlparse import urlparse
6 from urllib.parse import urlparse
8 from oauthlib.common import add_params_to_uri, urldecode
9 from oauthlib.oauth1 import SIGNATURE_HMAC, SIGNATURE_TYPE_AUTH_HEADER
19 class OAuth1Session(requests.Session):
20 """Request signing and convenience methods for the oauth dance.
22 What is the difference between OAuth1Session and OAuth1?
24 OAuth1Session actually uses OAuth1 internally and it's purpose is to assist
25 in the OAuth workflow through convenience methods to prepare authorization
26 URLs and parse the various token and redirection responses. It also provide
27 rudimentary validation of responses.
29 An example of the OAuth workflow using a basic CLI app and Twitter.
31 >>> # Credentials obtained during the registration.
32 >>> client_key = 'client key'
33 >>> client_secret = 'secret'
34 >>> callback_uri = 'https://127.0.0.1/callback'
36 >>> # Endpoints found in the OAuth provider API documentation
37 >>> request_token_url = 'https://api.twitter.com/oauth/request_token'
38 >>> authorization_url = 'https://api.twitter.com/oauth/authorize'
39 >>> access_token_url = 'https://api.twitter.com/oauth/access_token'
41 >>> oauth_session = OAuth1Session(client_key,client_secret=client_secret, callback_uri=callback_uri)
43 >>> # First step, fetch the request token.
44 >>> oauth_session.fetch_request_token(request_token_url)
46 'oauth_token': 'kjerht2309u',
47 'oauth_token_secret': 'lsdajfh923874',
50 >>> # Second step. Follow this link and authorize
51 >>> oauth_session.authorization_url(authorization_url)
52 'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&oauth_callback=https%3A%2F%2F127.0.0.1%2Fcallback'
54 >>> # Third step. Fetch the access token
55 >>> redirect_response = raw_input('Paste the full redirect URL here.')
56 >>> oauth_session.parse_authorization_response(redirect_response)
58 'oauth_token: 'kjerht2309u',
59 'oauth_token_secret: 'lsdajfh923874',
60 'oauth_verifier: 'w34o8967345',
62 >>> oauth_session.fetch_access_token(access_token_url)
64 'oauth_token': 'sdf0o9823sjdfsdf',
65 'oauth_token_secret': '2kjshdfp92i34asdasd',
67 >>> # Done. You can now make OAuth requests.
68 >>> status_url = 'http://api.twitter.com/1/statuses/update.json'
69 >>> new_status = {'status': 'hello world!'}
70 >>> oauth_session.post(status_url, data=new_status)
74 def __init__(self, client_key,
76 resource_owner_key=None,
77 resource_owner_secret=None,
79 signature_method=SIGNATURE_HMAC,
80 signature_type=SIGNATURE_TYPE_AUTH_HEADER,
83 """Construct the OAuth 1 session.
85 :param client_key: A client specific identifier.
86 :param client_secret: A client specific secret used to create HMAC and
88 :param resource_owner_key: A resource owner key, also referred to as
89 request token or access token depending on
90 when in the workflow it is used.
91 :param resource_owner_secret: A resource owner secret obtained with
92 either a request or access token. Often
93 referred to as token secret.
94 :param callback_uri: The URL the user is redirect back to after
96 :param signature_method: Signature methods determine how the OAuth
97 signature is created. The three options are
98 oauthlib.oauth1.SIGNATURE_HMAC (default),
99 oauthlib.oauth1.SIGNATURE_RSA and
100 oauthlib.oauth1.SIGNATURE_PLAIN.
101 :param signature_type: Signature type decides where the OAuth
102 parameters are added. Either in the
103 Authorization header (default) or to the URL
104 query parameters or the request body. Defined as
105 oauthlib.oauth1.SIGNATURE_TYPE_AUTH_HEADER,
106 oauthlib.oauth1.SIGNATURE_TYPE_QUERY and
107 oauthlib.oauth1.SIGNATURE_TYPE_BODY
109 :param rsa_key: The private RSA key as a string. Can only be used with
110 signature_method=oauthlib.oauth1.SIGNATURE_RSA.
111 :param verifier: A verifier string to prove authorization was granted.
113 super(OAuth1Session, self).__init__()
114 self._client = OAuth1(client_key,
115 client_secret=client_secret,
116 resource_owner_key=resource_owner_key,
117 resource_owner_secret=resource_owner_secret,
118 callback_uri=callback_uri,
119 signature_method=signature_method,
120 signature_type=signature_type,
123 self.auth = self._client
125 def authorization_url(self, url, request_token=None, **kwargs):
126 """Create an authorization URL by appending request_token and optional
129 This is the second step in the OAuth 1 workflow. The user should be
130 redirected to this authorization URL, grant access to you, and then
131 be redirected back to you. The redirection back can either be specified
132 during client registration or by supplying a callback URI per request.
134 :param url: The authorization endpoint URL.
135 :param request_token: The previously obtained request token.
136 :param kwargs: Optional parameters to append to the URL.
137 :returns: The authorization URL with new parameters embedded.
139 An example using a registered default callback URI.
141 >>> request_token_url = 'https://api.twitter.com/oauth/request_token'
142 >>> authorization_url = 'https://api.twitter.com/oauth/authorize'
143 >>> oauth_session = OAuth1Session('client-key', client_secret='secret')
144 >>> oauth_session.fetch_request_token(request_token_url)
146 'oauth_token': 'sdf0o9823sjdfsdf',
147 'oauth_token_secret': '2kjshdfp92i34asdasd',
149 >>> oauth_session.authorization_url(authorization_url)
150 'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf'
151 >>> oauth_session.authorization_url(authorization_url, foo='bar')
152 'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&foo=bar'
154 An example using an explicit callback URI.
156 >>> request_token_url = 'https://api.twitter.com/oauth/request_token'
157 >>> authorization_url = 'https://api.twitter.com/oauth/authorize'
158 >>> oauth_session = OAuth1Session('client-key', client_secret='secret', callback_uri='https://127.0.0.1/callback')
159 >>> oauth_session.fetch_request_token(request_token_url)
161 'oauth_token': 'sdf0o9823sjdfsdf',
162 'oauth_token_secret': '2kjshdfp92i34asdasd',
164 >>> oauth_session.authorization_url(authorization_url)
165 'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&oauth_callback=https%3A%2F%2F127.0.0.1%2Fcallback'
167 kwargs['oauth_token'] = request_token or self._client.client.resource_owner_key
168 return add_params_to_uri(url, kwargs.items())
170 def fetch_request_token(self, url, realm=None):
171 """Fetch a request token.
173 This is the first step in the OAuth 1 workflow. A request token is
174 obtained by making a signed post request to url. The token is then
175 parsed from the application/x-www-form-urlencoded response and ready
176 to be used to construct an authorization url.
178 :param url: The request token endpoint URL.
179 :param realm: A list of realms to request access to.
180 :returns: The response in dict format.
182 Note that a previously set callback_uri will be reset for your
183 convenience, or else signature creation will be incorrect on
184 consecutive requests.
186 >>> request_token_url = 'https://api.twitter.com/oauth/request_token'
187 >>> oauth_session = OAuth1Session('client-key', client_secret='secret')
188 >>> oauth_session.fetch_request_token(request_token_url)
190 'oauth_token': 'sdf0o9823sjdfsdf',
191 'oauth_token_secret': '2kjshdfp92i34asdasd',
194 self._client.client.realm = ' '.join(realm) if realm else None
195 token = self._fetch_token(url)
196 self._client.client.callback_uri = None
197 self._client.client.realm = None
200 def fetch_access_token(self, url):
201 """Fetch an access token.
203 This is the final step in the OAuth 1 workflow. An access token is
204 obtained using all previously obtained credentials, including the
205 verifier from the authorization step.
207 Note that a previously set verifier will be reset for your
208 convenience, or else signature creation will be incorrect on
209 consecutive requests.
211 >>> access_token_url = 'https://api.twitter.com/oauth/access_token'
212 >>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345'
213 >>> oauth_session = OAuth1Session('client-key', client_secret='secret')
214 >>> oauth_session.parse_authorization_response(redirect_response)
216 'oauth_token: 'kjerht2309u',
217 'oauth_token_secret: 'lsdajfh923874',
218 'oauth_verifier: 'w34o8967345',
220 >>> oauth_session.fetch_access_token(access_token_url)
222 'oauth_token': 'sdf0o9823sjdfsdf',
223 'oauth_token_secret': '2kjshdfp92i34asdasd',
226 if not hasattr(self._client.client, 'verifier'):
227 raise ValueError('No client verifier has been set.')
228 token = self._fetch_token(url)
229 self._client.client.verifier = None
232 def parse_authorization_response(self, url):
233 """Extract parameters from the post authorization redirect response URL.
235 :param url: The full URL that resulted from the user being redirected
236 back from the OAuth provider to you, the client.
237 :returns: A dict of parameters extracted from the URL.
239 >>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345'
240 >>> oauth_session = OAuth1Session('client-key', client_secret='secret')
241 >>> oauth_session.parse_authorization_response(redirect_response)
243 'oauth_token: 'kjerht2309u',
244 'oauth_token_secret: 'lsdajfh923874',
245 'oauth_verifier: 'w34o8967345',
248 token = dict(urldecode(urlparse(url).query))
249 self._populate_attributes(token)
252 def _populate_attributes(self, token):
253 if 'oauth_token' in token:
254 self._client.client.resource_owner_key = token['oauth_token']
256 raise ValueError('Response does not contain a token. %s', token)
257 if 'oauth_token_secret' in token:
258 self._client.client.resource_owner_secret = (
259 token['oauth_token_secret'])
260 if 'oauth_verifier' in token:
261 self._client.client.verifier = token['oauth_verifier']
263 def _fetch_token(self, url):
264 token = dict(urldecode(self.post(url).text))
265 self._populate_attributes(token)