auth.py 45 KB

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