CSRF Token doesn’t work in production environment

  Kiến thức lập trình

My environment: Django backend deployed on Elastic Beanstalk behind a application load balancer that terminates ssl.

The flow is: my website is served on S3 and cloudfront on domain: https://www.test.app.mydomain.com/. This sends request to backend which has domain: https://api.test.mydomain.com/. The request grabs the csrftoken in browser cookies and includes it in the headers.

CSRF tokens work locally, but it doesn’t work in my production environment. Most importantly, there is no csrftoken in the browser cookies in the production environment.

These are my settings that are relevant:

MIDDLEWARE = [
    # keep on top
    'corsheaders.middleware.CorsMiddleware',
    # rest of the middleware
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]
SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies"

SESSION_COOKIE_AGE = 7200  # 2 hours

SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
CSRF_TRUSTED_ORIGINS = ['http://localhost:3000', 'https://www.test.app.mydomain.com', 'https://test.app.mydomain.com']
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
USE_X_FORWARDED_HOST = True

CORS_ALLOWED_ORIGINS = ['http://localhost:3000', 'https://www.test.app.mydomain.com', 'https://test.app.mydomain.com']
CORS_ALLOW_CREDENTIALS = True

CORS_ALLOW_HEADERS = list(default_headers) + [
    'Tab-ID',
]

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT