身份验证 Cookie 未随浏览器中的 Axios 请求一起发送

问题描述 投票:0回答:1

我在我的

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"

登录后可以看到Chrome中存储的cookie: enter image description here

但是,当我的

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
的消息: enter image description here

我尝试过的:

  • 在 Chrome 和 Edge 中检查,结果相同。
  • 验证 axios 请求中设置了 withCredentials: true 。
  • 尝试不同的 Cookie 设置(例如 SameSite=None、Secure=False)。

问题:

  • 为什么浏览器不随我的请求发送 cookie?
  • Django 或 React 中是否有我可能缺少的特定设置或配置?
javascript reactjs django cookies browser
1个回答
0
投票

从您提供的信息中,我没有看到任何应该处理此问题的 SimpleJWT 配置。

查看:https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html

© www.soinside.com 2019 - 2024. All rights reserved.