
我目前正在開發一個使用 Docker 的 Django 項目,最近我使用容器化版本設定了 SSL 憑證證書機器人為了透過 HTTPS 保護我的 Django 應用程式。然而,在實施 SSL 憑證並更新 nginx 設定後,我開始遇到「CSRF 驗證失敗」錯誤,這在設定之前不是問題。以前,我可以在使用 HTTP 時登入我的 Django 應用程式。造成這個問題的原因可能是什麼?
我的 Django 設定。
# settings.py
ALLOWED_HOSTS = ["*"]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"corsheaders.middleware.CorsMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
if DEBUG:
CORS_ALLOW_ALL_ORIGINS = True
else:
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = [
'https://example.ph',
]
我之前的 nginx 設定。
upstream api {
server sinag_app:8000;
}
server {
listen 80;
location / {
proxy_pass http://api;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
}
location /static/ {
alias /static/;
}
}
我的新 nginx 設定帶有 SSL 憑證。
upstream api {
server sinag_app:8000;
}
server {
listen 80;
server_name ${DOMAIN};
location /.well-known/acme-challenge/ {
root /vol/www;
}
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name ${DOMAIN};
ssl_certificate /etc/letsencrypt/live/${DOMAIN}/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/${DOMAIN}/privkey.pem;
include /etc/nginx/options-ssl-nginx.conf;
ssl_dhparam /vol/proxy/ssl-dhparams.pem;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
client_max_body_size 4G;
keepalive_timeout 5;
location /static/ {
alias /static/;
}
location / {
proxy_pass http://api;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_redirect off;
}
}
答案1
我不是 SSL 專家,但我在 django 網站上使用了 SSL,我認為設定 CSRF_COOKIE_SECURE 對於在啟動 SSL 時驗證您的表單(如果您尚未設定)是必要的。
看https://docs.djangoproject.com/en/4.2/topics/security/#ssl-https