我正在做一个带有cookie授权的项目。带有用户名的访问令牌由服务器发送到 js 客户端,并且在浏览器的网络监视器中我可以看到 cookie 是通过来自
fetch
的请求发送的。页面重新加载后,我想读取保存的 cookie,如果存在,则保留以供用户登录。
问题是 Firefox 中的 Storage->Cookies 为空,并且
document.cookie
返回空字符串。
后端 - Python FastAPI,cookie 是这样设置的:
login_manager.set_cookie(response, token) # httponly=True
response.set_cookie("blueberry-user", data.login, httponly=False, expires=timedelta(days=1))
js前端发送授权请求并接收cookie的代码:
let response = await fetch(backendUrl + handleUrl, {
method: "post",
mode: "cors",
credentials: "include",
body: JSON.stringify({ login: login, password: password }),
headers: {
"Content-Type": "application/json",
},
});
正在设置 Cookie 并与下一个请求一起发送: img img
起初我以为问题出在 httponly 上,但是当我将其关闭以设置 cookie 时,它并没有帮助。
通过将
domain="blueberry.adefe.xyz"
添加到 cookie 作为响应解决了该问题。后端 URL:api.blueberry.adefe.xyz,前端 URL:blueberry.adefe.xyz,也许问题出在跨域 cookie 上。
向 FastAPI 响应添加 cookie 的完整代码:
@router.post("/user/login", tags=["Authentification"])
def post_login(data: AuthRequestModel, response: Response):
...
response.set_cookie(
"blueberry-user",
data.login,
httponly=False,
expires=timedelta(days=1),
domain="blueberry.adefe.xyz",
)
response.status_code = status.HTTP_200_OK
return response
还是不明白为什么cookie会自动存储并随请求一起发送,但在js和浏览器中却无法访问