django CSRF_TRUSTED_ORIGINS 未按预期工作

问题描述 投票:0回答:2

我无法理解为什么来自第三方网站的帖子被拒绝,即使该网站已添加到 settings.py 中的

CSRF_TRUSTED_ORIGINS
列表中。在发布说明 csrf 检查失败的帖子后,我收到了 403 错误。我认为将网站添加到
CSRF_TRUSTED_ORIGINS
应该可以使网站免受 csrf 检查。为了接收来自外部来源的帖子请求,我还应该做些什么吗?我正在运行 django 3.2

CSRF_TRUSTED_ORIGINS = ['site.lv']

请求标头:

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,lv;q=0.8,ru;q=0.7
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 899
Content-Type: application/x-www-form-urlencoded
Host: cvcentrs-staging.herokuapp.com
Origin: https://www.site.lv
Pragma: no-cache
Referer: https://www.site.lv/
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Microsoft Edge";v="96"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: cross-site
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62
python python-3.x django csrf django-csrf
2个回答
32
投票

这个假设是错误的:

我认为将网站添加到 CSRF_TRUSTED_ORIGINS 应该可以使网站免受 csrf 检查。

将 URL 添加到

CSRF_TRUSTED_ORIGINS
只是允许来自外部域上的表单的 POST 请求所需要做的一件事。您还需要:

从Django 4.0开始,你必须在

CSRF_TRUSTED_ORIGINS
中包含该方案:

CSRF_TRUSTED_ORIGINS = ['https://site.lv', 'https://www.site.lv']

6
投票

为了启用 CSRF_TRUSTED_ORIGINS,请按照以下步骤操作

  1. pip install django-cors-headers

已安装的应用程序

  1. INSTALLED_APPS = [ 'corsheaders', ]

中间件

  1. MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ]

确保添加https

  1. CSRF_TRUSTED_ORIGINS = ['https://site.lv']

  2. 如果仍然不起作用,请在函数之前将此装饰器添加到您的视图中

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt 
def login(): pass
© www.soinside.com 2019 - 2024. All rights reserved.