Django: "Forbidden (403) CSRF verification failed. Request aborted." in Docker Production

2.3k views Asked by At

I am getting this error whenever I am trying to login into Django Admin or Whenever I try to signup in my Django application.

I am using Production in Docker and serving site with http. Whatever I know, this problem is arises because of serving it over http instead of https.

Here is my production settings.py:

SECURE_HSTS_SECONDS = 518400
SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool('DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS', default=True)
SECURE_CONTENT_TYPE_NOSNIFF = env.bool('DJANGO_SECURE_CONTENT_TYPE_NOSNIFF', default=True)
# SECURE_BROWSER_XSS_FILTER = True
SESSION_COOKIE_SECURE = False
SESSION_COOKIE_HTTPONLY = True
SECURE_SSL_REDIRECT = env.bool('DJANGO_SECURE_SSL_REDIRECT', default=False)
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_HTTPONLY = True
X_FRAME_OPTIONS = 'DENY'

I know I have to make some changes into this setting to make it work, but I don't know which one.

2

There are 2 answers

1
Adi Mabfalin On

Try the answer from this question:

You need to add {% csrf_token %} in your form

https://docs.djangoproject.com/en/1.4/ref/contrib/csrf/

like that :

<form>
    {% csrf_token %}
    <anything_else>
</form>

Also, you have to use RequestContext(request) everytime you use render_to_response :

return render_to_response("login.html",
    {"registration_id":registration_id},
    context_instance=RequestContext(request))

And you have to import authenticate and login :

from django.contrib.auth import authenticate, login
0
Philippe F On

Check if your error message includes a line like :

  Origin checking failed - http://my.web.site.com does not match any trusted origins.

If that's the case, your problem is probably that your django code running inside Docker sees a request as coming from a different site (the one outside Docker) and complains about it.

Proper solution is to trust your site. Add a line like this one to your settings.py :

CSRF_TRUSTED_ORIGINS = [
    'http://my.web.site.com',
]

See Django documentation for more details: Cross Site Request Forgery protection