How Will the Inclusion of Two Forms Affect my CSRF Token Use?

两盒软妹~` 提交于 2019-12-10 13:55:42

问题


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).

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?

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);

回答1:


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.

You can do something like

<form action="." >{% csrf_token %}
    {{form1.as_p}}
</form>

when you do data=form.serialize(), the csrf token is automatically serialized in the data of the ajax request.

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.



来源:https://stackoverflow.com/questions/17537562/how-will-the-inclusion-of-two-forms-affect-my-csrf-token-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!