简体   繁体   English

部署到 AWS 服务器时 django 应用程序的 CSRF 令牌错误

[英]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)我有一个在本地运行良好的 django 站点,但是在尝试使用 AWS elastic beanstalk 进行部署时,当我尝试登录时出现以下错误(使用 django allauth)

Forbidden (403) CSRF verification failed.禁止 (403) CSRF 验证失败。 Request aborted.请求中止。

The logs state:日志状态:

Forbidden (CSRF cookie not set.): /accounts/login/禁止(未设置 CSRF cookie。):/accounts/login/

My settings.py middleware has:我的 settings.py 中间件有:

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如果我注释掉“django.middleware.csrf.CsrfViewMiddleware”那么它工作正常

The form has a csrf_token:表单有一个 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.如果您最近升级到 Django 4.0,您现在需要设置 CSRF_TRUSTED_ORIGINS - 这在我的情况下修复了错误。 https://docs.djangoproject.com/en/4.0/ref/settings/#csrf-trusted-origins https://docs.djangoproject.com/en/4.0/ref/settings/#csrf-trusted-origins

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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