How does CSRF validation work in Django and why do 2 different tokens still pass the check?

46 views Asked by At

I'm currently reading up on CSRF and was wondering how is it possible for the CSRF validation in Django to validate 2 tokens as equal even if the values differ?

if not _does_token_match(request_csrf_token, csrf_token):
    reason = self._bad_token_message("incorrect", token_source)
    raise RejectRequest(reason)

This is the token check function, and it consists of:

def _does_token_match(request_csrf_token, csrf_token):
    # Assume both arguments are sanitized -- that is, strings of
    # length CSRF_TOKEN_LENGTH, all CSRF_ALLOWED_CHARS.
    return constant_time_compare(
        _unmask_cipher_token(request_csrf_token),
        _unmask_cipher_token(csrf_token),
    )

I've used the CSRF token that Django automatically generates and returns back in the response, and one which I generated manually with the get_token function from django.middleware.csrf and the result of _does_token_match is True. Not sure that I understand why is that.

0

There are 0 answers