目录
-
开启XSRF保护
#要开启XSRF保护,需要在Application的构造函数中添加xsrf_cookies参数: app = tornado.web.Application( [(r"/", IndexHandler),], cookie_secret = "2hcicVu+TqShDpfsjMWQLZ0Mkq5NPEWSk9fi0zsSt3A=", xsrf_cookies = True ) #当这个参数被设置时,Tornado将拒绝请求参数中不包含正确的_xsrf值的POST、 #PUT和DELETE请求。 class IndexHandler(RequestHandler): def post(self): self.write("hello itcast") #⽤不带xsrf的post请求时,报出了`HTTP 403: Forbidden ('xsrf' argument missing #from POST)`的错误。
-
模板应用
在模板中使⽤XSRF保护,只需在模板中添加 {% module xsrf_form_html() %} 新建⼀个模板index.html <!DOCTYPE html> <html> <head> <title>测试XSRF</title> </head> <body> <form method="post"> {% module xsrf_form_html() %} <input type="text" name="message"/> <input type="submit" value="Post"/> </form> </body> </html>
#后端 class IndexHandler(RequestHandler): def get(self): self.render("index.html") def post(self): self.write("hello itcast")
模板中添加的语句帮我们做了两件事: 为浏览器设置了_xsrf的Cookie(注意此Cookie浏览器关闭时就会失效) 为模板的表单中添加了⼀个隐藏的输⼊名为_xsrf,其值为_xsrf的Cookie值 渲染后的⻚⾯原码如下: <!DOCTYPE html> <html> <head> <title>测试XSRF</title> </head> <body> <form method="post"> <input type="hidden" name="_xsrf" value="2|543c2206|a056ff9e49df23eaffde0a694cde2b02|1476443353"/> <input type="text" name="message"/> <input type="submit" value="Post"/> </form> </body> </html>
-
非模板应用
'''对于不使⽤模板的应⽤来说,⾸先要设置xsrf的Cookie值,可以在任意的Handler中 通过获取self.xsrf_token的值来⽣成xsrf并设置Cookie。 下⾯两种⽅式都可以起到设置_xsrf Cookie的作⽤。''' class XSRFTokenHandler(RequestHandler): """专⻔⽤来设置_xsrf Cookie的接⼝""" def get(self): self.xsrf_token self.write("Ok") class StaticFileHandler(tornado.web.StaticFileHandler): """重写StaticFileHandler,构造时触发设置_xsrf Cookie""" def __init__(self, *args, **kwargs): super(StaticFileHandler, self).__init__(*args, **kwargs) self.xsrf_token '''对于请求携带_xsrf参数,有两种⽅式: 若请求体是表单编码格式的,可以在请求体中添加_xsrf参数 若请求体是其他格式的(如json或xml等),可以通过设置HTTP头XXSRFToken来传递_xsrf值'''