如何为移动应用程序客户端的后端 django 使用 CSRF 安全性

How to use CSRF security for a backend django for an mobile application client

我正在使用 Django 开发移动应用程序的后端,其中用于用户注册的用户数据使用 POST 方法发送。由于 Django 提供 CSRF 安全作为中间件。这里我的问题是,如果我有一个前端,我可以通过 jinja 代码启用 CSRF 令牌作为 {% csrf_token %} 但是因为它是一个后端以及如何解决这个问题

一种解决方案是删除 csrf 令牌行表格 setting.py 文件 :)

To guard against these type of attacks, you need to do two things: 1 Ensure that the 'safe' HTTP operations, such as GET, HEAD and OPTIONS cannot be used to alter any server-side state. 2 Ensure that any 'unsafe' HTTP operations, such as POST, PUT, PATCH and DELETE, always require a valid CSRF token. If you're using SessionAuthentication you'll need to include valid CSRF tokens for any POST, PUT, PATCH or DELETE operations. In order to make AJAX requests, you need to include CSRF token in the HTTP header, as described in the Django documentation.

检查此 link。它准确地解释了您的方法应该是什么。

基本上,如果您希望 POST 请求具有 csrf,则需要在 header 中发送 csrf 令牌。但我们不会为未经身份验证的请求要求 csrf 令牌。

如果您还没有使用 Django Rest Framework 来创建 API 会更好