简体   繁体   中英

CSRF Token Generation in Javascript with Django

I'm creating a web application with a Django backend, but most of the heavy lifting will be done with Javascript. I've been having a debate with some colleagues about whether or not it would be secure to generate the CSRF token with javascript instead of the Django template tag.

From the research that I've done so far, it looks like Django just compares the value set in the CSRF_COOKIE with the value submitted in the csrfmiddlewaretoken form field.

Is it insecure to generate a random 32 character string and set the form field value and the cookie with javascript?

Essentially what you're proposing is a variation of the Double Submit Cookies CSRF prevention method. This works because an attacker cannot read or write the cookie value in the browser for your domain, so cannot duplicate the same value to be submitted with the form.

When a user authenticates to a site, the site should generate a (cryptographically strong) pseudorandom value

This is the biggest problem with the JavaScript approach - the random number generator in JavaScript is not cryptographically secure. You could try one of the solutions here - your mileage may vary between browsers. Capturing mouse movement sounds interesting but care must be taken with this approach - you will need to prevent any forms from being submitted where there is none detected as that may be the case in a real CSRF attack. If possible try and avoid anything fancy such as this as with security it is best to keep things simple - complexity is the enemy of security.

I really like the explanation by SilverlightFox, but I figured I'd add some commentary. Your server is already involved for at least the first request. Take that opportunity to set a javascript variable from your template, and continue to use that for the lifecycle of the page.

{% extends 'base.html' %}

<script>
    window.csrf_token = "{% csrftoken %}";
</script>

It avoids the complexity of generating tokens client side, but still allows you to use the token for any forms you create dynamically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM