问题描述
感谢 express,我向我的前端发送了一个 cookie:
// signing the token
static generatetoken(user: PartialUser): Cookie {
return jwt.sign({ _id: user._id },process.env.JWT_TOKEN_KEY,{
expiresIn: "14d",});
// sending the cookie
return res
.status(200)
.cookie("myApp",token,{
expires: new Date(Date.Now() + msPerDay * 14),httpOnly: true,secure: true,})
.json({ user });
// initializing cookie parser in index.js:
app.use(cookieParser(process.env.JWT_TOKEN_KEY));
//parsing the cookie
const authenticate = (req: Authenticate,res: Response,next: NextFunction) => {
const { myApp } = req.signedCookies;
if (req.signedCookies) {
return jwt.verify(
myApp,(error,parsedToken) => {
if (error) {
return res.sendStatus(403);
}
req.cookie = { _id: parsedToken._id };
return next();
}
);
}
return res.sendStatus(401);
};
req.signedCookies
对象始终为空。所以我所有的路线都返回 403 - 禁止访问。但是,如果我在发送 cookie 时不指定 secure: true
,它会起作用,因为我可以在 req.cookies
中访问它。网络选项卡显示 cookie 已正确发送到客户端请求。
如何解决这个问题?
ps:我可以使用 req.cookies
,但我的 express 服务器托管在 Heroku 上,它从不向客户端发送 cookie,客户端是自定义 https 域。这就是我尝试使用 secure:true
选项的原因。目前,它只适用于本地主机。也许解决方案在别处?
解决方法
一方面是 cookie 签名,另一方面是 {"respStatus":"SUCCESS","respObj":{"message":"Object created"}}
选项,实际上是两种不同的东西。
secure
选项限制 cookie 仅通过 https 发送。这是为了避免通过网络窃听。默认情况下,设置为 secure
的传入 cookie 将始终在 secure
上由 req.cookies
公开。
另一方面,cookie 签名基本上是一种加密哈希,旨在使 cookie 防篡改。似乎使用 cookie-parser
包,您使用 cookie-parser
选项签署 cookie。只有经过明确签名的传入 cookie 才会在 signed: true
上公开。请注意,这与 req.signedCookies
选项无关。