Django App not returning csrf token on get response.cookie consistently

12 Views Asked by At

Given I have this GET view:

class PublicKeyView(View):
    def get(self, request):
        # Ensure a session ID is available
        if not request.session.session_key:
            request.session.save()

        session_id = request.session.session_key

        private_key, public_key = RSAKeyManager.get_keys(session_id)
        if not private_key or not public_key:
            # Keys are generated as bytes, so decode them before storing
            private_key, public_key = RSAKeyManager.generate_keys()
            RSAKeyManager.store_keys(session_id, private_key.decode('utf-8'), public_key.decode('utf-8'))


        if isinstance(public_key, bytes):
            public_key = public_key.decode('utf-8')
        print(public_key)
        # public_key = public_key.replace('\n', '')
        # Return the public key and session ID
        return JsonResponse({"session_id": session_id, "public_key": public_key}, status=200)

And this settings.py

Django settings for django_backend project.

Generated by 'django-admin startproject' using Django 5.0.2.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""

from pathlib import Path

from utils.utils import get_secrets

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-&sru-aw9zw@2t*hyy7eh&ynb5buu(tw_sd7=xsgt(+6bi5&h4f"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['eliptum.tech']
CSRF_TRUSTED_ORIGINS = ['https://eliptum.tech']

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "backend_app"
]

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",
]

ROOT_URLCONF = "django_backend.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "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 = "django_backend.wsgi.application"

# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'eliptumr_users',
        'USER': 'eliptumr_db',
        'PASSWORD': get_secrets("DB_PASSWORD"),
        'HOST': 'servercp73.20x.host',
        'PORT': '3306',
    }
}

# 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/

STATIC_URL = "static/"

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

SESSION_ENGINE = 'django.contrib.sessions.backends.db'
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ]
}

AUTH_USER_MODEL = 'backend_app.CustomUser'
INPUT_DATA_ENCRYPT = False

If I start a localhost server, and request GET for that view, it include in response.cookies CSRFToken

But if I do the same exact request to the app, but via host, it does not include the token, and I cannot understand why

Isn't the logic for CSRF to sent token via GET, use that received token to do POST requests?

0

There are 0 best solutions below