跨域请求未设置cookies,ReactJs,Django后端,Firefox + Chrome

0 投票
1 回答
42 浏览
提问于 2025-04-14 18:22

我有一个React应用程序,发送请求的方式如下:

        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,
        },
      },
    );

我在https://eliptum.tech/get-public-key的后端视图处理GET请求的代码是:


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

设置如下:

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



INSTALLED_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/#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',
    ]
}

SANDBOX = "https://7w37f9-3000.csb.app"

AUTH_USER_MODEL = 'backend_app.CustomUser'
INPUT_DATA_ENCRYPT = False
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = [
    'https://eliptum.tech',
    SANDBOX,
]
ALLOWED_HOSTS = ['eliptum.tech', SANDBOX]
CSRF_TRUSTED_ORIGINS = ['https://eliptum.tech', SANDBOX]
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = ['https://eliptum.tech', SANDBOX]

我尝试了所有能找到的设置来让跨域请求正常工作,但是没有成功,比如:

const response = await axios.post( "https://eliptum.tech/user/create"

后端使用了django-cors-headers,并且有这段代码:response.set_cookie('csrftoken', csrf_token, secure=True, samesite='None') response['Access-Control-Allow-Credentials'] = 'true'

所有的请求都设置了withCredentials: true,但我不太确定缺少了什么或者配置得不对的地方。

基本上,我的后端在eliptum.tech上,前端在某个沙盒环境里,但看起来我无法让它们一起工作。

不确定你能否访问https://7w37f9-3000.csb.app/#,这是前端,你可以测试我说的内容,得选择登录/注册,然后用一个随机账户注册。

问题是我无法发送POST请求,因为:

Reason given for failure:

    CSRF cookie not set.

这也算合理,因为没有设置cookie :(

1 个回答

0

看起来除了我到目前为止添加的所有内容,在Django的设置里还需要加上这一行:

CSRF_COOKIE_SAMESITE = 'None'

撰写回答