CSRF django nginx with ssl from cloudflare

Background

I am trying to configure a Django application to work with the ssl provided by cloudflare. I have about the same setup as this answer , and they performed the same solution.

Question:

It killed me for several weeks (please help!), Since I am not a network / security guy, and I just need a solution that will allow me not to take my eyes out, but to keep the site safe.

I am currently getting a CSRF issue where https://www.domain.co.uk does not match https://domain.co.uk

Config

Settings.py

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
USE_X_FORWARDED_HOST = True

Nginx:

server {

    listen 80 default_server;

    server_name domain.co.uk www.domain.co.uk;
    access_log off;

    location /static/ {
        alias /static/;
    }


    location / {
            proxy_pass http://127.0.0.1:8000;
            proxy_set_header X-Forwarded-Host $server_name;
            proxy_set_header X-Real-IP $remote_addr;
            add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';

            proxy_set_header X-Scheme $scheme;
            proxy_set_header X-Forwarded-Protocol $scheme;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            }
}

Cloudflare DNS:

A domain.co.uk  points to <ip> Automatic
CNAME www is an alias of domain.co.uk Automatic 

Bonus

, .com , , ssl.

+4
2

, cookie CSRF. CSRF_COOKIE_DOMAIN ".domain.co.uk" CSRF_COOKIE_SECURE True .

โ„–4 https://docs.djangoproject.com/en/1.9/ref/csrf/#how-it-works

+3

nginx, Django. , CSRF , . , ... nginx, , . Django.

nginx , , , 301 www. -www, http https.

nginx:

server_name domain.co.uk www.domain.co.uk;

server_name domain.co.uk;  # This assumes you're directing www. to non-www

CSRF... , .

301 , .

[EDIT] , CNAME www. -www, https -https 301 , .

+1

Source: https://habr.com/ru/post/1622939/


All Articles