一、安全cookie機制html
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的鍵值web
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()
二、用戶身份認證flask
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()
防止跨站攻擊cookie
一、在實例化tornado.web.Application傳入xsrf_cookies=True參數session
application = tornado.web.Application([(r'/', MainHandler), (r'/login', LoginHandler), ], cookie_secret='mimi', login_url='/login',xsrf_cookies=True)
二、在每一個HTML表單模板文件中爲全部表單添加xsrf_form_html()函數標籤app
<form action="/login" method="post"> {% module xsrf_form_html() %} <input type="text" name="message"> <input type="submit" value="post"> </form>