简体   繁体   English

在Django中为简单的注释表单添加CSRF保护

[英]Adding CSRF protection to simple comment forms in Django

I have blog comment forms in Django and I would like to know the following: 我在Django中有博客评论表格,我想知道以下内容:

  1. Should I add CSRF to the forms? 我应该在表单中添加CSRF吗?
  2. If I want to use the simple "render_comment_form" method, how do I add it? 如果我想使用简单的“ render_comment_form”方法,该如何添加?
  3. If I can't add it like that, what is the best practice for doing it? 如果我不能那样添加,这样做的最佳实践是什么?

Each tutorial or discussion on the subject seems to have a different approach, and I am not certain I understand how it all works. 关于该主题的每个教程或讨论似乎都有不同的方法,并且我不确定我是否了解所有方法。

My answer assumes that you are using Django 1.2: 我的答案假设您使用的是Django 1.2:

  1. Yes! 是! You should protect all your data that is sent by POST requests to the server against CSRF attacks. 您应该保护POST请求发送给服务器的所有数据免受CSRF攻击。
  2. You don't need to add the token yourself. 您不需要自己添加令牌。 This is already done by django. django已经做到了。 Have a look at the default template that is used by the render_comment_form tag and you will see, that the csrf_token is already included. 看一下render_comment_form标记使用默认模板,您会发现csrf_token已经包含在内。 You can overwrite this template in your project and including the CSRF token into it is as easy as writing {% csrf_token %} into the form. 您可以覆盖项目中的此模板,并将CSRF令牌包含到其中就像将{% csrf_token %}写入表单一样简单。
  3. There is a way to protect your forms even if you don't set the tokens in the templates. 即使您没有在模板中设置令牌,也有一种保护表单的方法。 Have a look at django's documentation about that topic . 查看有关该主题的django文档 But this method is marked as a legacy method so it's not recommended to use that - it's only provided for backwards compatibility with versions of Django earlier than 1.2. 但是此方法被标记为遗留 方法,因此不建议使用它-仅为了与早于1.2的Django版本向后兼容而提供。

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

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