1、安全cookie机制
import tornado.web session_id = 1 class MainHandler(tornado.web.RequestHandler): def get(self):
global session_id if not self.get_cookie('session'): self.set_cookie('session',str(session_id)) session_id = session_id + 1 self.write('你设置了一个新的session') else: self.write('你已经获取了session')
为了防止客户端篡改,随意解析cookie的键值
import tornado.web import tornado.ioloop session_id = 1 class MainHandler(tornado.web.RequestHandler): def get(self): global session_id if not self.get_secure_cookie('session'): self.set_secure_cookie('session',str(session_id)) session_id = session_id+1 self.write('你设置了一个新的session') else: self.write('你已经获取了session') application = tornado.web.Application([(r'/',MainHandler),],cookie_secret = 'mimi') # 设置密钥 def main(): application.listen(8888) tornado.ioloop.IOLoop.current().start() if __name__ =='__main__': main()
2、用户身份认证
tornado和flask一样,在requestHandler中current_user保存当前请求用户名,但默认值时空,需要用requestHandler.get_current_user属性设置该属性
import tornado.web import tornado.ioloop import uuid # uuid生成库 dict_sessions = {} # 保存所有登陆的session class BaseHandler(tornado.web.RequestHandler): def get_current_user(self): # 写入current_user函数 session_id = self.get_secure_cookie('session') return dict_sessions.get(session_id) class MainHandler(BaseHandler): @tornado.web.authenticated # 需要身份认证才能访问的处理器 def get(self): name = tornado.escape.xhtml_escape(self.current_user) # 自动转义 self.write('hello' + name) class LoginHandler(BaseHandler): def get(self): self.write( '<html><body><form action="/login" method = "post">Name:<input type = "text" name = "name">:<input type = "submit" value = "sign in"></form></body></html>') def post(self): if len(self.get_argument('name')) < 3: self.redirect('/login') session_id = str(uuid.uuid1()) dict_sessions[session_id] = self.get_argument('name') self.set_secure_cookie('session_id', session_id) self.redirect('/') application = tornado.web.Application([(r'/', MainHandler), (r'/login', LoginHandler), ], cookie_secret='mimi', login_url='/login') def main(): application.listen(8888) tornado.ioloop.IOLoop.current().start() if __name__ == '__main__': main()
防止跨站攻击
1、在实例化tornado.web.Application传入xsrf_cookies=True参数
application = tornado.web.Application([(r'/', MainHandler), (r'/login', LoginHandler), ], cookie_secret='mimi', login_url='/login',xsrf_cookies=True)
2、在每个HTML表单模板文件中为所有表单添加xsrf_form_html()函数标签
<form action="/login" method="post"> {% module xsrf_form_html() %} <input type="text" name="message"> <input type="submit" value="post"> </form>