def get_secure_cookie(self, name, value=None): """Returns the given signed cookie if it validates, or None. In older versions of Tornado (0.1 and 0.2), we did not include the name of the cookie in the cookie signature. To read these old-style cookies, pass include_name=False to this method. Otherwise, all attempts to read old-style cookies will fail (and you may log all your users out whose cookies were written with a previous Tornado version). """ if value is None: value = self.get_cookie(name) if not value: return None parts = value.split("|") if len(parts) != 3: return None signature = utils.cookie_signature(name, parts[0], parts[1]) if not utils.time_independent_equals(parts[2], signature): logging.warning("Invalid cookie signature %r", value) return None timestamp = int(parts[1]) if timestamp < time.time() - 31 * 86400: logging.warning("Expired cookie %r", value) return None try: return base64.b64decode(parts[0]) except: return None
def set_secure_cookie(self, name, value, **kwargs): """Signs and timestamps a cookie so it cannot be forged. You must specify the 'cookie_secret' setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature. To read a cookie set with this method, use get_secure_cookie(). """ timestamp = str(int(time.time())) value = base64.b64encode(value) signature = utils.cookie_signature(name, value, timestamp) value = "|".join([value, timestamp, signature]) self.set_cookie(name, value, **kwargs)