两种形式的包含将如何影响我的CSRF令牌使用? [英] How Will the Inclusion of Two Forms Affect my CSRF Token Use?
问题描述
我正在尝试创建一个包含两种形式的页面:一种在页面加载时可见(登录表单),另一种在用户单击按钮时在模式中显示(注册表单).
I am attempting to create a page that includes two forms: one that is visible when the page loads (a signin form), and a second that appears in a modal if the user clicks a button (a signup form).
我正在使用Django,尽管我仍在弄清楚如何处理这些形式,但我最大的担忧是CSRF令牌如何在所有这些方面发挥作用.例如,我应该只在一个<form></form>
标签中使用{% csrf_token %}
,还是应该在两个标签中都放置它?
I am using Django, and, although I am still figuring out how I will handle these forms, my largest concern is how the CSRF token will play into all of this. For example, should I use {% csrf_token %}
inside of only one of my <form></form>
tags, or should I place it in both?
此外,如果我同时使用这两种形式,这会以任何方式影响我到服务器的POSTS吗?目前,我以表格形式获取数据(具体取决于单击了哪个提交按钮),并以这种方式发布:
Further, if I do use it in both forms, will this affect my POSTS to the server in any way? Currently, I am taking the data in a form (depending on which submit button is clicked) and POSTing this way:
var data={
'username':$('#username').val(),
'password':$('#password').val(),
'csrfmiddlewaretoken': '{{ csrf_token }}'
}
$.post("/", signin_data);
推荐答案
csrf_token
应该放在两种形式中,只要两者都是通过GET
或POST
在服务器端访问的,并且是您可以可以对两个表单使用相同的csrf_token
,而不会出现任何问题.
csrf_token
should be placed in both the forms, as long as both are being accessed on the server side via GET
or POST
, and YES you can use the same csrf_token
for both the forms without any issues.
您可以做类似的事情
<form action="." >{% csrf_token %}
{{form1.as_p}}
</form>
当您执行data=form.serialize()
时,csrf
令牌会自动在ajax请求的data
中序列化.
when you do data=form.serialize()
, the csrf
token is automatically serialized in the data
of the ajax request.
多个{% csrf_token %}
起作用的原因是,所有令牌所做的都是为了提供信息以验证表单请求来自有效(未经篡改)用户会话.
The reason multiple {% csrf_token %}
works is because all the token does is provide information for validation that a form request is from a valid (untampered) user session.
这篇关于两种形式的包含将如何影响我的CSRF令牌使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!