Understanding csrf in django hidden field in form and CSRFCookie

I am writing my understanding of the csrf protcetion mechanism in django . Please correct me if it is defective.

csrfViewMiddleware creates a unique string and stores it in the hidden field "csrfmiddlewaretoken" of the form coming from the host. Since a malicious website that mimics this form will not know the value of this field, it will not be able to use it.

When someone tries to publish a form, the website checks the csrfmiddlewaretoken field and its value. If this is incorrect or not set, a csrf attempt is detected.

But what is a CSRFCookie ? The doc document states that the unique value is set in CSRFCookie as well as in hidden field . This is where I got confused. sent to browser with unique string embedded? I want someone to explain this a little clearly.

Thank you,

+6
source share
2 answers

So here is my explanation:

Django assigns an authenticated user CSRF token, which is stored in a cookie. The value in this cookie is read every time a user makes a request that is considered "unsafe" (namely POST, PUT, DELETE) to confirm that the user, and not a malicious third-party, makes the request.

The CSRF tag that you place on the form actually grabs the CSRF token from the cookie, and then passes it as a POST variable when the form is submitted.

Hope this makes it a little easier.

+5
source

With my current understanding, I am not completely satisfied with the established answer.

You can find my version here .

To summarize, CSRFCookie is “safe,” in the sense that an attacker cannot gain access to it because of policies of the same origin. The browser will automatically send this value. Now your form should also send this value (for example, in a hidden field). This means that your form must know this value, and it can receive it from the cookie.

An attacker cannot obtain a token from a cookie and, therefore, cannot fake malicious code containing a token.

What is important, in the end, the user can send the csrf token and that the server can check it. Using a cookie is a convenient way to do this, but it can be implemented in different ways (for example, a server can save CSRF tokens for each session, for example).

I am not an expert, but as I understand it. Hope this helps.

+1
source

Source: https://habr.com/ru/post/912011/


All Articles