你好,我正在学习Django,我写了一个应用程序,并在本地环境中使用gunicorn和ngnix在AWS EC2示例中发布它,一切正常,但在生产中,每次提交表单时,我都会收到这个403错误:
Forbidden (403)
CSRF verification failed. Request aborted.
More information is available with DEBUG=True.
字符串
我确信在模板中每个表单都有{% csrf_token %},这是我的setting.py django应用程序文件:
import os
from pathlib import Path
from decouple import config
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = config("DJANGO_SECRET_KEY")
SITE_ID = 1
DEBUG = False
ALLOWED_HOSTS = ["winni-furnace.ca", "www.winni-furnace.ca"]
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_DOMAIN = '.winni-furnace.ca'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.sitemaps',
# local
'accounts.apps.AccountsConfig',
'blog.apps.BlogConfig',
'mail_service.apps.MailServiceConfig',
'messages_app.apps.MessagesAppConfig',
'offers.apps.OffersConfig',
'pages.apps.PagesConfig',
'projects.apps.ProjectsConfig',
'score.apps.ScoreConfig',
'services.apps.ServicesConfig',
# 3rd
'taggit',
"django_social_share",
"whitenoise.runserver_nostatic"
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'app.urls'
INTERNAL_IPS = [
# ...
"127.0.0.1",
# ...
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates']
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'app.wsgi.application'
AUTH_USER_MODEL = "accounts.CustomUser"
LOGIN_REDIRECT_URL = "pages:index"
LOGOUT_REDIRECT_URL = "pages:index"
# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': config('POSTGRES_DB'),
'USER': config('POSTGRES_USER'),
'PASSWORD': config('POSTGRES_PASSWORD'),
'HOST': 'wiinidb.cxmwqowm20bd.us-east-1.rds.amazonaws.com',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = "django_ses.SESBackend"
AWS_SES_REGION_NAME = "us-west-1"
ASW_SES_REGION_ENDPOINT = "email-smtp.us-west-1.amazonaws.com"
EMAIL_HOST_USER = "[email protected]"
STATIC_URL = "/static/"
STATICFILES_DIRS = [BASE_DIR / "static"]
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
AWS_ACCESS_KEY_ID = config("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = config("AWS_SECRET_ACCESS_KEY")
AWS_STORAGE_BUCKET_NAME = 'wiini'
AWS_S3_SIGNATURE_NAME = config("AWS_S3_SIGNATURE_NAME")
AWS_S3_REGION_NAME = 'ca-central-1'
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
AWS_S3_VERITY = True
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
型
这是我的ngnix配置:
server{
listen 80;
server_name winni-furnace.ca www.winni-furnace.ca;
location /static/ {
root /home/ubuntu/winnipeg_prod/app/staticfiles;
}
location / {
include proxy_params;
proxy_pass http://unix:/home/ubuntu/winnipeg_prod/app/app.sock;
}
}
型
我不知道我必须做什么,为什么会发生这种情况,而且我不专业,所以如果我做了一个愚蠢的错误,请对我放松,谢谢
update(我把debug设置为True)我现在得到这个错误页面:
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
Origin checking failed - https://winni-furnace.ca does not match any trusted origins.
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure:
Your browser is accepting cookies.
The view function passes a request to the template’s render method.
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login.
You’re seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.
You can customize this page using the CSRF_FAILURE_VIEW setting.
型
2条答案
按热度按时间inn6fuwd1#
一切正常,但在生产上的每一个形式提交我得到这个403错误
你得到这个错误的原因是因为你用https请求你的网站,但你没有在nginx上定义443端口。这里是一个post使用AWS来做这件事。
下面是一个简单的例子:
字符串
注意,我添加了这行
return 301 https://winni-furnace.ca$request_uri;
,它会自动将所有http请求重定向到https。qnakjoqk2#
您需要在settings.py中包含CSRF_TRUSTED_ORIGINS
字符串