auth.py 45 KB

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