Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSRF django nginx with ssl from cloudflare

Background

I'm trying to configure my Django app to work with ssl provided by cloudflare. I have about the same setup as this answer and have followed the same solution.

Issue:

This has been killing me for weeks (please help!) as I am not a networking/security guy and just need a solution that will avoid me gouging my eyes out but keep the site secure.

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

In addition I also have the .com for the domain and would like to know how best to set this up so that it is also ssl.

like image 616
Silian Rails Avatar asked Jan 05 '16 15:01

Silian Rails


1 Answers

You need to setup the domain which is sending the CSRF cookie. Try setting CSRF_COOKIE_DOMAIN to ".domain.co.uk" and CSRF_COOKIE_SECURE to True in your settings.

Point #4 is worth reading https://docs.djangoproject.com/en/1.9/ref/csrf/#how-it-works

like image 111
fasouto Avatar answered Oct 04 '22 20:10

fasouto