首页 > 解决方案 > 使用 Django 的 CSRF 攻击

问题描述

我正在开发一个 Django 项目,我可以从外部 url 或文件进行 CSRF 攻击。我怎么能阻止它?

攻击包括:

  1. 我创建了一个包含以下内容的文件:
<html>
   <body>
   <script>history.pushState('', '', '/')</script>
   <form action="https://XXXXXX.com/YYYYY/AAAAAA/LLLLLL">
       <input type="submit" value="Submit request" />
    </form>
   </body>
</html>
  1. 我在我的页面上登录
  2. 我在同一个浏览器中打开文件
  3. 提交按钮

接受请求并执行操作。

谢谢你的一切:)

解决了

django.middleware.csrf.CsrfViewMiddleware如果请求是,则不提供 csrf 保护GET

# Assume that anything not defined as 'safe' by RFC7231 needs protection
if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
    if getattr(request, '_dont_enforce_csrf_checks', False):
        # Mechanism to turn off CSRF checks for test suite.
        # It comes after the creation of CSRF cookies, so that
        # everything else continues to work exactly the same
        # (e.g. cookies are sent, etc.), but before any
        # branches that call reject().
        return self._accept(request)

标签: djangosecuritycsrf

解决方案


更改发布和添加 csrf 令牌的方法

<html>
   <body>
   <script>history.pushState('', '', '/')</script>
   <form action="https://XXXXXX.com/YYYYY/AAAAAA/LLLLLL" method="post">
      {% csrf_token %}

       <input type="submit" value="Submit request" />
    </form>
   </body>
</html>

并在内部处理您的视图:

if request.method == 'POST':
     # your logic here

确保 'django.middleware.csrf.CsrfViewMiddleware' 应该出现在任何假定 CSRF 攻击已被处理的视图中间件之前。


推荐阅读