Tuesday, 14 June 2022

Django + Caddy = CSRF protection issues

I deployed a Django 4 app with Daphne (ASGI) in a docker container. I use Caddy as a reverse proxy in front. It works, except I can't fill in any form because the CSRF protection kicks in. So no admin login, for example.

I can currently access the admin interface in two ways:

  1. Directly through docker, via a SSH tunelled port
  2. Through Caddy, which is then forwarding to the Docker container.

Option 1 works. I can log into the admin interface just as if I was running the development server locally. All is working as expected.

However, option 2 (caddy reverse proxy) doesn't work. I can access Django and load pages, but any form submission will be blocked because the CSRF protection kicks in.

CSRF verification failed. Request aborted.

Reason given for failure:
    Origin checking failed - https://<mydomain.com> does not match any trusted origins.

My Caddyfile contains this:

<mydomain.com> {
       reverse_proxy localhost:8088
}

localhost:8088 is the port exposed by my docker container.

In an effort to eliminate potential issues, I've set the following to false in my config file:

  • SECURE_SSL_REDIRECT (causes a redirect loop, probably related to the reverse proxying)
  • SESSION_COOKIE_SECURE (I'd rather have it set to True, but I don't know at this point)
  • CSRF_COOKIE_SECURE (same remark)

The only Django-Caddy examples I could find online are outdated and refer to older versions of Caddy and/or Django. Django is deployed on ASGI with Daphne.

I've seens posts suggesting to change CSRF_TRUSTED_ORIGINS, but it doesn't seem right that I would have to add a host that is already in the ALLOWED_HOSTS list. That also wouldn't explain why it works directly on the docker container, unless localhost is a special case for CSRF.

Versions:

  • Caddy: 2.5.1
  • Django: 4.0.5
  • Daphne: 3.0.2
  • Python: 3.10.5

Any idea what goes wrong, and how I should go about debugging such issues?



from Django + Caddy = CSRF protection issues

No comments:

Post a Comment