Home > other >  Django forbidden 403 Origin checking failed csrf failed
Django forbidden 403 Origin checking failed csrf failed

Time:09-07

I'm running django on a docker machine. Everything works just fine, but when I want to login into the admin site I get 403 forbidden

Origin checking failed - https://example.com does not match any trusted origins.

I've tried to add some other settings like:

ALLOWED_HOSTS = [
    "example.com",
    "127.0.0.1",
    "localhost",
]

CSRF_TRUSTED_ORIGIN = ["https://example.com"]

if PRODUCTION:
    CSRF_COOKIE_SECURE = True
    SESSION_COOKIE_SECURE = True

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

as it is mentioned here and here but it doesn't work either.

This is my nginx setup:

server {
        server_name example.com;

        location = /favicon.ico {
                access_log off;
                log_not_found off;
        }

        location /static/ {
                alias /home/example/data/static/;
        }

        location /media/ {
                alias /home/example/data/media/;
        }

        location / {
                proxy_pass http://127.0.0.1:8000;
        }

        listen 443 ssl; # managed by Certbot
        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

how do I fix this error?

CodePudding user response:

I've managed to fix this error by adding:

SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")

into django settings and

include proxy_params;

into nginx configuration

  • Related