Issue with CORS, CSRF, Session Authentication

Hello everyone,

I’m having a problem accessing the CSRF cookie in my Django project. My frontend is separate from my backend, and both use HTTPS. I’m trying to retrieve the csrftoken cookie in the frontend using a get_cookie(name) function, but I can’t get its value.

Here’s the code I use to retrieve the cookie:

const get_cookie = (name) => {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
};

const csrfToken = get_cookie('csrftoken');

However, document.cookie doesn’t return anything, even though I can see the csrftoken cookie in the “Cookies” tab of the browser’s development tools. I did check the cookie configuration in Django (CSRF_COOKIE_HTTPONLY = False), but this doesn’t seem to solve the problem.

Here’s Django’s configuration in settings.py :

CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = ["https://example.com"]
CSRF_TRUSTED_ORIGINS = ["https://example.com"]
CSRF_COOKIE_HTTPONLY = False
CSRF_USE_SESSIONS = False
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_NAME = 'csrftoken'
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SAMESITE = 'None'
CSRF_COOKIE_SAMESITE = 'None'

Details:

  • The frontend and backend are on different domains.
  • The backend is hosted on Railway, and I use HTTPS for both the frontend (https://example.com) and the backend.
  • In my CORS configuration, I’ve added my frontend URL to CORS_ALLOWED_ORIGINS and CSRF_TRUSTED_ORIGINS

I’ve also added credentials: ‘include’ to my fetch requests to make sure the cookies are sent, but I still can’t get the cookie value in JavaScript. The cookies are indeed present in the cookies tab in applications, but it’s impossible to retrieve them with “document.cookie”. I should also point out that these cookies are sent in the request header in the Cookies section.

Has anyone encountered a similar problem or can help me understand why I can’t access the cookie? I’m a bit lost and would really appreciate any help or suggestions.

Thanks in advance!

Welcome @DeepLeau !

Please post your INSTALLED_APPS and MIDDLEWARE sections from your settings.

Yes of course ! Here are the INSTALLED_APPS :

INSTALLED_APPS = [
    'django.contrib.admin',
    'users',
    'gallery',
    'corsheaders',
    'rest_framework',
    'django.contrib.humanize',
    'django.contrib.auth',
    'django.contrib.sessions',
    'django.contrib.contenttypes',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_celery_beat',
]

and MIDDLEWARE :

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',  
    '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',
]

Does anyone know how to solve this problem? @KenWhitesell ?

Please do not tag individuals (any individual) requesting assistance.

Everyone here are volunteers, answering questions as time, knowledge, and energy permits. Depending upon a number of factors, it may take more than a week for the right person to see the question and respond.

Speaking for myself, I don’t deploy to hosting service providers, so I don’t know what information may be available for diagnosing or correcting this.
My prior response was to get you to post what I think the important information someone else would need to know to try and help.