Django中是否同时需要csrftoken cookie和csrf_token输入类型?
在Django中,csrftoken
这个cookie有什么用呢?我们每次提交表单都需要发送{% csrf_token %}
。
<form method="post" action="actionFile/">
{% csrf_token %}
<button>Submit</button>
</form>
Django的处理器总是要求提供{% csrf_token %}
。
难道我们每个表单都必须放{% csrf_token %}
吗?Django的处理器就不能利用csrftoken
这个cookie吗?
虽然{% csrf_token %}
可能是为了防止伪造请求,但那这个cookie又有什么用呢?
请解释一下。
2 个回答
CSRF的意思是:跨站请求伪造
这是一种在网络应用中非常常见的攻击方式。所以不仅是Django,大多数其他框架,比如Ruby on Rails,也都有防止这种攻击的措施。
在Django中,防止这种攻击的方法是通过发送"csrfmiddlewaretoken"作为POST数据。Django会把这个令牌的值和合法的值进行比对。如果匹配,请求就通过了;否则,就会抛出错误。
{% csrf_token %}模板标签会生成一个隐藏的输入字段,里面包含合法的CSRF令牌值。
所有的处理和错误抛出都是在CsrfViewMiddleware中完成的。你可以在Django文档中找到更多信息(解释得很清楚):https://docs.djangoproject.com/en/1.6/ref/contrib/csrf/
Cross-site request forgery, also known as a one-click attack or session riding and
abbreviated as CSRF or XSRF, is a type of malicious exploit of a website whereby
unauthorized commands are transmitted from a user that the website trusts.Unlike cross-
site scripting (XSS), which exploits the trust a user has for a particular site, CSRF
exploits the trust that a site has in a user's browser.
使用一个秘密的cookie
Remember that all cookies, even the secret ones, will be submitted with every request.
All authentication tokens will be submitted regardless of whether or not the end-user
was tricked into submitting the request. Furthermore, session identifiers are simply
used by the application container to associate the request with a specific session
object. The session identifier does not verify that the end-user intended to submit
the request.
只接受POST请求
Applications can be developed to only accept POST requests for the execution of business
logic. The misconception is that since the attacker cannot construct a malicious link,
a CSRF attack cannot be executed. Unfortunately, this logic is incorrect. There are
numerous methods in which an attacker can trick a victim into submitting a forged POST
request, such as a simple form hosted in attacker's website with hidden values. This
form can be triggered automatically by JavaScript or can be triggered by the victim who
thinks form will do something else.
Django在你每次请求服务器的时候都会设置一个叫csrftoken的cookie。当你从客户端向服务器发送数据时,这个token会和服务器上的token进行匹配。如果匹配成功,就没问题;如果不匹配,就会报错,说明这是一个恶意请求。
如果你想要在某个特定的视图中关闭CSRF保护,可以使用csrf_exempt这个装饰器。
from django.views.decorators.csrf import csrf_exempt
然后在你的视图前面写上@csrf_exempt