User Authentication

Now that we’ve seen how to set and retrieve cookies securely and understand the theory behind XSRF attacks, let’s look at an example that demonstrates a simple user authentication system. In this section, we will build an application that asks a visitor for her username and stores it in a secure cookie to be retrieved later. Subsequent requests will recognize the returning visitor and display a page customized specifically for her. You’ll learn about the login_url parameter and the tornado.web.authenticated decorator, which will eliminate some of the headaches normally involved in such an application.

Example: Welcome Back

In this example, we will simply identify someone by a username stored in a secure cookie. When someone visits our page for the first time in a particular browser (or after her cookie expires), we present a page with a login form. The form is submitted as a POST request that is routed to LoginHandler. The body of the post method calls set_secure_cookie() to store the value submitted in the username request argument.

The Tornado application in Example 6-2 demonstrates the authentication functions we will discuss in this section. The LoginHandler class renders the login form and sets the cookie while the LogoutHandler class deletes it.

Example 6-2. Authenticating visitors: cookies.py

import tornado.httpserver import tornado.ioloop import tornado.web import tornado.options import os.path from tornado.options import define, options define("port", default=8000, ...

Get Introduction to Tornado now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.