As we have seen, Tornado helps you deal with Cookies and Secure cookies so what’s the next logical thing? Yes, user login. Let’s look at the Tornado’s capability for providing user authentication.

Tornado provides get_current_user() method to determine if the user is already logged in. Developers need to override this method to get the current user and that can be done through cookies (secure). Every logged-in user, is represented by Tornado as self.current_user. By default this value is set to None.

Let’s see how these two work in conjunction in the example below.

Sequence of events,

  • When user browses to, GET method of Main Handler is called.
  • In order to check if user has logged-in (with self.current_user), the call is routed to get_current_user().
  • In the first run, since there is no authenticated user, the client is redirected to /login page, with Get request.
  • In Login Handler, auth.html web page is rendered to the client and user is asked to log-in with username.
  • When the user enters a username and submits it, a Post request is sent to /login where a secure cookie is set for the username entered and the client gets redirected to the Main Handler ‘/’. This time round, since the user has logged-in, self.current_user is not None and a message ‘Hi there, ” with username is received on the client’s browser.

/login page


Python Decorator – @tornado.web.authenticated

The above behavior can also be achieved with decorator @tornado.web.authenticated. Example below:

In this code snippet, we need not worry about getting self.current_user. This work is done by the decorator. So here if the user is not logged in, the request is redirected to login_url application setting, which is /login in this case.