I have a react app, and sending requests as such:
const public_key_r = await axios.get("https://eliptum.tech/get-public-key", { withCredentials: true, // This is crucial for cookies to be sent and received in cross-origin requests }, ); const publicKey = public_key_r.data.publicKey; const csrfToken = public_key_r.data.csrf_token; console.log(csrfToken); const encryptedPassword = await encryptData(password, publicKey, false); const response = await axios.post("https://eliptum.tech/user/create", { username, encryptedPassword, email, phone_number: phoneNumber, }, { withCredentials: true, headers: {"X-CSRFToken": csrfToken, }, }, );
My Backed view for https://eliptum.tech/get-public-key get request is:
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') # Retrieve CSRF token csrf_token = get_token(request) # Construct the JSON response response_data = {"session_id": session_id,"public_key": public_key,"csrf_token": csrf_token } # Create JsonResponse with the response data response = JsonResponse(response_data, status=200) # Set CSRF token as a cookie in the response # Ensure the Secure and SameSite attributes are correctly set for cross-origin compatibility response.set_cookie('csrftoken', csrf_token, secure=True, samesite='None') response['Access-Control-Allow-Credentials'] = 'true' return response
Settings are:
"""Django settings for django_backend project.Generated by 'django-admin startproject' using Django 5.0.2.For more information on this file, seehttps://docs.djangoproject.com/en/5.0/topics/settings/For the full list of settings and their values, seehttps://docs.djangoproject.com/en/5.0/ref/settings/"""from pathlib import Pathfrom 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 = TrueINSTALLED_APPS = ["django.contrib.admin","django.contrib.auth","django.contrib.contenttypes","django.contrib.sessions","django.contrib.messages","django.contrib.staticfiles","backend_app","corsheaders",]MIDDLEWARE = ["corsheaders.middleware.CorsMiddleware","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/#databasesDATABASES = {'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-validatorsAUTH_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 = TrueUSE_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-fieldDEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"SESSION_ENGINE = 'django.contrib.sessions.backends.db'REST_FRAMEWORK = {'DEFAULT_AUTHENTICATION_CLASSES': ['rest_framework.authentication.TokenAuthentication', ]}SANDBOX = "https://7w37f9-3000.csb.app"AUTH_USER_MODEL = 'backend_app.CustomUser'INPUT_DATA_ENCRYPT = FalseCORS_ORIGIN_ALLOW_ALL = FalseCORS_ORIGIN_WHITELIST = ['https://eliptum.tech', SANDBOX,]ALLOWED_HOSTS = ['eliptum.tech', SANDBOX]CSRF_TRUSTED_ORIGINS = ['https://eliptum.tech', SANDBOX]CORS_ALLOW_CREDENTIALS = TrueCORS_ALLOWED_ORIGINS = ['https://eliptum.tech', SANDBOX]
Added everything i could find to make cross origin work but, no, for: const response = await axios.post( "https://eliptum.tech/user/create"
Backend has django-cors-headers and response.set_cookie('csrftoken', csrf_token, secure=True, samesite='None') response['Access-Control-Allow-Credentials'] = 'true'
All requests have withCredentials: true
for axios, not sure what's missing or what's not configured properly, if anything
Basically i have my backed at eliptum.tech host, and frontend on some sandbox, but there is no way for me to make em work together it seems
Not sure if you can access https://7w37f9-3000.csb.app/#, its the frontend that you could test what im saying, gotta select signin/signup and then signup with a random account
Issue is i cannot do the post request because:
Reason given for failure: CSRF cookie not set.
Which is fair considering no cookies are set :(