Forbidden (CSRF cookie 未设置.): /login/ REACT & DJANGO



我已经用react构建了前端,用django构建了后端,在localhost上一切都很好,但当我在heroku上部署前端并发出POST登录请求时(后端仍在localhost运行(,我收到了以下错误:

禁止(未设置CSRF cookie。(:/login/

前端代码:

https://pastebin.com/CHArh4JL

function getCsrf(){
fetch("http://localhost:8000/csrf/", {
credentials: "include",
})
.then((res) => {
let csrfToken = res.headers.get("X-CSRFToken");
setCsrf({csrf: csrfToken});

})
.catch((err) => {
console.log(err);
})

}
const login = (event) => {
event.preventDefault();
setIsLoading(true)
fetch("http://localhost:8000/login/", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRFToken": csrf.csrf,
},
credentials: "include",
body: JSON.stringify({username: username, password: password}),
})
.then(isResponseOk)
.then((data) => {
console.log(data);
setIsAuthenticated(true)
localStorage.setItem("authenticated", true);
setUsername('')
setPassword('')
setIsLoading(false)
//   this.setState({isAuthenticated: true, username: "", password: ""});
})
.catch((err) => {
console.log('inside login catch')
console.log(csrf.csrf, 'catch')
console.log(err);
});

}
const isResponseOk = (response) =>{
if (response.status >= 200 && response.status <= 299) {
return response.json();
} else {
console.log(response)
throw Error(response.statusText);
}
}
useEffect(() => {
//getSessions
setIsLoading(true)
fetch("http://localhost:8000/session/", {
credentials: "include",
})
.then((res) => res.json())
.then((data) => {
// console.log(data);
if (data.isAuthenticated) {
setIsAuthenticated(true)

console.log(data)
} else {
// test()
setIsAuthenticated(false)
console.log(data)

getCsrf()
}
setIsLoading(false)
})
.catch((err) => {
console.log(err);
});


}, [])


后端代码:

https://pastebin.com/sXv1AWhK

@require_POST
# @csrf_exempt
def login_view(request):

print(request.body)
data = json.loads(request.body)
print(data)
username = data.get('username')
password = data.get('password')
# username = None
# password = None
# newUser = DjangoUser(username="test", password="test")
# newUser.save()
if username is None or password is None:
return JsonResponse({'detail': 'Please provide username and password.'}, status=400)
user = authenticate(username=username, password=password)
if user is None:
return JsonResponse({'detail': 'Invalid credentials.'}, status=400)
login(request, user)
return JsonResponse({'detail': 'Successfully logged in.'})
@ensure_csrf_cookie
def session_view(request):
if not request.user.is_authenticated:
return JsonResponse({'isAuthenticated': False})
return JsonResponse({'isAuthenticated': True})

这是我的设置.py

https://pastebin.com/nqRVy6ty

"""
Django settings for ecommerce project.
Generated by 'django-admin startproject' using Django 3.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
# 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/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ["*"]
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Application definition
INSTALLED_APPS = [
'core.apps.CoreConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
"corsheaders.middleware.CorsMiddleware",
'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',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
ROOT_URLCONF = 'ecommerce.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 = 'ecommerce.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
#database stuff here
'CONN_MAX_AGE': None,
}
}

# Password validation
# https://docs.djangoproject.com/en/3.2/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/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CORS_ALLOW_ALL_ORIGINS = True
CSRF_TRUSTED_ORIGINS = ['https://theherokuweb.herokuapp.com','http://theherokuweb.herokuapp.com','http://localhost:3000','https://*.127.0.0.1']

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATED_CLASSES': [
'rest_framework.authenticated.SessionAuthentication',
]
}
CSRF_COOKIE_SAMESITE = 'Lax'
SESSION_COOKIE_SAMESITE = 'Lax'
# CSRF_COOKIE_HTTPONLY = True
# SESSION_COOKIE_HTTPONLY = True
# PROD ONLY
# CSRF_COOKIE_SECURE = True
# SESSION_COOKIE_SECURE = True
CORS_EXPOSE_HEADERS = ['Content-Type', 'X-CSRFToken']
CORS_ALLOW_CREDENTIALS = True

编辑:我现在已经分别部署了react前端和django后端,但仍然得到了[Forbidden(403(CSRF验证失败。请求中止。]错误。

这是因为在settings.py中设置了CSRF_COOKIE_SECURE = True,也设置了CSRF_COOKIE_HTTPONLY = True。您可以参考CSRF_COOKIE_SECURE和CSRF_COOK IE_HTTPONLY文档。希望这个答案能对你有所帮助。

最新更新