简体   繁体   中英

CSRF token error for django app when deploying to AWS server

I have a django site that runs fine locally but when trying to deploy with AWS elastic beanstalk I get the following error when I try to login (using django allauth)

Forbidden (403) CSRF verification failed. Request aborted.

The logs state:

Forbidden (CSRF cookie not set.): /accounts/login/

My settings.py middleware has:

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

If I comment out "django.middleware.csrf.CsrfViewMiddleware" then it works fine

The form has a csrf_token:

<form class="login" method="POST" action="{% url 'account_login' %}">
  {% csrf_token %}
  {{ form|crispy }}
  {% if redirect_field_value %}
  <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
  {% endif %}
  <a class="button secondaryAction" href="{% url 'account_reset_password' %}">{% trans "Forgot Password?" %}</a>
  <button class="primaryAction btn btn-primary" type="submit">{% trans "Sign In" %}</button>
</form>

Any advice as to how to fix and why it runs ok locally but not when deployed appreciated

Try to reorder the middlewares. They are exequted sequentially. So any middleware passes the request to the next and if something has been blocked it will not be available for the next middleware and so on

尝试SESSION_COOKIE_SECURE = True设置以保护您的 cookie 当 cookie 不安全时会发生此错误 可能调试为 True 确保其 False DEBUG = False有时为中间件订单重新排序您的中间件

If you've recently upgraded to Django 4.0, you now need to set CSRF_TRUSTED_ORIGINS - that fixed the error in my case. https://docs.djangoproject.com/en/4.0/ref/settings/#csrf-trusted-origins

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