当前端在本地主机上而后端在远程服务器上时,DRF set_cookie不工作



我创建了一个DRF应用程序,后端使用jwt身份验证和httpolnly cookie进行身份验证,它还使用enforce_csrf来抵御csrf攻击。

from rest_framework_simplejwt.authentication import JWTAuthentication
from django.conf import settings
from rest_framework.authentication import CSRFCheck
from rest_framework import exceptions
def enforce_csrf(request):
check = CSRFCheck()
check.process_request(request)
reason = check.process_view(request, None, (), {})
print(reason)
if reason:
raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)
class CookieBasedJWTAuthentication(JWTAuthentication):
def authenticate(self, request):
header = self.get_header(request)

if header is None:
raw_token = request.COOKIES.get(settings.SIMPLE_JWT['AUTH_COOKIE_ACCESS']) or None
else:
raw_token = self.get_raw_token(header)
if raw_token is None:
return None

validated_token = self.get_validated_token(raw_token)
enforce_csrf(request)
return self.get_user(validated_token), validated_token

对于变态的csrf攻击,django设置了一个cookie和一个"csrftokenmiddleware",并对它们进行比较。

以下是设置csrf cookie和令牌的示例代码:

class SetCSRFToken(APIView):
permission_classes = [AllowAny]
def get(self, request):
response = Response() 
csrf.get_token(request)
response.status_code = status.HTTP_200_OK
csrf_secret = csrf.get_token(request)
response.set_cookie(
key = 'csrftoken', 
value = request.META["CSRF_COOKIE"],
expires = settings.SIMPLE_JWT['REFRESH_TOKEN_LIFETIME'],
path= settings.SIMPLE_JWT['AUTH_COOKIE_PATH'],
secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'],
httponly = False,
samesite = 'Lax'
)
response.data = {"status": "CSRF cookie set", 'csrfmiddlewaretoken':request.META["CSRF_COOKIE"]}
return response

我还设置了:

CORS_ALLOW_ALL_ORIGINS=  True
CORS_ALLOW_CREDENTIALS = True

当前端和后端都在本地主机上时,代码运行得很好,但当我在远程服务器上运行后端时,不会设置cookie,但浏览器会接收到响应请求。

当前端在同一主机上时

当后端在远程服务器上,前端在本地启动时

这是两种情况的控制台结果

这是设置,我尝试过使用CSRF选项,但仍然没有设置cookie,令人担忧的是,当我从浏览器(而不是javascript(调用我的apiView时,cookie正在被设置。

settings.py:

"""
Django settings for core project.
Generated by 'django-admin startproject' using Django 4.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path
import os
from .info import *
from datetime import timedelta
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
EMAIL_USE_TLS = EMAIL_USE_TLS
EMAIL_HOST = EMAIL_HOST
EMAIL_HOST_USER =  EMAIL_HOST_USER
EMAIL_HOST_PASSWORD =  EMAIL_HOST_PASSWORD
EMAIL_PORT =  EMAIL_PORT 
FRONTEND_URL = FRONTEND_URL
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-yzvg4k4r0%*3001&oo&up*@-yvcq(k@tpsdi^g=*ql#zvtogav'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['myip', 'localhost', '127.0.0.1']
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_SAMESITE = None
CSRF_TRUESTED_ORIGINS =['myip', 'localhost', '127.0.0.1'] 
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api',
'rest_framework',
'corsheaders',
'users',
'rest_framework_simplejwt.token_blacklist',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
"corsheaders.middleware.CorsMiddleware",
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'core.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'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 = 'core.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}

# Password validation
# https://docs.djangoproject.com/en/4.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/4.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/4.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CORS_ALLOW_ALL_ORIGINS=  True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
"http://myip:3000",
"http://127.0.0.1:3000",
"http://localhost:3000",
]

'''
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
'''
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
]  ,
'DEFAULT_AUTHENTICATION_CLASSES': (
#'rest_framework_simplejwt.authentication.JWTAuthentication',
'users.authentication.CookieBasedJWTAuthentication',
)
}
AUTH_USER_MODEL = 'users.DearUser'
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': True,
'BLACKLIST_AFTER_ROTATION': True,
'UPDATE_LAST_LOGIN': False,
'AUTH_HEADER_TYPES': ('Bearer','JWT'),
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
'ALGORITHM': 'HS256',
'SIGNING_KEY': SECRET_KEY,
'USER_ID_FIELD': 'email',
'USER_ID_CLAIM': 'email',

# cookie based jwt settings
'AUTH_COOKIE_ACCESS':'ACCESS',
'AUTH_COOKIE_REFRESH':'REFRESH',
'AUTH_COOKIE_SECURE': False, 
'AUTH_COOKIE_HTTP_ONLY' : True,
'AUTH_COOKIE_PATH': '/',
'AUTH_COOKIE_SAMESITE': 'None', #Strict
}

找到了!首先,请确保您的答案正确无误:https://stackoverflow.com/a/46412839/18327111

由于django-corsheads中间件正在检查以下if,请确保具有以下设置:

if conf.CORS_ALLOW_ALL_ORIGINS and not conf.CORS_ALLOW_CREDENTIALS:
response[ACCESS_CONTROL_ALLOW_ORIGIN] = "*"
else:
response[ACCESS_CONTROL_ALLOW_ORIGIN] = origin

新设置:

from corsheaders.defaults import default_headers
CORS_ALLOW_ALL_ORIGINS=  False
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
"http://yourip_or_domain:3000",
"http://127.0.0.1:3000",
"http://localhost:3000",
]
#making sure CORS_ALLOW_HEADERS  is not "*"
CORS_ALLOW_HEADERS = list(default_headers) + ['Set-Cookie']

如果你没有使用django会话身份验证(就像我一样(,并且想绕过它,请添加以下设置

CSRF_USE_SESSIONS = False
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_SAMESITE = None
SESSION_COOKIE_SAMESITE = None

它失败的主要原因是:这是从chrome开发工具复制的,mozila也有这个警告:

由于cookie的SameSite属性未设置或无效默认为SameSite=Lax,这会阻止cookie被发送进来跨站点请求。此行为保护用户数据免受意外泄露给第三方和跨站点请求伪造。通过更新cookie的属性来解决此问题:

如果应发送cookie,请指定SameSite=NoneSecure跨站点请求。这允许第三方使用。

如果cookie不应为在跨站点请求中发送。

因此,如果您想访问跨来源,唯一的方法是使用https和SameSite=None,否则您必须在同一域上部署您的api和后端

请注意,http和https被视为不同的域,并且是跨域的https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#samesitenone_requires_secure

来自同一域的Cookie不再被视为来自如果使用不同的方案(http:或https:(发送,则为同一站点。