简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM