[英]Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: Origin checking failed does not match any trusted origins
幫助
失敗原因:
Origin checking failed - https://praktikum6.jhoncena.repl.co does not match any trusted origins.
通常,當存在真正的跨站點請求偽造時,或者未正確使用 Django 的 CSRF 機制時,可能會發生這種情況。 對於 POST forms,您需要確保:
Your browser is accepting cookies.
The view function passes a request to the template’s render method.
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.
您看到此頁面的幫助部分是因為您的 Django 設置文件中有 DEBUG = True。 將其更改為 False,將僅顯示初始錯誤消息。
您可以使用 CSRF_FAILURE_VIEW 設置自定義此頁面。
檢查您是否使用 Django 4.0。 我正在使用 3.2 並在升級到 4.0 時遇到了這個問題。
如果您使用的是 4.0,這是我的修復。 將此行添加到您的settings.py
。 當我使用 3.2 時,這不是必需的,現在我無法在沒有它的情況下發布包含 CSRF 的表單。
CSRF_TRUSTED_ORIGINS = ['https://*.mydomain.com','https://*.127.0.0.1']
查看此行是否需要進行任何更改,例如,如果您需要將https
http
。
根本原因是在 4.0 中添加了原點 header 檢查。
https://docs.djangoproject.com/en/4.0/ref/settings/#csrf-trusted-origins
在 Django 4.0 中更改:
原點 header 檢查不在舊版本中執行。
如果您的django 版本是"4.xx" :
python -m django --version
// 4.x.x
那么,如果報錯如下圖:
來源檢查失敗 - https://example.com與任何受信任的來源都不匹配。
將此代碼添加到“settings.py” :
CSRF_TRUSTED_ORIGINS = ['https://example.com']
在您的情況下,您收到此錯誤:
來源檢查失敗 - https://praktikum6.jhoncena.repl.co與任何受信任的來源都不匹配。
因此,您需要將此代碼添加到“settings.py” :
CSRF_TRUSTED_ORIGINS = ['https://praktikum6.jhoncena.repl.co']
如果像我一樣,當源和主機是同一個域時,您會收到此錯誤。
可能是因為:
settings.py
中設置SECURE_PROXY_SSL_HEADER例如SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
和/或proxy_set_header X-Forwarded-Proto https;
對於 Nginx。在這種情況下:
https://www.example.com
。request.is_secure()
由於 2、3 和 4 而返回False
。_origin_verified()
returns False
because of line 285 of django.middleware.csrf (comparison of https://www.example.com
to http://www.example.com
): def _origin_verified(self, request):
request_origin = request.META["HTTP_ORIGIN"]
try:
good_host = request.get_host()
except DisallowedHost:
pass
else:
good_origin = "%s://%s" % (
"https" if request.is_secure() else "http",
good_host,
)
if request_origin == good_origin:
return True
確保在更改此設置之前閱讀https://docs.djangoproject.com/en/4.0/ref/settings/#secure-proxy-ssl-header中的警告!
實際上,自 Django 4.0 以來,settings.py 中的 CSRF_TRUSTED_ORIGINS 似乎是強制性的。
您也可能出現此錯誤,因為您在 Proxmox 上使用了容器。
如果您的 https 域名由 Proxmox 通過內部 http 連接路由,您將遇到此錯誤。
域名 (https) => Proxmox => (http) => 帶有 Django 的容器:CSRF 錯誤
我遇到了這個錯誤,並通過 https 內部連接將通過 Proxmox 的路由更改到我的容器(我必須在我的 CT 上創建並簽署證書)。
域名 (hhtps) => Proxmox => (https) => 帶有 Django 的容器
由於 Django 上的 CSRF 錯誤消失了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.