Hello I am learning Django i write a app and publish it in AWS EC2 instance with gunicorn and ngnix
on local environments everything works fine but in production on every submit on forms i get this 403 Error :
Forbidden (403)
CSRF verification failed. Request aborted.
More information is available with DEBUG=True.
iam sure in templates every form have {% csrf_token %} and this is my setting.py file of django app:
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'
this is my ngnix config :
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;
}
}
i dont have idea what i must do and why this happen and also iam not professional so if i do a silly misstake take it easy on me thank you
update ( I turn debug to True ) i get this error page now :
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
Answers
You need to include CSRF_TRUSTED_ORIGINS in your settings.py
The reason you get this error is because you are requesting your website with https but you have not defined the 443 port on nginx. Here is a post to do this using AWS.
Here is a simple example:
Notice I have added this line
return 301 https://winni-furnace.ca$request_uri;
which will redirect all http request to https automatically.