我在我的
Django
+ React
应用程序中遇到基于 cookie 的身份验证问题。我已在后端设置了 cookie,但它不会与来自前端 React
(使用 Vite
)运行于 Google Chrome
上的应用程序的后续请求一起发送。
我正在尝试使用
Django
在 Simple JWT
后端中使用 cookie 来实现身份验证。成功登录后,我在Django
中设置了身份验证cookie(“CAT”)。这是我用来设置 cookie 的代码:
final_response.set_cookie(
"CAT",
combined_token,
httponly=True,
secure=False,
samesite="None",
max_age=86400,
path="/",
)
return final_response
Django 服务器上的Setting.py:
CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOWED_ORIGINS = ["http://localhost:5173/"]
CORS_ALLOW_CREDENTIALS = True
SECURE_CROSS_ORIGIN_OPENER_POLICY = "same-origin"
但是,当我的
React
应用程序发出后续请求时,浏览器似乎不包含 cookie,并且我收到身份验证失败(“找不到 Cookie”)。这是我在 Axios
应用程序中的 React
请求设置:
try {
const auth_response = await axios.get(
"http://my-django-server/api/auth/auth-checker",
{
headers: {
"Content-Type": "application/json",
},
withCredentials: true,
timeout: 5000,
}
);
console.log(auth_response?.data);
if (auth_response?.status === 200) {
navigate("/profile");
} else {
console.error("Unauthorized access. Please try again.");
}
} catch (error) {
console.error("An error occurred. Please try again.", error);
}
手动验证工作原理: 有趣的是,当我在来自终端的
Axios
请求中手动设置 cookie 时,该请求按预期工作,并且我得到了经过身份验证的响应。然而,在浏览器中,它失败了。
getRegularHeader(port: string): Record<string, string> {
return {
"Content-Type": "application/json",
Origin: `http://localhost:${port}`,
};
}
const token = readlineSync.question("Enter CAT token: ");
try {
const response = await axios.get(url, {
headers: { ...this.getRegularHeader(port), Cookie: `CAT=${token}` },
withCredentials: true,
timeout: 5000,
});
return response;
} catch (error) {
console.error(`Failed to authenticate: ${error}`);
return null;
}
还有来自
Google Chrome
的消息:
我尝试过的:
问题:
从您提供的信息中,我没有看到任何应该处理此问题的 SimpleJWT 配置。
查看:https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html