简体   繁体   English

使用Django使用Javascript生成CSRF令牌

[英]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. 我正在使用Django后端创建Web应用程序,但是大部分繁重的工作将由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. 我一直在和一些同事讨论使用JavaScript而不是Django template tag生成CSRF令牌是否安全。

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. 从我到目前为止所做的研究来看, Django似乎只是将 CSRF_COOKIE设置的值与csrfmiddlewaretoken表单字段中提交的值进行了csrfmiddlewaretoken

Is it insecure to generate a random 32 character string and set the form field value and the cookie with javascript? 生成随机的32个字符串并使用javascript设置表单字段值和cookie是否不安全?

Essentially what you're proposing is a variation of the Double Submit Cookies CSRF prevention method. 本质上,您提议的是Double Submit Cookies CSRF预防方法的一种变体。 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. 之所以可行,是因为攻击者无法在您的域的浏览器中读取或写入Cookie值,因此无法复制要与表单一起提交的相同值。

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. 这是JavaScript方法的最大问题-JavaScript中的随机数生成器不是加密安全的。 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. 捕获鼠标的移动听起来很有趣,但是使用这种方法时必须格外小心-您必须防止在未检测到任何形式的情况下提交任何形式,因为在实际CSRF攻击中可能就是这种情况。 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. 我真的很喜欢SilverlightFox的解释,但我想我会添加一些评论。 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. 借此机会从模板中设置一个javascript变量,然后继续在页面的生命周期中使用它。

{% 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. 它避免了在客户端生成令牌的复杂性,但仍允许您将令牌用于动态创建的任何表单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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