Securing Tornado cookies
Introduction
Tornado is a popular Python web framework and asynchronous networking library. It's highly efficient and flexible, making it a great choice for building web applications. One of the key aspects of building a secure web application is properly managing cookies. In this tutorial, we'll focus on how to secure Tornado cookies.
What are Cookies?
Cookies are tiny pieces of data stored by a web browser on a user's computer. They're meant to remember information about the user, like login information, site preferences, etc. However, if not handled securely, they can become an avenue for attacks like session hijacking, cross-site scripting, and others.
Cookie Secret
Tornado uses a secret key to sign cookies, which helps to prevent forgery. The secret key should be a long, random, and unguessable string. It’s also recommended to periodically rotate this key.
Here's how you set it:
import tornado.web
application = tornado.web.Application([
(r"/", MainHandler),
], cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__")
Secure Cookies
Tornado provides the set_secure_cookie
and get_secure_cookie
methods to deal with secure cookies. The set_secure_cookie
method signs and timestamps the cookie so it can't be forged or tampered with.
class MainHandler(tornado.web.RequestHandler):
def get(self):
cookie_value = self.get_secure_cookie("mycookie")
if cookie_value:
# Do something with the cookie
pass
else:
self.set_secure_cookie("mycookie", "some_value")
HTTPOnly Cookies
Setting the httponly
flag on a cookie helps mitigate the risk of client side script accessing the protected cookie. If the HttpOnly flag is included in the HTTP response header, the cookie cannot be accessed through client side script.
self.set_secure_cookie("mycookie", "some_value", httponly=True)
Secure Flag
The secure
flag is an option that can be set by the application server when sending a new cookie to the user's web browser. This flag tells the browser to only send the cookie if the request is being sent over a secure channel such as HTTPS.
self.set_secure_cookie("mycookie", "some_value", secure=True)
Expiration
By default, Tornado cookies are valid until the user's browser is closed. However, you can set an expiration time (in days) as follows:
self.set_secure_cookie("mycookie", "some_value", expires_days=1)
Conclusion
By implementing these techniques, you can ensure that the cookies in your Tornado application are secure. Always remember that each layer of security you add to your application will significantly decrease the chances of any potential data breaches or hacks.