Django CSRF 框架有很多失败
我的站点上的 CSRF Django 中间件(来自 SVN trunk 的版本)出现了许多失败。我得到的唯一错误是: CSRF 失败:原因=CSRF 令牌丢失或不正确。
我如何诊断这些 CSRF 错误来自何处?我自己无法导致 CSRF 错误,但我将网站设置为每当触发 CSRF 错误视图时都会向我发送电子邮件,因此我知道这种情况经常发生。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我真的很努力地把它做好,但最终还是做到了。以下是我的主要问题(Django 1.2 beta):
确保您的设置电子邮件都是正确的。我必须做这样的事情:
EMAIL_HOST='mail.my-domain.com'
EMAIL_HOST_USER='我在服务器上的用户名'
EMAIL_HOST_PASSWORD='密码'
EMAIL_PORT= '26' # 在我读到的许多论坛帖子中通常看起来是 25 或 26
DEFAULT_FROM_EMAIL='[电子邮件受保护]' # 在托管域上,请确保它已设置并发送
SERVER_EMAIL = '[电子邮件受保护]' # 与上面相同的电子邮件
return render_to_response('contact.htm',{'favicon':r'____.ico',
'more_stuff':“……”
'more_stuff':“……”
'more_stuff':“……”
},
context_instance = RequestContext(request))
确保您
的 settings.py 文件中
有:请注意,这实际上不是一个如何做,这只是我为了让我的工作而所做的。现在发布它的原因是我看到论坛上有很多人讨论这个主题,只是关闭 csrf_token。
I really struggled to get it right, but eventually did. Here were my main issues (Django 1.2 beta):
Make sure that your settings emails are all the right ones. I had to do something like this:
EMAIL_HOST='mail.my-domain.com'
EMAIL_HOST_USER='my user name on the server'
EMAIL_HOST_PASSWORD='passwd'
EMAIL_PORT= '26' # often seems to be 25 or 26 on many of the forum posts I read
DEFAULT_FROM_EMAIL='[email protected]' # on hosted domains, make sure it is set up and sending
SERVER_EMAIL = '[email protected]' # Same email as above
return render_to_response('contact.htm',{'favicon':r'____.ico',
'more_stuff':"......"
'more_stuff':"......"
'more_stuff':"......"
},
context_instance = RequestContext(request))
Make sure you have:
in your settings.py file.
Note that this is really not a how to, this is just what I did to get mine working. The reason for posting it now is that I see so many people on forums discussing this topic resort to just turning the csrf_token off.
当中间件成功阻止跨站请求伪造攻击时,应该会发生 CSRF 错误。验证情况的最佳方法可能是检查您的 Web 服务器日志,并且您应该看到与早期请求无关的请求。
A CSRF error should happen when the middleware successfully stops a Cross Site Request Forgery attack. Probably the best way to verify that this is the case it to check your web server logs and you should see requests that aren't related to an earlier request.
此外,您还应该检查
settings.py
文件中MIDDLEWARE_CLASSES
的顺序。应该看起来像这样:最后的
LocaleMiddleware
。对我来说,解决方案是
RequestContext
实例和排序。Also you should check the order of the
MIDDLEWARE_CLASSES
in yoursettings.py
file. Should look something like this:LocaleMiddleware
at the end.For me, the solution was the
RequestContext
instance and the ordering.确保 GET 请求的视图函数如下所示:
然后检查 newform.html 的视图源,它必须有隐藏字段。
在这里,action 可以引用同一页面,
action=""
。Make sure your view function for GET Request looks like this:
Then check the view source for your newform.html, it must have Hidden field.
Here, action can refer the same page,
action=""
.