Certbot으로 SSL을 설정한 후 Django CSRF 확인에 실패했습니다.

Certbot으로 SSL을 설정한 후 Django CSRF 확인에 실패했습니다.

저는 현재 Docker를 활용하는 Django 프로젝트를 진행하고 있으며 최근에 컨테이너화된 버전을 사용하여 SSL 인증서를 설정했습니다.인증서봇HTTPS를 통해 Django 앱을 보호하기 위해. 그러나 SSL 인증서를 구현하고 nginx 구성을 업데이트한 후 'CSRF 확인 실패' 오류가 발생하기 시작했는데, 이는 설정 전에는 문제가 아니었습니다. 이전에는 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/;
    }
}

SSL 인증서를 사용한 새로운 nginx 구성입니다.

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을 아직 설정하지 않은 경우 SSL이 활성화되었을 때 양식을 확인하려면 CSRF_COOKIE_SECURE 설정이 필요하다고 생각합니다.

보다https://docs.djangoproject.com/en/4.2/topics/security/#ssl-https

관련 정보