我正在使用 MERN 堆栈开展一个项目。
当请求发送到登录端点时,客户端以 JSON 形式返回访问令牌,并以 res.cookies 形式返回刷新令牌。这是示例代码
const login = asyncHandler(async (req, res) =>{
const accessToken = 1234
const refreshToken = 5678
res.cookie("jwt", refreshToken, {
httpOnly: true,
secure: false,
sameSite: "None",
maxAge: 7 * 24 * 60 * 60 * 1000,
path: "/auth/refresh",
});
res.json({ accessToken });
}
当请求发送到刷新端点时,根据我的逻辑,httponly cookie应该自动发送到客户端,并且客户端应该以json形式返回访问令牌。这是示例代码
const refresh = (req, res) => {
console.log("inside refresh");
const cookies = req.cookies;
console.log("cookies", cookies);
if (!cookies?.jwt) {
return res
.status(401)
.json({ message: "Unauthorized:No refresh token cookie found" });
}
const refreshToken = cookies.jwt;
jwt.verify(
refreshToken,
process.env.REFRESH_TOKEN_SECRET,
asyncHandler(async (err, decoded) => {
if (err) {
return res
.status(403)
.json({ message: "Forbidden: Wrong refresh token cookie" });
}
const foundUser = await User.findOne({ username: decoded.username });
if (!foundUser) {
res
.status(401)
.json({ message: "Unauthorized: wrong cookie send, no user found" });
}
const accessToken = jwt.sign(
{
UserInfo: {
username: foundUser.username,
roles: foundUser.roles,
},
},
process.env.ACCESS_TOKEN_SECRET,
{ expiresIn: "20" }
);
res.json({ accessToken });
})
);
};
export async function refresh() {
const res = await axios.get("/auth/refresh", {
withCredentials: true,
});
return res.accessToken;
}```
Now when I am doing the following steps
1)Sending login request to the client; I confirmed that the access token is returned and the HTTPonly cookie is stored as set-cookie in the res headers
2)Sending refresh request to the client using refresh function in the client side; The refresh end point is not getting the acces to the HTTPcookie?. When trying to print the cookie in the refresh end point, the cookie is returned as [Object: null prototype]
What am I doing wrong?
在登录请求中添加 {withCredentials:true} 解决了问题