According to my understanding, the way Django verifies CSRF is by comparing the
request.POST.get('csrfmiddlewaretoken', '') | request.META.get(settings.CSRF_HEADER_NAME, '') == request.session.get(CSRF_SESSION_KEY) | request.COOKIES[settings.CSRF_COOKIE_NAME]
Now the way, these 2 tokens (one from LHS and one from RHS) are compared is by the deciphering using following function
The 2 tokens being compared, are different, but are deciphered to the same "secret".
My question is shouldn't Django ensure that they are different ? Whats the purpose of using the 2 different tokens(and the overhead of deciphering them),if not ensuring they are different ?
I think the questioner has few different doubts
Why is the token set in the cookie
This is explained in jd.'s and Mike DeSimone's answers.
In short to support AJAX posting and avoid any server side state storage
Why is the tokens salted ? This is explained in Jacques Gaudin's answer
In short to prevent BREACH attack
Why can't we use a single salted token in both the form and cookie ?
I think that's because if we use the same salted token, then we'll need to store the secret (unsalted token) in the server side.