我目前正在开发一个使用 Docker 的 Django 项目,最近我使用容器化版本的Certbot以便通过 HTTPS 保护我的 Django 应用程序。但是,在实施 SSL 证书并更新我的 nginx 配置后,我开始遇到“CSRF 验证失败”错误,这在设置之前不是问题。以前,当我的 Django 应用程序使用 HTTP 时,我能够登录它。这个问题可能是什么原因造成的?
我的 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,并且我认为如果您尚未设置,则在激活 SSL 时设置 CSRF_COOKIE_SECURE 是验证您的表单所必需的。
看https://docs.djangoproject.com/en/4.2/topics/security/#ssl-https