auth.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  1. #
  2. # Copyright 2009 Facebook
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. """This module contains implementations of various third-party
  16. authentication schemes.
  17. All the classes in this file are class mixins designed to be used with
  18. the `tornado.web.RequestHandler` class. They are used in two ways:
  19. * On a login handler, use methods such as ``authenticate_redirect()``,
  20. ``authorize_redirect()``, and ``get_authenticated_user()`` to
  21. establish the user's identity and store authentication tokens to your
  22. database and/or cookies.
  23. * In non-login handlers, use methods such as ``facebook_request()``
  24. or ``twitter_request()`` to use the authentication tokens to make
  25. requests to the respective services.
  26. They all take slightly different arguments due to the fact all these
  27. services implement authentication and authorization slightly differently.
  28. See the individual service classes below for complete documentation.
  29. Example usage for Google OAuth:
  30. .. testcode::
  31. class GoogleOAuth2LoginHandler(tornado.web.RequestHandler,
  32. tornado.auth.GoogleOAuth2Mixin):
  33. async def get(self):
  34. if self.get_argument('code', False):
  35. user = await self.get_authenticated_user(
  36. redirect_uri='http://your.site.com/auth/google',
  37. code=self.get_argument('code'))
  38. # Save the user with e.g. set_secure_cookie
  39. else:
  40. await self.authorize_redirect(
  41. redirect_uri='http://your.site.com/auth/google',
  42. client_id=self.settings['google_oauth']['key'],
  43. scope=['profile', 'email'],
  44. response_type='code',
  45. extra_params={'approval_prompt': 'auto'})
  46. .. testoutput::
  47. :hide:
  48. .. versionchanged:: 4.0
  49. All of the callback interfaces in this module are now guaranteed
  50. to run their callback with an argument of ``None`` on error.
  51. Previously some functions would do this while others would simply
  52. terminate the request on their own. This change also ensures that
  53. errors are more consistently reported through the ``Future`` interfaces.
  54. """
  55. from __future__ import absolute_import, division, print_function
  56. import base64
  57. import binascii
  58. import functools
  59. import hashlib
  60. import hmac
  61. import time
  62. import uuid
  63. import warnings
  64. from tornado.concurrent import (Future, _non_deprecated_return_future,
  65. future_set_exc_info, chain_future,
  66. future_set_result_unless_cancelled)
  67. from tornado import gen
  68. from tornado import httpclient
  69. from tornado import escape
  70. from tornado.httputil import url_concat
  71. from tornado.log import gen_log
  72. from tornado.stack_context import ExceptionStackContext, wrap
  73. from tornado.util import unicode_type, ArgReplacer, PY3
  74. if PY3:
  75. import urllib.parse as urlparse
  76. import urllib.parse as urllib_parse
  77. long = int
  78. else:
  79. import urlparse
  80. import urllib as urllib_parse
  81. class AuthError(Exception):
  82. pass
  83. def _auth_future_to_callback(callback, future):
  84. try:
  85. result = future.result()
  86. except AuthError as e:
  87. gen_log.warning(str(e))
  88. result = None
  89. callback(result)
  90. def _auth_return_future(f):
  91. """Similar to tornado.concurrent.return_future, but uses the auth
  92. module's legacy callback interface.
  93. Note that when using this decorator the ``callback`` parameter
  94. inside the function will actually be a future.
  95. .. deprecated:: 5.1
  96. Will be removed in 6.0.
  97. """
  98. replacer = ArgReplacer(f, 'callback')
  99. @functools.wraps(f)
  100. def wrapper(*args, **kwargs):
  101. future = Future()
  102. callback, args, kwargs = replacer.replace(future, args, kwargs)
  103. if callback is not None:
  104. warnings.warn("callback arguments are deprecated, use the returned Future instead",
  105. DeprecationWarning)
  106. future.add_done_callback(
  107. wrap(functools.partial(_auth_future_to_callback, callback)))
  108. def handle_exception(typ, value, tb):
  109. if future.done():
  110. return False
  111. else:
  112. future_set_exc_info(future, (typ, value, tb))
  113. return True
  114. with ExceptionStackContext(handle_exception, delay_warning=True):
  115. f(*args, **kwargs)
  116. return future
  117. return wrapper
  118. class OpenIdMixin(object):
  119. """Abstract implementation of OpenID and Attribute Exchange.
  120. Class attributes:
  121. * ``_OPENID_ENDPOINT``: the identity provider's URI.
  122. """
  123. @_non_deprecated_return_future
  124. def authenticate_redirect(self, callback_uri=None,
  125. ax_attrs=["name", "email", "language", "username"],
  126. callback=None):
  127. """Redirects to the authentication URL for this service.
  128. After authentication, the service will redirect back to the given
  129. callback URI with additional parameters including ``openid.mode``.
  130. We request the given attributes for the authenticated user by
  131. default (name, email, language, and username). If you don't need
  132. all those attributes for your app, you can request fewer with
  133. the ax_attrs keyword argument.
  134. .. versionchanged:: 3.1
  135. Returns a `.Future` and takes an optional callback. These are
  136. not strictly necessary as this method is synchronous,
  137. but they are supplied for consistency with
  138. `OAuthMixin.authorize_redirect`.
  139. .. deprecated:: 5.1
  140. The ``callback`` argument and returned awaitable will be removed
  141. in Tornado 6.0; this will be an ordinary synchronous function.
  142. """
  143. callback_uri = callback_uri or self.request.uri
  144. args = self._openid_args(callback_uri, ax_attrs=ax_attrs)
  145. self.redirect(self._OPENID_ENDPOINT + "?" + urllib_parse.urlencode(args))
  146. callback()
  147. @_auth_return_future
  148. def get_authenticated_user(self, callback, http_client=None):
  149. """Fetches the authenticated user data upon redirect.
  150. This method should be called by the handler that receives the
  151. redirect from the `authenticate_redirect()` method (which is
  152. often the same as the one that calls it; in that case you would
  153. call `get_authenticated_user` if the ``openid.mode`` parameter
  154. is present and `authenticate_redirect` if it is not).
  155. The result of this method will generally be used to set a cookie.
  156. .. deprecated:: 5.1
  157. The ``callback`` argument is deprecated and will be removed in 6.0.
  158. Use the returned awaitable object instead.
  159. """
  160. # Verify the OpenID response via direct request to the OP
  161. args = dict((k, v[-1]) for k, v in self.request.arguments.items())
  162. args["openid.mode"] = u"check_authentication"
  163. url = self._OPENID_ENDPOINT
  164. if http_client is None:
  165. http_client = self.get_auth_http_client()
  166. fut = http_client.fetch(url, method="POST", body=urllib_parse.urlencode(args))
  167. fut.add_done_callback(wrap(functools.partial(
  168. self._on_authentication_verified, callback)))
  169. def _openid_args(self, callback_uri, ax_attrs=[], oauth_scope=None):
  170. url = urlparse.urljoin(self.request.full_url(), callback_uri)
  171. args = {
  172. "openid.ns": "http://specs.openid.net/auth/2.0",
  173. "openid.claimed_id":
  174. "http://specs.openid.net/auth/2.0/identifier_select",
  175. "openid.identity":
  176. "http://specs.openid.net/auth/2.0/identifier_select",
  177. "openid.return_to": url,
  178. "openid.realm": urlparse.urljoin(url, '/'),
  179. "openid.mode": "checkid_setup",
  180. }
  181. if ax_attrs:
  182. args.update({
  183. "openid.ns.ax": "http://openid.net/srv/ax/1.0",
  184. "openid.ax.mode": "fetch_request",
  185. })
  186. ax_attrs = set(ax_attrs)
  187. required = []
  188. if "name" in ax_attrs:
  189. ax_attrs -= set(["name", "firstname", "fullname", "lastname"])
  190. required += ["firstname", "fullname", "lastname"]
  191. args.update({
  192. "openid.ax.type.firstname":
  193. "http://axschema.org/namePerson/first",
  194. "openid.ax.type.fullname":
  195. "http://axschema.org/namePerson",
  196. "openid.ax.type.lastname":
  197. "http://axschema.org/namePerson/last",
  198. })
  199. known_attrs = {
  200. "email": "http://axschema.org/contact/email",
  201. "language": "http://axschema.org/pref/language",
  202. "username": "http://axschema.org/namePerson/friendly",
  203. }
  204. for name in ax_attrs:
  205. args["openid.ax.type." + name] = known_attrs[name]
  206. required.append(name)
  207. args["openid.ax.required"] = ",".join(required)
  208. if oauth_scope:
  209. args.update({
  210. "openid.ns.oauth":
  211. "http://specs.openid.net/extensions/oauth/1.0",
  212. "openid.oauth.consumer": self.request.host.split(":")[0],
  213. "openid.oauth.scope": oauth_scope,
  214. })
  215. return args
  216. def _on_authentication_verified(self, future, response_fut):
  217. try:
  218. response = response_fut.result()
  219. except Exception as e:
  220. future.set_exception(AuthError(
  221. "Error response %s" % e))
  222. return
  223. if b"is_valid:true" not in response.body:
  224. future.set_exception(AuthError(
  225. "Invalid OpenID response: %s" % response.body))
  226. return
  227. # Make sure we got back at least an email from attribute exchange
  228. ax_ns = None
  229. for name in self.request.arguments:
  230. if name.startswith("openid.ns.") and \
  231. self.get_argument(name) == u"http://openid.net/srv/ax/1.0":
  232. ax_ns = name[10:]
  233. break
  234. def get_ax_arg(uri):
  235. if not ax_ns:
  236. return u""
  237. prefix = "openid." + ax_ns + ".type."
  238. ax_name = None
  239. for name in self.request.arguments.keys():
  240. if self.get_argument(name) == uri and name.startswith(prefix):
  241. part = name[len(prefix):]
  242. ax_name = "openid." + ax_ns + ".value." + part
  243. break
  244. if not ax_name:
  245. return u""
  246. return self.get_argument(ax_name, u"")
  247. email = get_ax_arg("http://axschema.org/contact/email")
  248. name = get_ax_arg("http://axschema.org/namePerson")
  249. first_name = get_ax_arg("http://axschema.org/namePerson/first")
  250. last_name = get_ax_arg("http://axschema.org/namePerson/last")
  251. username = get_ax_arg("http://axschema.org/namePerson/friendly")
  252. locale = get_ax_arg("http://axschema.org/pref/language").lower()
  253. user = dict()
  254. name_parts = []
  255. if first_name:
  256. user["first_name"] = first_name
  257. name_parts.append(first_name)
  258. if last_name:
  259. user["last_name"] = last_name
  260. name_parts.append(last_name)
  261. if name:
  262. user["name"] = name
  263. elif name_parts:
  264. user["name"] = u" ".join(name_parts)
  265. elif email:
  266. user["name"] = email.split("@")[0]
  267. if email:
  268. user["email"] = email
  269. if locale:
  270. user["locale"] = locale
  271. if username:
  272. user["username"] = username
  273. claimed_id = self.get_argument("openid.claimed_id", None)
  274. if claimed_id:
  275. user["claimed_id"] = claimed_id
  276. future_set_result_unless_cancelled(future, user)
  277. def get_auth_http_client(self):
  278. """Returns the `.AsyncHTTPClient` instance to be used for auth requests.
  279. May be overridden by subclasses to use an HTTP client other than
  280. the default.
  281. """
  282. return httpclient.AsyncHTTPClient()
  283. class OAuthMixin(object):
  284. """Abstract implementation of OAuth 1.0 and 1.0a.
  285. See `TwitterMixin` below for an example implementation.
  286. Class attributes:
  287. * ``_OAUTH_AUTHORIZE_URL``: The service's OAuth authorization url.
  288. * ``_OAUTH_ACCESS_TOKEN_URL``: The service's OAuth access token url.
  289. * ``_OAUTH_VERSION``: May be either "1.0" or "1.0a".
  290. * ``_OAUTH_NO_CALLBACKS``: Set this to True if the service requires
  291. advance registration of callbacks.
  292. Subclasses must also override the `_oauth_get_user_future` and
  293. `_oauth_consumer_token` methods.
  294. """
  295. @_non_deprecated_return_future
  296. def authorize_redirect(self, callback_uri=None, extra_params=None,
  297. http_client=None, callback=None):
  298. """Redirects the user to obtain OAuth authorization for this service.
  299. The ``callback_uri`` may be omitted if you have previously
  300. registered a callback URI with the third-party service. For
  301. some services, you must use a previously-registered callback
  302. URI and cannot specify a callback via this method.
  303. This method sets a cookie called ``_oauth_request_token`` which is
  304. subsequently used (and cleared) in `get_authenticated_user` for
  305. security purposes.
  306. This method is asynchronous and must be called with ``await``
  307. or ``yield`` (This is different from other ``auth*_redirect``
  308. methods defined in this module). It calls
  309. `.RequestHandler.finish` for you so you should not write any
  310. other response after it returns.
  311. .. versionchanged:: 3.1
  312. Now returns a `.Future` and takes an optional callback, for
  313. compatibility with `.gen.coroutine`.
  314. .. deprecated:: 5.1
  315. The ``callback`` argument is deprecated and will be removed in 6.0.
  316. Use the returned awaitable object instead.
  317. """
  318. if callback_uri and getattr(self, "_OAUTH_NO_CALLBACKS", False):
  319. raise Exception("This service does not support oauth_callback")
  320. if http_client is None:
  321. http_client = self.get_auth_http_client()
  322. if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
  323. fut = http_client.fetch(
  324. self._oauth_request_token_url(callback_uri=callback_uri,
  325. extra_params=extra_params))
  326. fut.add_done_callback(wrap(functools.partial(
  327. self._on_request_token,
  328. self._OAUTH_AUTHORIZE_URL,
  329. callback_uri,
  330. callback)))
  331. else:
  332. fut = http_client.fetch(self._oauth_request_token_url())
  333. fut.add_done_callback(
  334. wrap(functools.partial(
  335. self._on_request_token, self._OAUTH_AUTHORIZE_URL,
  336. callback_uri,
  337. callback)))
  338. @_auth_return_future
  339. def get_authenticated_user(self, callback, http_client=None):
  340. """Gets the OAuth authorized user and access token.
  341. This method should be called from the handler for your
  342. OAuth callback URL to complete the registration process. We run the
  343. callback with the authenticated user dictionary. This dictionary
  344. will contain an ``access_key`` which can be used to make authorized
  345. requests to this service on behalf of the user. The dictionary will
  346. also contain other fields such as ``name``, depending on the service
  347. used.
  348. .. deprecated:: 5.1
  349. The ``callback`` argument is deprecated and will be removed in 6.0.
  350. Use the returned awaitable object instead.
  351. """
  352. future = callback
  353. request_key = escape.utf8(self.get_argument("oauth_token"))
  354. oauth_verifier = self.get_argument("oauth_verifier", None)
  355. request_cookie = self.get_cookie("_oauth_request_token")
  356. if not request_cookie:
  357. future.set_exception(AuthError(
  358. "Missing OAuth request token cookie"))
  359. return
  360. self.clear_cookie("_oauth_request_token")
  361. cookie_key, cookie_secret = [
  362. base64.b64decode(escape.utf8(i)) for i in request_cookie.split("|")]
  363. if cookie_key != request_key:
  364. future.set_exception(AuthError(
  365. "Request token does not match cookie"))
  366. return
  367. token = dict(key=cookie_key, secret=cookie_secret)
  368. if oauth_verifier:
  369. token["verifier"] = oauth_verifier
  370. if http_client is None:
  371. http_client = self.get_auth_http_client()
  372. fut = http_client.fetch(self._oauth_access_token_url(token))
  373. fut.add_done_callback(wrap(functools.partial(self._on_access_token, callback)))
  374. def _oauth_request_token_url(self, callback_uri=None, extra_params=None):
  375. consumer_token = self._oauth_consumer_token()
  376. url = self._OAUTH_REQUEST_TOKEN_URL
  377. args = dict(
  378. oauth_consumer_key=escape.to_basestring(consumer_token["key"]),
  379. oauth_signature_method="HMAC-SHA1",
  380. oauth_timestamp=str(int(time.time())),
  381. oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
  382. oauth_version="1.0",
  383. )
  384. if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
  385. if callback_uri == "oob":
  386. args["oauth_callback"] = "oob"
  387. elif callback_uri:
  388. args["oauth_callback"] = urlparse.urljoin(
  389. self.request.full_url(), callback_uri)
  390. if extra_params:
  391. args.update(extra_params)
  392. signature = _oauth10a_signature(consumer_token, "GET", url, args)
  393. else:
  394. signature = _oauth_signature(consumer_token, "GET", url, args)
  395. args["oauth_signature"] = signature
  396. return url + "?" + urllib_parse.urlencode(args)
  397. def _on_request_token(self, authorize_url, callback_uri, callback,
  398. response_fut):
  399. try:
  400. response = response_fut.result()
  401. except Exception as e:
  402. raise Exception("Could not get request token: %s" % e)
  403. request_token = _oauth_parse_response(response.body)
  404. data = (base64.b64encode(escape.utf8(request_token["key"])) + b"|" +
  405. base64.b64encode(escape.utf8(request_token["secret"])))
  406. self.set_cookie("_oauth_request_token", data)
  407. args = dict(oauth_token=request_token["key"])
  408. if callback_uri == "oob":
  409. self.finish(authorize_url + "?" + urllib_parse.urlencode(args))
  410. callback()
  411. return
  412. elif callback_uri:
  413. args["oauth_callback"] = urlparse.urljoin(
  414. self.request.full_url(), callback_uri)
  415. self.redirect(authorize_url + "?" + urllib_parse.urlencode(args))
  416. callback()
  417. def _oauth_access_token_url(self, request_token):
  418. consumer_token = self._oauth_consumer_token()
  419. url = self._OAUTH_ACCESS_TOKEN_URL
  420. args = dict(
  421. oauth_consumer_key=escape.to_basestring(consumer_token["key"]),
  422. oauth_token=escape.to_basestring(request_token["key"]),
  423. oauth_signature_method="HMAC-SHA1",
  424. oauth_timestamp=str(int(time.time())),
  425. oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
  426. oauth_version="1.0",
  427. )
  428. if "verifier" in request_token:
  429. args["oauth_verifier"] = request_token["verifier"]
  430. if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
  431. signature = _oauth10a_signature(consumer_token, "GET", url, args,
  432. request_token)
  433. else:
  434. signature = _oauth_signature(consumer_token, "GET", url, args,
  435. request_token)
  436. args["oauth_signature"] = signature
  437. return url + "?" + urllib_parse.urlencode(args)
  438. def _on_access_token(self, future, response_fut):
  439. try:
  440. response = response_fut.result()
  441. except Exception:
  442. future.set_exception(AuthError("Could not fetch access token"))
  443. return
  444. access_token = _oauth_parse_response(response.body)
  445. fut = self._oauth_get_user_future(access_token)
  446. fut = gen.convert_yielded(fut)
  447. fut.add_done_callback(
  448. wrap(functools.partial(self._on_oauth_get_user, access_token, future)))
  449. def _oauth_consumer_token(self):
  450. """Subclasses must override this to return their OAuth consumer keys.
  451. The return value should be a `dict` with keys ``key`` and ``secret``.
  452. """
  453. raise NotImplementedError()
  454. @_non_deprecated_return_future
  455. def _oauth_get_user_future(self, access_token, callback):
  456. """Subclasses must override this to get basic information about the
  457. user.
  458. Should return a `.Future` whose result is a dictionary
  459. containing information about the user, which may have been
  460. retrieved by using ``access_token`` to make a request to the
  461. service.
  462. The access token will be added to the returned dictionary to make
  463. the result of `get_authenticated_user`.
  464. For backwards compatibility, the callback-based ``_oauth_get_user``
  465. method is also supported.
  466. .. versionchanged:: 5.1
  467. Subclasses may also define this method with ``async def``.
  468. .. deprecated:: 5.1
  469. The ``_oauth_get_user`` fallback is deprecated and support for it
  470. will be removed in 6.0.
  471. """
  472. warnings.warn("_oauth_get_user is deprecated, override _oauth_get_user_future instead",
  473. DeprecationWarning)
  474. # By default, call the old-style _oauth_get_user, but new code
  475. # should override this method instead.
  476. self._oauth_get_user(access_token, callback)
  477. def _oauth_get_user(self, access_token, callback):
  478. raise NotImplementedError()
  479. def _on_oauth_get_user(self, access_token, future, user_future):
  480. if user_future.exception() is not None:
  481. future.set_exception(user_future.exception())
  482. return
  483. user = user_future.result()
  484. if not user:
  485. future.set_exception(AuthError("Error getting user"))
  486. return
  487. user["access_token"] = access_token
  488. future_set_result_unless_cancelled(future, user)
  489. def _oauth_request_parameters(self, url, access_token, parameters={},
  490. method="GET"):
  491. """Returns the OAuth parameters as a dict for the given request.
  492. parameters should include all POST arguments and query string arguments
  493. that will be sent with the request.
  494. """
  495. consumer_token = self._oauth_consumer_token()
  496. base_args = dict(
  497. oauth_consumer_key=escape.to_basestring(consumer_token["key"]),
  498. oauth_token=escape.to_basestring(access_token["key"]),
  499. oauth_signature_method="HMAC-SHA1",
  500. oauth_timestamp=str(int(time.time())),
  501. oauth_nonce=escape.to_basestring(binascii.b2a_hex(uuid.uuid4().bytes)),
  502. oauth_version="1.0",
  503. )
  504. args = {}
  505. args.update(base_args)
  506. args.update(parameters)
  507. if getattr(self, "_OAUTH_VERSION", "1.0a") == "1.0a":
  508. signature = _oauth10a_signature(consumer_token, method, url, args,
  509. access_token)
  510. else:
  511. signature = _oauth_signature(consumer_token, method, url, args,
  512. access_token)
  513. base_args["oauth_signature"] = escape.to_basestring(signature)
  514. return base_args
  515. def get_auth_http_client(self):
  516. """Returns the `.AsyncHTTPClient` instance to be used for auth requests.
  517. May be overridden by subclasses to use an HTTP client other than
  518. the default.
  519. """
  520. return httpclient.AsyncHTTPClient()
  521. class OAuth2Mixin(object):
  522. """Abstract implementation of OAuth 2.0.
  523. See `FacebookGraphMixin` or `GoogleOAuth2Mixin` below for example
  524. implementations.
  525. Class attributes:
  526. * ``_OAUTH_AUTHORIZE_URL``: The service's authorization url.
  527. * ``_OAUTH_ACCESS_TOKEN_URL``: The service's access token url.
  528. """
  529. @_non_deprecated_return_future
  530. def authorize_redirect(self, redirect_uri=None, client_id=None,
  531. client_secret=None, extra_params=None,
  532. callback=None, scope=None, response_type="code"):
  533. """Redirects the user to obtain OAuth authorization for this service.
  534. Some providers require that you register a redirect URL with
  535. your application instead of passing one via this method. You
  536. should call this method to log the user in, and then call
  537. ``get_authenticated_user`` in the handler for your
  538. redirect URL to complete the authorization process.
  539. .. versionchanged:: 3.1
  540. Returns a `.Future` and takes an optional callback. These are
  541. not strictly necessary as this method is synchronous,
  542. but they are supplied for consistency with
  543. `OAuthMixin.authorize_redirect`.
  544. .. deprecated:: 5.1
  545. The ``callback`` argument and returned awaitable will be removed
  546. in Tornado 6.0; this will be an ordinary synchronous function.
  547. """
  548. args = {
  549. "redirect_uri": redirect_uri,
  550. "client_id": client_id,
  551. "response_type": response_type
  552. }
  553. if extra_params:
  554. args.update(extra_params)
  555. if scope:
  556. args['scope'] = ' '.join(scope)
  557. self.redirect(
  558. url_concat(self._OAUTH_AUTHORIZE_URL, args))
  559. callback()
  560. def _oauth_request_token_url(self, redirect_uri=None, client_id=None,
  561. client_secret=None, code=None,
  562. extra_params=None):
  563. url = self._OAUTH_ACCESS_TOKEN_URL
  564. args = dict(
  565. redirect_uri=redirect_uri,
  566. code=code,
  567. client_id=client_id,
  568. client_secret=client_secret,
  569. )
  570. if extra_params:
  571. args.update(extra_params)
  572. return url_concat(url, args)
  573. @_auth_return_future
  574. def oauth2_request(self, url, callback, access_token=None,
  575. post_args=None, **args):
  576. """Fetches the given URL auth an OAuth2 access token.
  577. If the request is a POST, ``post_args`` should be provided. Query
  578. string arguments should be given as keyword arguments.
  579. Example usage:
  580. ..testcode::
  581. class MainHandler(tornado.web.RequestHandler,
  582. tornado.auth.FacebookGraphMixin):
  583. @tornado.web.authenticated
  584. async def get(self):
  585. new_entry = await self.oauth2_request(
  586. "https://graph.facebook.com/me/feed",
  587. post_args={"message": "I am posting from my Tornado application!"},
  588. access_token=self.current_user["access_token"])
  589. if not new_entry:
  590. # Call failed; perhaps missing permission?
  591. await self.authorize_redirect()
  592. return
  593. self.finish("Posted a message!")
  594. .. testoutput::
  595. :hide:
  596. .. versionadded:: 4.3
  597. .. deprecated:: 5.1
  598. The ``callback`` argument is deprecated and will be removed in 6.0.
  599. Use the returned awaitable object instead.
  600. """
  601. all_args = {}
  602. if access_token:
  603. all_args["access_token"] = access_token
  604. all_args.update(args)
  605. if all_args:
  606. url += "?" + urllib_parse.urlencode(all_args)
  607. callback = wrap(functools.partial(self._on_oauth2_request, callback))
  608. http = self.get_auth_http_client()
  609. if post_args is not None:
  610. fut = http.fetch(url, method="POST", body=urllib_parse.urlencode(post_args))
  611. else:
  612. fut = http.fetch(url)
  613. fut.add_done_callback(callback)
  614. def _on_oauth2_request(self, future, response_fut):
  615. try:
  616. response = response_fut.result()
  617. except Exception as e:
  618. future.set_exception(AuthError("Error response %s" % e))
  619. return
  620. future_set_result_unless_cancelled(future, escape.json_decode(response.body))
  621. def get_auth_http_client(self):
  622. """Returns the `.AsyncHTTPClient` instance to be used for auth requests.
  623. May be overridden by subclasses to use an HTTP client other than
  624. the default.
  625. .. versionadded:: 4.3
  626. """
  627. return httpclient.AsyncHTTPClient()
  628. class TwitterMixin(OAuthMixin):
  629. """Twitter OAuth authentication.
  630. To authenticate with Twitter, register your application with
  631. Twitter at http://twitter.com/apps. Then copy your Consumer Key
  632. and Consumer Secret to the application
  633. `~tornado.web.Application.settings` ``twitter_consumer_key`` and
  634. ``twitter_consumer_secret``. Use this mixin on the handler for the
  635. URL you registered as your application's callback URL.
  636. When your application is set up, you can use this mixin like this
  637. to authenticate the user with Twitter and get access to their stream:
  638. .. testcode::
  639. class TwitterLoginHandler(tornado.web.RequestHandler,
  640. tornado.auth.TwitterMixin):
  641. async def get(self):
  642. if self.get_argument("oauth_token", None):
  643. user = await self.get_authenticated_user()
  644. # Save the user using e.g. set_secure_cookie()
  645. else:
  646. await self.authorize_redirect()
  647. .. testoutput::
  648. :hide:
  649. The user object returned by `~OAuthMixin.get_authenticated_user`
  650. includes the attributes ``username``, ``name``, ``access_token``,
  651. and all of the custom Twitter user attributes described at
  652. https://dev.twitter.com/docs/api/1.1/get/users/show
  653. """
  654. _OAUTH_REQUEST_TOKEN_URL = "https://api.twitter.com/oauth/request_token"
  655. _OAUTH_ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token"
  656. _OAUTH_AUTHORIZE_URL = "https://api.twitter.com/oauth/authorize"
  657. _OAUTH_AUTHENTICATE_URL = "https://api.twitter.com/oauth/authenticate"
  658. _OAUTH_NO_CALLBACKS = False
  659. _TWITTER_BASE_URL = "https://api.twitter.com/1.1"
  660. @_non_deprecated_return_future
  661. def authenticate_redirect(self, callback_uri=None, callback=None):
  662. """Just like `~OAuthMixin.authorize_redirect`, but
  663. auto-redirects if authorized.
  664. This is generally the right interface to use if you are using
  665. Twitter for single-sign on.
  666. .. versionchanged:: 3.1
  667. Now returns a `.Future` and takes an optional callback, for
  668. compatibility with `.gen.coroutine`.
  669. .. deprecated:: 5.1
  670. The ``callback`` argument is deprecated and will be removed in 6.0.
  671. Use the returned awaitable object instead.
  672. """
  673. http = self.get_auth_http_client()
  674. fut = http.fetch(self._oauth_request_token_url(callback_uri=callback_uri))
  675. fut.add_done_callback(wrap(functools.partial(
  676. self._on_request_token, self._OAUTH_AUTHENTICATE_URL,
  677. None, callback)))
  678. @_auth_return_future
  679. def twitter_request(self, path, callback=None, access_token=None,
  680. post_args=None, **args):
  681. """Fetches the given API path, e.g., ``statuses/user_timeline/btaylor``
  682. The path should not include the format or API version number.
  683. (we automatically use JSON format and API version 1).
  684. If the request is a POST, ``post_args`` should be provided. Query
  685. string arguments should be given as keyword arguments.
  686. All the Twitter methods are documented at http://dev.twitter.com/
  687. Many methods require an OAuth access token which you can
  688. obtain through `~OAuthMixin.authorize_redirect` and
  689. `~OAuthMixin.get_authenticated_user`. The user returned through that
  690. process includes an 'access_token' attribute that can be used
  691. to make authenticated requests via this method. Example
  692. usage:
  693. .. testcode::
  694. class MainHandler(tornado.web.RequestHandler,
  695. tornado.auth.TwitterMixin):
  696. @tornado.web.authenticated
  697. async def get(self):
  698. new_entry = await self.twitter_request(
  699. "/statuses/update",
  700. post_args={"status": "Testing Tornado Web Server"},
  701. access_token=self.current_user["access_token"])
  702. if not new_entry:
  703. # Call failed; perhaps missing permission?
  704. yield self.authorize_redirect()
  705. return
  706. self.finish("Posted a message!")
  707. .. testoutput::
  708. :hide:
  709. .. deprecated:: 5.1
  710. The ``callback`` argument is deprecated and will be removed in 6.0.
  711. Use the returned awaitable object instead.
  712. """
  713. if path.startswith('http:') or path.startswith('https:'):
  714. # Raw urls are useful for e.g. search which doesn't follow the
  715. # usual pattern: http://search.twitter.com/search.json
  716. url = path
  717. else:
  718. url = self._TWITTER_BASE_URL + path + ".json"
  719. # Add the OAuth resource request signature if we have credentials
  720. if access_token:
  721. all_args = {}
  722. all_args.update(args)
  723. all_args.update(post_args or {})
  724. method = "POST" if post_args is not None else "GET"
  725. oauth = self._oauth_request_parameters(
  726. url, access_token, all_args, method=method)
  727. args.update(oauth)
  728. if args:
  729. url += "?" + urllib_parse.urlencode(args)
  730. http = self.get_auth_http_client()
  731. http_callback = wrap(functools.partial(self._on_twitter_request, callback, url))
  732. if post_args is not None:
  733. fut = http.fetch(url, method="POST", body=urllib_parse.urlencode(post_args))
  734. else:
  735. fut = http.fetch(url)
  736. fut.add_done_callback(http_callback)
  737. def _on_twitter_request(self, future, url, response_fut):
  738. try:
  739. response = response_fut.result()
  740. except Exception as e:
  741. future.set_exception(AuthError(
  742. "Error response %s fetching %s" % (e, url)))
  743. return
  744. future_set_result_unless_cancelled(future, escape.json_decode(response.body))
  745. def _oauth_consumer_token(self):
  746. self.require_setting("twitter_consumer_key", "Twitter OAuth")
  747. self.require_setting("twitter_consumer_secret", "Twitter OAuth")
  748. return dict(
  749. key=self.settings["twitter_consumer_key"],
  750. secret=self.settings["twitter_consumer_secret"])
  751. @gen.coroutine
  752. def _oauth_get_user_future(self, access_token):
  753. user = yield self.twitter_request(
  754. "/account/verify_credentials",
  755. access_token=access_token)
  756. if user:
  757. user["username"] = user["screen_name"]
  758. raise gen.Return(user)
  759. class GoogleOAuth2Mixin(OAuth2Mixin):
  760. """Google authentication using OAuth2.
  761. In order to use, register your application with Google and copy the
  762. relevant parameters to your application settings.
  763. * Go to the Google Dev Console at http://console.developers.google.com
  764. * Select a project, or create a new one.
  765. * In the sidebar on the left, select APIs & Auth.
  766. * In the list of APIs, find the Google+ API service and set it to ON.
  767. * In the sidebar on the left, select Credentials.
  768. * In the OAuth section of the page, select Create New Client ID.
  769. * Set the Redirect URI to point to your auth handler
  770. * Copy the "Client secret" and "Client ID" to the application settings as
  771. {"google_oauth": {"key": CLIENT_ID, "secret": CLIENT_SECRET}}
  772. .. versionadded:: 3.2
  773. """
  774. _OAUTH_AUTHORIZE_URL = "https://accounts.google.com/o/oauth2/v2/auth"
  775. _OAUTH_ACCESS_TOKEN_URL = "https://www.googleapis.com/oauth2/v4/token"
  776. _OAUTH_USERINFO_URL = "https://www.googleapis.com/oauth2/v1/userinfo"
  777. _OAUTH_NO_CALLBACKS = False
  778. _OAUTH_SETTINGS_KEY = 'google_oauth'
  779. @_auth_return_future
  780. def get_authenticated_user(self, redirect_uri, code, callback):
  781. """Handles the login for the Google user, returning an access token.
  782. The result is a dictionary containing an ``access_token`` field
  783. ([among others](https://developers.google.com/identity/protocols/OAuth2WebServer#handlingtheresponse)).
  784. Unlike other ``get_authenticated_user`` methods in this package,
  785. this method does not return any additional information about the user.
  786. The returned access token can be used with `OAuth2Mixin.oauth2_request`
  787. to request additional information (perhaps from
  788. ``https://www.googleapis.com/oauth2/v2/userinfo``)
  789. Example usage:
  790. .. testcode::
  791. class GoogleOAuth2LoginHandler(tornado.web.RequestHandler,
  792. tornado.auth.GoogleOAuth2Mixin):
  793. async def get(self):
  794. if self.get_argument('code', False):
  795. access = await self.get_authenticated_user(
  796. redirect_uri='http://your.site.com/auth/google',
  797. code=self.get_argument('code'))
  798. user = await self.oauth2_request(
  799. "https://www.googleapis.com/oauth2/v1/userinfo",
  800. access_token=access["access_token"])
  801. # Save the user and access token with
  802. # e.g. set_secure_cookie.
  803. else:
  804. await self.authorize_redirect(
  805. redirect_uri='http://your.site.com/auth/google',
  806. client_id=self.settings['google_oauth']['key'],
  807. scope=['profile', 'email'],
  808. response_type='code',
  809. extra_params={'approval_prompt': 'auto'})
  810. .. testoutput::
  811. :hide:
  812. .. deprecated:: 5.1
  813. The ``callback`` argument is deprecated and will be removed in 6.0.
  814. Use the returned awaitable object instead.
  815. """ # noqa: E501
  816. http = self.get_auth_http_client()
  817. body = urllib_parse.urlencode({
  818. "redirect_uri": redirect_uri,
  819. "code": code,
  820. "client_id": self.settings[self._OAUTH_SETTINGS_KEY]['key'],
  821. "client_secret": self.settings[self._OAUTH_SETTINGS_KEY]['secret'],
  822. "grant_type": "authorization_code",
  823. })
  824. fut = http.fetch(self._OAUTH_ACCESS_TOKEN_URL,
  825. method="POST",
  826. headers={'Content-Type': 'application/x-www-form-urlencoded'},
  827. body=body)
  828. fut.add_done_callback(wrap(functools.partial(self._on_access_token, callback)))
  829. def _on_access_token(self, future, response_fut):
  830. """Callback function for the exchange to the access token."""
  831. try:
  832. response = response_fut.result()
  833. except Exception as e:
  834. future.set_exception(AuthError('Google auth error: %s' % str(e)))
  835. return
  836. args = escape.json_decode(response.body)
  837. future_set_result_unless_cancelled(future, args)
  838. class FacebookGraphMixin(OAuth2Mixin):
  839. """Facebook authentication using the new Graph API and OAuth2."""
  840. _OAUTH_ACCESS_TOKEN_URL = "https://graph.facebook.com/oauth/access_token?"
  841. _OAUTH_AUTHORIZE_URL = "https://www.facebook.com/dialog/oauth?"
  842. _OAUTH_NO_CALLBACKS = False
  843. _FACEBOOK_BASE_URL = "https://graph.facebook.com"
  844. @_auth_return_future
  845. def get_authenticated_user(self, redirect_uri, client_id, client_secret,
  846. code, callback, extra_fields=None):
  847. """Handles the login for the Facebook user, returning a user object.
  848. Example usage:
  849. .. testcode::
  850. class FacebookGraphLoginHandler(tornado.web.RequestHandler,
  851. tornado.auth.FacebookGraphMixin):
  852. async def get(self):
  853. if self.get_argument("code", False):
  854. user = await self.get_authenticated_user(
  855. redirect_uri='/auth/facebookgraph/',
  856. client_id=self.settings["facebook_api_key"],
  857. client_secret=self.settings["facebook_secret"],
  858. code=self.get_argument("code"))
  859. # Save the user with e.g. set_secure_cookie
  860. else:
  861. await self.authorize_redirect(
  862. redirect_uri='/auth/facebookgraph/',
  863. client_id=self.settings["facebook_api_key"],
  864. extra_params={"scope": "read_stream,offline_access"})
  865. .. testoutput::
  866. :hide:
  867. This method returns a dictionary which may contain the following fields:
  868. * ``access_token``, a string which may be passed to `facebook_request`
  869. * ``session_expires``, an integer encoded as a string representing
  870. the time until the access token expires in seconds. This field should
  871. be used like ``int(user['session_expires'])``; in a future version of
  872. Tornado it will change from a string to an integer.
  873. * ``id``, ``name``, ``first_name``, ``last_name``, ``locale``, ``picture``,
  874. ``link``, plus any fields named in the ``extra_fields`` argument. These
  875. fields are copied from the Facebook graph API
  876. `user object <https://developers.facebook.com/docs/graph-api/reference/user>`_
  877. .. versionchanged:: 4.5
  878. The ``session_expires`` field was updated to support changes made to the
  879. Facebook API in March 2017.
  880. .. deprecated:: 5.1
  881. The ``callback`` argument is deprecated and will be removed in 6.0.
  882. Use the returned awaitable object instead.
  883. """
  884. http = self.get_auth_http_client()
  885. args = {
  886. "redirect_uri": redirect_uri,
  887. "code": code,
  888. "client_id": client_id,
  889. "client_secret": client_secret,
  890. }
  891. fields = set(['id', 'name', 'first_name', 'last_name',
  892. 'locale', 'picture', 'link'])
  893. if extra_fields:
  894. fields.update(extra_fields)
  895. fut = http.fetch(self._oauth_request_token_url(**args))
  896. fut.add_done_callback(wrap(functools.partial(self._on_access_token, redirect_uri, client_id,
  897. client_secret, callback, fields)))
  898. @gen.coroutine
  899. def _on_access_token(self, redirect_uri, client_id, client_secret,
  900. future, fields, response_fut):
  901. try:
  902. response = response_fut.result()
  903. except Exception as e:
  904. future.set_exception(AuthError('Facebook auth error: %s' % str(e)))
  905. return
  906. args = escape.json_decode(response.body)
  907. session = {
  908. "access_token": args.get("access_token"),
  909. "expires_in": args.get("expires_in")
  910. }
  911. user = yield self.facebook_request(
  912. path="/me",
  913. access_token=session["access_token"],
  914. appsecret_proof=hmac.new(key=client_secret.encode('utf8'),
  915. msg=session["access_token"].encode('utf8'),
  916. digestmod=hashlib.sha256).hexdigest(),
  917. fields=",".join(fields)
  918. )
  919. if user is None:
  920. future_set_result_unless_cancelled(future, None)
  921. return
  922. fieldmap = {}
  923. for field in fields:
  924. fieldmap[field] = user.get(field)
  925. # session_expires is converted to str for compatibility with
  926. # older versions in which the server used url-encoding and
  927. # this code simply returned the string verbatim.
  928. # This should change in Tornado 5.0.
  929. fieldmap.update({"access_token": session["access_token"],
  930. "session_expires": str(session.get("expires_in"))})
  931. future_set_result_unless_cancelled(future, fieldmap)
  932. @_auth_return_future
  933. def facebook_request(self, path, callback, access_token=None,
  934. post_args=None, **args):
  935. """Fetches the given relative API path, e.g., "/btaylor/picture"
  936. If the request is a POST, ``post_args`` should be provided. Query
  937. string arguments should be given as keyword arguments.
  938. An introduction to the Facebook Graph API can be found at
  939. http://developers.facebook.com/docs/api
  940. Many methods require an OAuth access token which you can
  941. obtain through `~OAuth2Mixin.authorize_redirect` and
  942. `get_authenticated_user`. The user returned through that
  943. process includes an ``access_token`` attribute that can be
  944. used to make authenticated requests via this method.
  945. Example usage:
  946. .. testcode::
  947. class MainHandler(tornado.web.RequestHandler,
  948. tornado.auth.FacebookGraphMixin):
  949. @tornado.web.authenticated
  950. async def get(self):
  951. new_entry = await self.facebook_request(
  952. "/me/feed",
  953. post_args={"message": "I am posting from my Tornado application!"},
  954. access_token=self.current_user["access_token"])
  955. if not new_entry:
  956. # Call failed; perhaps missing permission?
  957. yield self.authorize_redirect()
  958. return
  959. self.finish("Posted a message!")
  960. .. testoutput::
  961. :hide:
  962. The given path is relative to ``self._FACEBOOK_BASE_URL``,
  963. by default "https://graph.facebook.com".
  964. This method is a wrapper around `OAuth2Mixin.oauth2_request`;
  965. the only difference is that this method takes a relative path,
  966. while ``oauth2_request`` takes a complete url.
  967. .. versionchanged:: 3.1
  968. Added the ability to override ``self._FACEBOOK_BASE_URL``.
  969. .. deprecated:: 5.1
  970. The ``callback`` argument is deprecated and will be removed in 6.0.
  971. Use the returned awaitable object instead.
  972. """
  973. url = self._FACEBOOK_BASE_URL + path
  974. # Thanks to the _auth_return_future decorator, our "callback"
  975. # argument is a Future, which we cannot pass as a callback to
  976. # oauth2_request. Instead, have oauth2_request return a
  977. # future and chain them together.
  978. oauth_future = self.oauth2_request(url, access_token=access_token,
  979. post_args=post_args, **args)
  980. chain_future(oauth_future, callback)
  981. def _oauth_signature(consumer_token, method, url, parameters={}, token=None):
  982. """Calculates the HMAC-SHA1 OAuth signature for the given request.
  983. See http://oauth.net/core/1.0/#signing_process
  984. """
  985. parts = urlparse.urlparse(url)
  986. scheme, netloc, path = parts[:3]
  987. normalized_url = scheme.lower() + "://" + netloc.lower() + path
  988. base_elems = []
  989. base_elems.append(method.upper())
  990. base_elems.append(normalized_url)
  991. base_elems.append("&".join("%s=%s" % (k, _oauth_escape(str(v)))
  992. for k, v in sorted(parameters.items())))
  993. base_string = "&".join(_oauth_escape(e) for e in base_elems)
  994. key_elems = [escape.utf8(consumer_token["secret"])]
  995. key_elems.append(escape.utf8(token["secret"] if token else ""))
  996. key = b"&".join(key_elems)
  997. hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1)
  998. return binascii.b2a_base64(hash.digest())[:-1]
  999. def _oauth10a_signature(consumer_token, method, url, parameters={}, token=None):
  1000. """Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request.
  1001. See http://oauth.net/core/1.0a/#signing_process
  1002. """
  1003. parts = urlparse.urlparse(url)
  1004. scheme, netloc, path = parts[:3]
  1005. normalized_url = scheme.lower() + "://" + netloc.lower() + path
  1006. base_elems = []
  1007. base_elems.append(method.upper())
  1008. base_elems.append(normalized_url)
  1009. base_elems.append("&".join("%s=%s" % (k, _oauth_escape(str(v)))
  1010. for k, v in sorted(parameters.items())))
  1011. base_string = "&".join(_oauth_escape(e) for e in base_elems)
  1012. key_elems = [escape.utf8(urllib_parse.quote(consumer_token["secret"], safe='~'))]
  1013. key_elems.append(escape.utf8(urllib_parse.quote(token["secret"], safe='~') if token else ""))
  1014. key = b"&".join(key_elems)
  1015. hash = hmac.new(key, escape.utf8(base_string), hashlib.sha1)
  1016. return binascii.b2a_base64(hash.digest())[:-1]
  1017. def _oauth_escape(val):
  1018. if isinstance(val, unicode_type):
  1019. val = val.encode("utf-8")
  1020. return urllib_parse.quote(val, safe="~")
  1021. def _oauth_parse_response(body):
  1022. # I can't find an officially-defined encoding for oauth responses and
  1023. # have never seen anyone use non-ascii. Leave the response in a byte
  1024. # string for python 2, and use utf8 on python 3.
  1025. body = escape.native_str(body)
  1026. p = urlparse.parse_qs(body, keep_blank_values=False)
  1027. token = dict(key=p["oauth_token"][0], secret=p["oauth_token_secret"][0])
  1028. # Add the extra parameters the Provider included to the token
  1029. special = ("oauth_token", "oauth_token_secret")
  1030. token.update((k, p[k][0]) for k in p if k not in special)
  1031. return token