一.cookie介绍 cookie在浏览器端保存的键值对,每次http请求时都会带上它 在tornado中: 服务端: self.cookies 获取所有cookie self.set_cookie(key,value) 设置cookie self.get_cookie(key) 获取cookie 前端浏览器中: document.cookie获取所有cookie document.cookie=“k2=value”设置cookie 获取指定cookie的话需要进行split分割document.cookie.split(";") 前端通过javascript中设置cookie:
<script> function setCookie(key,value,expires){ //创建时间对象 var current_date=new Date(); //设置当前时间加expires秒 current_date.setSeconds(current_date.getSeconds()+expires); //设置cookie document.cookie=key+"="+value+";expires="+current_date.toUTCString(); } </script>前端通过jquery设置cookie
![](/i/l/?n=23&i=blog/1534225/202304/1534225-20230410203443935-192171017.png)
import tornado.web import tornado.ioloop settings = { "template_path": "views", "static_path": "static", } class MainHandler(tornado.web.RequestHandler): def get(self): #获取cookie print(self.cookies) #设置cookie self.set_cookie("ss","4545") self.render("main.html") app = tornado.web.Application([ #基本路由 (r"/main", MainHandler), ], **settings) if __name__ == "__main__": app.listen(8090) tornado.ioloop.IOLoop.instance().start()main.html文件代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script src="{{static_url('jquery.js')}}"></script> <script src="{{static_url('jquery.cookie.js')}}"></script> <script> <!-- jquery进行设置cookie --> //expires是数字的表示过期时间是以天为单位的 $.cookie("s1","v1",{expires:1}) var ts=new Date() ts.setSeconds(ts.getSeconds()+60) //设置过期为60s $.cookie("s2","k2",{expires: ts}) // <!--javascript进行设置cookie --> function setCookie(key,value,expires){ //创建时间对象 var current_date=new Date(); //设置当前时间加expires秒 current_date.setSeconds(current_date.getSeconds()+expires); //设置cookie document.cookie=key+"="+value+";expires="+current_date.toUTCString(); } </script> </body> </html>二.带签名的cookie app.py文件代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import tornado.web import tornado.ioloop settings = { "template_path": "views", "static_path": "static", "cookie_secret":"fsfasfasfa33adddd" } class MainHandler(tornado.web.RequestHandler): def get(self): #获取cookie print(self.cookies) #设置带签名的cookie self.set_secure_cookie("test","qianmingCookie") self.render("main.html") def post(self): print("获取带签名的cookie:",self.get_secure_cookie("test"),"是byte类型的,需要转换成字符串") # 获取带签名的cookie并转换成字符串,如果cookie一致则跳转到daiQianMingCookie.html页面,否则跳转到main.html页面 if str(self.get_secure_cookie("test"),encoding="utf-8")=="qianmingCookie": self.render("daiQianMingCookie.html") else: self.redirect("/main") app = tornado.web.Application([ #基本路由 (r"/main", MainHandler), ], **settings) if __name__ == "__main__": app.listen(8090) tornado.ioloop.IOLoop.instance().start()View Code main.html文件代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/main" method="POST"> <input type="submit" value="跳转一下"> </form> <script src="{{static_url('jquery.js')}}"></script> <script src="{{static_url('jquery.cookie.js')}}"></script> <script> <!-- jquery进行设置cookie --> //expires是数字的表示过期时间是以天为单位的 $.cookie("s1","v1",{expires:1}) var ts=new Date() ts.setSeconds(ts.getSeconds()+60) //设置过期为60s $.cookie("s2","k2",{expires: ts}) // <!--javascript进行设置cookie --> function setCookie(key,value,expires){ //创建时间对象 var current_date=new Date(); //设置当前时间加expires秒 current_date.setSeconds(current_date.getSeconds()+expires); //设置cookie document.cookie=key+"="+value+";expires="+current_date.toUTCString(); } </script> </body> </html>View Code
daiQianMingCookie.html文件代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>这是带签名的cookie页面</h1> </body> </html>View Code
运行app.py文件后在浏览器输入127.0.0.1:8090/main后打开main.html页面,在页面点击跳转一下请求post方法,如果cookie一致的话跳转到daiQianMingCookie的页面,不一致还是跳转到当前页面
三.cookie进行用户签名验证 app.py文件代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import tornado.web import tornado.ioloop settings = { "template_path": "views", "static_path": "static", "cookie_secret":"fsfasfasfa33adddd" } INFO={"userName":""} class MainHandler(tornado.web.RequestHandler): def get(self): #获取cookie print(self.cookies) #设置带签名的cookie self.set_secure_cookie("test","qianmingCookie") self.render("main.html") def post(self): print("获取带签名的cookie:",self.get_secure_cookie("test"),"是byte类型的,需要转换成字符串") # 获取带签名的cookie并转换成字符串,如果cookie一致则跳转到daiQianMingCookie.html页面,否则跳转到main.html页面 if str(self.get_secure_cookie("test"),encoding="utf-8")=="qianmingCookie": self.render("daiQianMingCookie.html") else: self.redirect("/main") class LoginHandler(tornado.web.RequestHandler): def get(self): self.render("account.html",info="") def post(self): # 获取用户密码并加入到INFO中 pwdCookie=self.get_argument("pwd",None) INFO["userName"]=pwdCookie #设置带签名的cookie self.set_secure_cookie("userName",pwdCookie) self.render("account.html",info="设置了cookie") class IndexHandler(tornado.web.RequestHandler): #用户cookie验证通过后跳转到index.html页面,否则跳转login路由下的account页面 def get(self): try: if str(self.get_secure_cookie("userName"),encoding="utf-8")==INFO["userName"]: self.render("index.html",info="") else: self.redirect("/login") except: self.write("出错了") app = tornado.web.Application([ #基本路由 (r"/main", MainHandler), (r"/login", LoginHandler), (r"/index", IndexHandler), ], **settings) if __name__ == "__main__": app.listen(8090) tornado.ioloop.IOLoop.instance().start()View Code
account.html文件代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>通用页面</h1> <p>设置cookie了</p> <form action="/login" method="POST"> <input type="text" name="userName"> <input type="password" name="pwd"> <input type="submit" value="提交"> </form> <h1>{{info}}</h1> </body> </html>View Code
index.html文件代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>cookie验证通过后的页面</h1> </body> </html>View Code 运行app.py文件后,输入127.0.0.1:8090/login后跳转account.html页面;设置cookie后输入127.0.0.1:8090/index,如果cookie验证通过后跳转 四.自定义Session 1.tornado不带session,自定义session实际就相当于把设置的cookie转换成字典形式进行存储,如cookie="user=123,pwd=456,email=789",变成了{"cookie":{user:123,pwd:456,email:789}},而random_str={user:123,pwd:456,email:789},而设置cookie时set_cookie=("cookie",random_str) session.py文件代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import tornado.web import tornado.ioloop import hashlib import time settings = { "template_path": "views", "static_path": "static", "cookie_secret":"fsfasfasfa33adddd" } INFO={} class SessionHandler(tornado.web.RequestHandler): def get(self): #自定义session,实际就相当于把cookie设置的内容转换成字典的形式进行存储了 #如cookie设置的k1=”user=123;pwd=456;email=rrr“变成了{"k1":{user:123,pwd:456,email:rrr}},即相当于set_cookie("k1",{"k1":{user:123,pwd:456,email:rrr}}) if self.get_argument("u",None) in ["test","java"]: #生成随机字符串 obj=hashlib.md5() obj.update(bytes(str(time.time()),encoding="utf-8")) random_str=obj.hexdigest() #即INFO={random_str:{}} INFO[random_str]={} INFO[random_str]["k1"]=123 INFO[random_str]["k2"]=self.get_argument("u",None)+"session" INFO[random_str]["is_login"]=True #即INFO={random_str:{"k1":123,"k2":"test","is_login":True}} self.set_secure_cookie("userName",random_str) self.weite("登录成功") else: self.write("请登录") class ManagerSessionHandler(tornado.web.RequestHandler): def get(self): # print("ssINFO",INFO) random_str=str(self.get_secure_cookie("userName",None),encoding="utf-8") current_user=INFO.get(random_str,None) # print(current_user) if not current_user: self.redirect("/session") else: if current_user.get("is_login",None): temp="%s-%s欢迎回来"%(current_user.get("k1",""),current_user.get("k2","")) self.write(temp) else: self.redirect("/session") app = tornado.web.Application([ #基本路由 (r"/session", SessionHandler), (r"/manager", ManagerSessionHandler), ], **settings) if __name__ == "__main__": app.listen(8090) tornado.ioloop.IOLoop.instance().start()View Code 运行session.py文件后,在浏览器中输入http://127.0.0.1:8090/session?u=test后出现登录成功页面,输入http://127.0.0.1:8090/manager后出现欢迎回来页面 2.上面自定义session代码每次设置session都要重新写一次,我们需要把它封装到一个自定义session类中 MyDifineSession.py文件代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import hashlib import time INFO={} class Session(): def __init__(self,handler): self.handler=handler self.__randomStr=self.randomValue() INFO[self.__randomStr]={} def randomValue(self): obj=hashlib.md5() obj.update(bytes(str(time.time()),encoding="utf-8")) random_str=obj.hexdigest() return random_str def setSessionValue(self,key,value): INFO[self.__randomStr][key]=value def setSessionCookie(self): self.handler.set_secure_cookie("userName",self.__randomStr) def getSessionValue(self,key): random_str=str(self.handler.get_secure_cookie("userName",None),encoding="utf-8") current_user=INFO.get(random_str,None) if current_user: return current_user.get(key,None) else: return FalseView Code
修改后的session.py文件代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import tornado.web import tornado.ioloop from MyDefineSession import Session,INFO settings = { "template_path": "views", "static_path": "static", "cookie_secret":"fsfasfasfa33adddd" } class SessionHandler(tornado.web.RequestHandler): def get(self): #自定义session,实际就相当于把cookie设置的内容转换成字典的形式进行存储了 #如cookie设置的k1=”user=123;pwd=456;email=rrr“变成了{"k1":{user:123,pwd:456,email:rrr}},即相当于set_cookie("k1",{"k1":{user:123,pwd:456,email:rrr}}) if self.get_argument("u",None) in ["test","java"]: s=Session(self) s.setSessionValue("name",self.get_argument("u",None)) s.setSessionValue("xxx","22222") s.setSessionValue("yyy","33333") s.setSessionValue("is_login",True) s.setSessionCookie() self.write("%s登录成功"%(self.get_argument("u"))) else: self.write("请登录") print("Session=======",INFO) class ManagerSessionHandler(tornado.web.RequestHandler): def get(self): print("Manager=======",INFO) s=Session(self) if s.getSessionValue("is_login"): self.write("%s欢迎回来"%(s.getSessionValue("name"))) else: self.redirect("/session") app = tornado.web.Application([ #基本路由 (r"/session", SessionHandler), (r"/manager", ManagerSessionHandler), ], **settings) if __name__ == "__main__": app.listen(8090) tornado.ioloop.IOLoop.instance().start()View Code 运行session.py文件后,在浏览器中输入http://127.0.0.1:8090/session?u=test后出现登录成功页面,输入http://127.0.0.1:8090/manager后出现欢迎回来页面 3.上述代码中逻辑存在漏洞,当同一个用户多次登录时会生成多个随机字符串的cookie,下述代码优化后一个用户多次登录后只会生成一个随机字符串 session.py文件代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import tornado.web import tornado.ioloop import hashlib import time INFO={} li={} settings = { "template_path": "views", "static_path": "static", "cookie_secret":"fsfasfasfa33adddd" } class selfSession: def __init__(self,handler): self.handler=handler self.randomStr=None def __randomStr(self): obj=hashlib.md5() obj.update(bytes(str(time.time()),encoding="utf-8")) random_str=obj.hexdigest() return random_str def setValue(self,key,value): #在INFO里面加入随机字符串 #定义专属数据 #在客户端写入随机字符串 #判断请求的用户是否已有随机字符串 if not self.randomStr: randomStr=self.handler.get_cookie("userName") if not randomStr: #没有随机字符串进行创建随机字符串 randomStr=self.__randomStr() INFO[randomStr]={} #客户端有随机字符串 else: #客户端有,服务端也有 if randomStr in INFO.keys(): #判断设置的值是否在用户名字典中,如果不在就重新生成新的随机字符串 if value in li.keys(): pass else: randomStr=self.__randomStr() INFO[randomStr]={} else: #客户端有,服务端没有 randomStr=self.__randomStr() INFO[randomStr]={} self.randomStr=randomStr INFO[self.randomStr][key]=value #把用户名加入到li字典中 li[INFO[self.randomStr]["name"]]=INFO[self.randomStr]["name"] self.handler.set_cookie("userName",self.randomStr) def getValue(self,key): #判断请求的用户是否已有随机字符串 randomStr=self.handler.get_cookie("userName") if not randomStr: return False #客户端有随机字符串 userInfo=INFO.get(randomStr,None) if not userInfo: return False value=userInfo.get(key,None) return value class SessionHandler(tornado.web.RequestHandler): def get(self): #自定义session,实际就相当于把cookie设置的内容转换成字典的形式进行存储了 #如cookie设置的k1=”user=123;pwd=456;email=rrr“变成了{"k1":{user:123,pwd:456,email:rrr}},即相当于set_cookie("k1",{"k1":{user:123,pwd:456,email:rrr}}) if self.get_argument("u",None) in ["test","java"]: s=selfSession(self) s.setValue("name",self.get_argument("u")) s.setValue("xxx","22222") s.setValue("yyy","33333") s.setValue("is_login",True) self.write("%s登录成功"%(self.get_argument("u"))) else: self.write("请登录") # print("Session=======",INFO) class ManagerSessionHandler(tornado.web.RequestHandler): def get(self): print("Manager=======",INFO) s=selfSession(self) if s.getValue("is_login"): self.write("%s欢迎回来"%(s.getValue("name"))) else: self.redirect("/session") app = tornado.web.Application([ #基本路由 (r"/session", SessionHandler), (r"/manager", ManagerSessionHandler), ], **settings) if __name__ == "__main__": app.listen(8090) tornado.ioloop.IOLoop.instance().start()View Code 运行session.py文件后,在浏览器中输入http://127.0.0.1:8090/session?u=test后出现登录成功页面,输入http://127.0.0.1:8090/manager后出现欢迎回来页面 4.上述代码中我们每次请求一次时就要创建一次selfSession类的对象,为减少代码重复调用,最终优化session.py文件代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import tornado.web import tornado.ioloop import hashlib import time INFO={} li={} settings = { "template_path": "views", "static_path": "static", "cookie_secret":"fsfasfasfa33adddd" } class selfSession: def __init__(self,handler): self.handler=handler self.randomStr=None def __randomStr(self): obj=hashlib.md5() obj.update(bytes(str(time.time()),encoding="utf-8")) random_str=obj.hexdigest() return random_str def __setitem__(self, key, value): #在INFO里面加入随机字符串 #定义专属数据 #在客户端写入随机字符串 #判断请求的用户是否已有随机字符串 if not self.randomStr: randomStr=self.handler.get_cookie("userName") if not randomStr: #没有随机字符串进行创建随机字符串 randomStr=self.__randomStr() INFO[randomStr]={} #客户端有随机字符串 else: #客户端有,服务端也有 if randomStr in INFO.keys(): #判断设置的值是否在用户名字典中,如果不在就重新生成新的随机字符串 if value in li.keys(): pass else: randomStr=self.__randomStr() INFO[randomStr]={} else: #客户端有,服务端没有 randomStr=self.__randomStr() INFO[randomStr]={} self.randomStr=randomStr INFO[self.randomStr][key]=value #把用户名加入到li字典中 li[INFO[self.randomStr]["name"]]=INFO[self.randomStr]["name"] self.handler.set_cookie("userName",self.randomStr) def __getitem__(self, key): #判断请求的用户是否已有随机字符串 randomStr=self.handler.get_cookie("userName") if not randomStr: return False #客户端有随机字符串 userInfo=INFO.get(randomStr,None) if not userInfo: return False value=userInfo.get(key,None) return value class BaseSessionHandler(tornado.web.RequestHandler): # 钩子函数 def initialize(self): self.session=selfSession(self) class SessionHandler(BaseSessionHandler): def get(self): #自定义session,实际就相当于把cookie设置的内容转换成字典的形式进行存储了 #如cookie设置的k1=”user=123;pwd=456;email=rrr“变成了{"k1":{user:123,pwd:456,email:rrr}},即相当于set_cookie("k1",{"k1":{user:123,pwd:456,email:rrr}}) if self.get_argument("u",None) in ["test","java"]: self.session["name"]=self.get_argument("u") self.session["xxx"]="22222" self.session["yyy"]="33333" self.session["is_login"]=True self.write("%s登录成功"%(self.get_argument("u"))) else: self.write("请登录") # print("Session=======",INFO) class ManagerSessionHandler(BaseSessionHandler): def get(self): print("Manager=======",INFO) if self.session["is_login"]: self.write("%s欢迎回来"%(self.session["name"])) else: self.redirect("/session") app = tornado.web.Application([ #基本路由 (r"/session", SessionHandler), (r"/manager", ManagerSessionHandler), ], **settings) if __name__ == "__main__": app.listen(8090) tornado.ioloop.IOLoop.instance().start()View Code 运行session.py文件后,在浏览器中输入http://127.0.0.1:8090/session?u=test后出现登录成功页面,输入http://127.0.0.1:8090/manager后出现欢迎回来页面 cookie与session区别: 1.cookie保存在客户端,session保存在服务端 2.cookie是自动生成的,session是人为制造的,session依赖于cookie 五.验证码 1.验证码需要拷贝check_code.py和Monaco.ttf放在代码文件下 session.py文件中定义LoginHandler和CheckCodeHandler
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import tornado.web import tornado.ioloop import hashlib import time,io import check_code INFO={} li={} settings = { "template_path": "views", "static_path": "static", "cookie_secret":"fsfasfasfa33adddd" } class selfSession: def __init__(self,handler): self.handler=handler self.randomStr=None def __randomStr(self): obj=hashlib.md5() obj.update(bytes(str(time.time()),encoding="utf-8")) random_str=obj.hexdigest() return random_str def __setitem__(self, key, value): #在INFO里面加入随机字符串 #定义专属数据 #在客户端写入随机字符串 #判断请求的用户是否已有随机字符串 if not self.randomStr: randomStr=self.handler.get_cookie("userName") if not randomStr: #没有随机字符串进行创建随机字符串 randomStr=self.__randomStr() INFO[randomStr]={} #客户端有随机字符串 else: #客户端有,服务端也有 if randomStr in INFO.keys(): #判断设置的值是否在用户名字典中,如果不在就重新生成新的随机字符串 if value in li.keys(): pass else: randomStr=self.__randomStr() INFO[randomStr]={} else: #客户端有,服务端没有 randomStr=self.__randomStr() INFO[randomStr]={} self.randomStr=randomStr INFO[self.randomStr][key]=value #把用户名加入到li字典中 if key=="name": li[INFO[self.randomStr]["name"]]=INFO[self.randomStr]["name"] self.handler.set_cookie("userName",self.randomStr) def __getitem__(self, key): #判断请求的用户是否已有随机字符串 randomStr=self.handler.get_cookie("userName") if not randomStr: return False #客户端有随机字符串 userInfo=INFO.get(randomStr,None) if not userInfo: return False value=userInfo.get(key,None) return value class BaseSessionHandler(tornado.web.RequestHandler): # 钩子函数 def initialize(self): self.session=selfSession(self) class SessionHandler(BaseSessionHandler): def get(self): #自定义session,实际就相当于把cookie设置的内容转换成字典的形式进行存储了 #如cookie设置的k1=”user=123;pwd=456;email=rrr“变成了{"k1":{user:123,pwd:456,email:rrr}},即相当于set_cookie("k1",{"k1":{user:123,pwd:456,email:rrr}}) if self.get_argument("u",None) in ["test","java"]: self.session["name"]=self.get_argument("u") self.session["xxx"]="22222" self.session["yyy"]="33333" self.session["is_login"]=True self.write("%s登录成功"%(self.get_argument("u"))) else: self.write("请登录") # print("Session=======",INFO) class ManagerSessionHandler(BaseSessionHandler): def get(self): print("Manager=======",INFO) if self.session["is_login"]: self.write("%s欢迎回来"%(self.session["name"])) else: self.redirect("/session") class LoginHandler(BaseSessionHandler): def get(self,*args,**kwargs): print(INFO) name=self.get_argument("name","") self.render("login.html",status="",name=name) def post(self): user=self.get_argument("user") pwd=self.get_argument("pwd") code=self.get_argument("code") check_code=self.session["CheckCode"] if code.upper()==check_code.upper(): self.write("验证码正确") else: self.render("login.html",status="验证码正确",name=user) class CheckCodeHandler(BaseSessionHandler): def get(self,*args,**kwargs): mstream = io.BytesIO() #创建图片并写入验证码 img, code = check_code.create_validate_code() img.save(mstream, "GIF") self.session["CheckCode"] = code # print(mstream.getvalue()) self.write(mstream.getvalue()) app = tornado.web.Application([ #基本路由 (r"/session", SessionHandler), (r"/manager", ManagerSessionHandler), (r"/login", LoginHandler), (r"/checkCode", CheckCodeHandler), ], **settings) if __name__ == "__main__": app.listen(8090) tornado.ioloop.IOLoop.instance().start()View Code
login.html文件代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login" method="post"> <p><input type="text" placeholder="用户" name="user"></p> <p><input type="text" placeholder="密码" name="pwd"></p> <p> <input type="text" name="code" placeholder="验证码" > <!-- src指向本地路由进行生成验证码 --> <img src="/checkCode?name={{name}}" alt=" " onclick='ChangeCode();' id='imgCode'> </p> <p> <input type="submit" value="提交"> <span style="color: red">{{status}}</span> </p> </form> <script type="text/javascript"> <!-- 点击图片验证码进行切换验证码 --> function ChangeCode() { var code = document.getElementById('imgCode'); code.src += '?'; } </script> </body> </html>View Code
运行session.py文件后,在浏览器输入http://127.0.0.1:8090/login后请求LoginHandler类中的get方法,返回login.html页面,该页面会去请求生成验证码
六、CSRF证书验证 1.csrf进行跨域请求证书验证 csrfHandler.py文件代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import tornado.web import tornado.ioloop class CrsfHandler(tornado.web.RequestHandler): def get(self): self.render("csrfHandler.html") def post(self): self.write("crsf.post页面") settings={ "template_path":"views", # xsrf设置为True时走Csrf验证 "xsrf_cookies":True } app=tornado.web.Application([ (r"/csrf",CrsfHandler) ],**settings) if __name__=="__main__": app.listen(8091) tornado.ioloop.IOLoop.instance().start()View Code
csrfHandler.html文件代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/csrf" method="post"> <input type="text" name="test"> <input type="submit" name="tijiao" value="提交"> </form> </body> </html>View Code 运行csrfHandler.py文件后在浏览器中输入127.0.0.1:8091/csrf后访问csrfHandler.html页面,点击该页面的提交后会请求post方法,而这时xsrf_cookies是True,会进行csrf证书校验,我们请求时没有发送证书,所以会报403,这时我们需要修改csrfHandler.html文件 修改后csrfHandler.html文件代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/crsf" method="post"> <!-- xsrf_form_html()请求时会把证书传过去 --> {% raw xsrf_form_html() %} <input type="text" name="test"> <input type="submit" name="tijiao" value="提交"> </form> </body> </html>View Code
2.通过ajax进行跨域请求,只需要修改csrfHandler.html文件代码即可
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/crsf" method="post"> <!-- xsrf_form_html()请求时会把证书传过去 --> {% raw xsrf_form_html() %} <input type="text" name="test"> <input type="submit" name="tijiao" value="提交"> <input type="button" value="ajax请求" onclick="ajaxRuquest()"> </form> <!--<script src="{{static_url('jquery.js')}}"></script>--> <script src="{{static_url('jquery.js')}}"></script> <script> function getCookie(name){ var cookie=document.cookie.match("\\b"+name+"=([^;]*)\\b") return cookie ? cookie[1]:undefined; } //通过ajax进行跨域请求 function ajaxRuquest(){ var nid=getCookie("_xsrf"); $.post({ url:"/crsf", data:{'k1':'v1',"_xsrf":nid}, success:function (callback){ //ajax发送请求成功后自动执行 //callback等于服务端write的数据 console.log(callback) } }) } </script> </body> </html>View Code
标签:INFO,randomStr,get,self,介绍,session,cookie,详细 From: https://www.cnblogs.com/zongchen/p/17304455.html