Cookie 不会在浏览器中设置,但在邮递员中设置



我到处找了找,但还是找不到。我关注这个博客是为了把事情做好。

这是我发送cookie的地方(服务器(:

//after user is has been authenticated
export const logInUser = async (req, res, next) => {
try {
const token = getToken({ _id: req.user._id, username: req.user.username, email: req.user.email})
const refreshToken = getRefreshToken({  _id: req.user._id, username: req.user.username, email: req.user.email})
await User.findOne({ username: req.user.username}).then((user)=>{
user.refreshToken.push({ refreshToken })
user.save((error, user) => {
if (error) {
res.status(500).json(error)
} else {
//sending the cookie
res.cookie("refreshToken", refreshToken, {httpOnly: true, secure: !dev, signed: true, maxAge: (60 * 60 * 24 * 30) * 1000, sameSite: "none"})
res.send({ success: true, token,  _id: req.user._id, username: req.user.username, email: req.user.email})
}
})
})
} catch (error) {
next(error)
res.status(500).json(error)
console.log(error)
}
}

index.js(服务器(:

const corsOptions ={
origin: true, 
credentials:true,
optionSuccessStatus:200
}
app.use(express.json());
app.use(helmet());
app.use(morgan("common"));
app.use(cookieParser(process.env.COOKIE_SECRET))
app.use(cors(corsOptions));
app.use(passport.initialize());

在客户端发出请求(使用next.js(:

function login(username, password) {
axios.post("http://localhost:5000/api/auth/login", {username, password}, {withCredentials: true, credentials: 'include'}).then((res)=>{
setCurrentUser(res.data)
}).catch((error)=>{
console.log(error)
})
}

浏览器中的响应

邮差中的一切都很完美

如果您试图在浏览器devtools中查看cookie,请检查此答案https://stackoverflow.com/a/38604501/16091749.

如果你想从下一个应用程序访问你的cookie,那么除非你禁用httpOnly标志,否则你无法这样做。在这种情况下,不建议使用httpOnly标志。因为你在这个cookie中保留敏感数据,所以如果你禁用了这个标志,你的cookie将容易受到任何可能与其接触的恶意脚本的攻击。有关cookie的更多信息,请查看此链接https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

我通过在res.cookie("refreshToken", refreshToken, {httpOnly: true, secure: !dev, signed: true, maxAge: (60 * 60 * 24 * 30) * 1000, sameSite: "none"})这一行中去掉cookie上的sameSite: "none"属性最终解决了这个问题

最新更新