【发布时间】:2020-07-09 18:05:49
【问题描述】:
所以我们遇到了一个随机问题,即我们存储在 cookie 中用于身份验证的 JWT 令牌时不时地没有在浏览器中设置。现在 99% 的用户进入登录网页输入他们的详细信息,它会向服务器发送一个请求,服务器会发回他们的用户详细信息和设置到 cookie 中的 JWT 令牌。现在时不时地似乎没有设置cookie。现在几乎所有浏览器都发生了随机事件,但没有理由说明原因。它发生在我们的本地、暂存和生产环境中。 (出于隐私原因,我删除了一些代码)
后端身份验证服务是使用 Node 和 ExpressJS 构建的,它使用以下代码设置令牌:
module.exports.signIn = async function(req, res, next) {
try {
const { email, password } = req.body;
if (!email || !password)
throwBadRequest("Please enter a valid email and password");
const data = await Users.get(`?email=${email.toLowerCase().trim()}`);
const { name, val, options } = await Token.generateCookieParams(data);
res.cookie(name, val, options);
return res.json(toDTO(data));
} catch (err) {
next(err)
}
};
如果有帮助,我们将使用中间件 cookie 解析器。这是设置令牌的代码:
async function generateFor(user, expireTime, special = null) {
const payload = { id: user._id, type: user.type, account: user.account };
if (user.entity) {
payload.entity = user.entity;
}
if (special) {
payload.special = special;
}
const token = await jwt.sign(payload, config.secret, {
expiresIn: expireTime
});
return token;
}
async function generateCookieParams(user) {
const expireTime = 60 * 60 * 12; // 12 hour
const token = await Token.generateFor(user, expireTime);
return { name: config.tokenKey, val: token, options: { httpOnly: true } };
}
我们正在使用中间件 cors 来管理 express 应用中的 cors,并将选项凭据设置为 true。
然后在前端,我们使用 superagent 来从 react 应用发出所有请求,我们也使用了 Axios,但有同样的问题。网络的基本代码在前端如下所示:
import superagent from "superagent";
const superagentManager = {};
/**
* POST
* @param {string} path => the path for the post request
* @param {object} data => the object you are posting in json format
*/
superagentManager.post = async (path, data) => {
return await superagent
.post(path)
.withCredentials()
.type("application/json")
.send(data);
};
/**
* GET
* @param {string} path => the path for the get request
*/
superagentManager.get = async path => {
return await superagent
.get(path)
.withCredentials()
.type("application/json");
};
/**
* PATCH
* @param {string} path => the path for the patch request
* @param {object} data => the object you are posting in json format
*/
superagentManager.patch = async (path, data) => {
return await superagent
.patch(path)
.withCredentials()
.type("application/json")
.send(data);
};
/**
* DELETE
* @param {string} path => the path for the delete request
*/
superagentManager.delete = async path => {
return await superagent
.delete(path)
.withCredentials()
.type("application/json");
};
export default superagentManager;
如果有人可以帮助我,将不胜感激。该系统可以工作,但时不时地假设每 50 次登录中有 1 次没有在浏览器中设置令牌。因此,用户对象是从登录请求返回的,但随后发生的进一步请求会引发错误,因为 cookie 中没有令牌。随着用户群的增长,该错误变得越来越明显。
【问题讨论】:
-
您的代码中的
jwt是什么?只是想知道jwt.sign是否吞下了一些在某些情况下返回空值的错误。 -
看起来您可能正在使用
jsonwebtoken?如果有,是什么版本? -
您是否查看了网络选项卡以查看 api 调用是否响应了 cookie?您需要观察没有发生登录时有什么不同
-
是的,cookie 确实回到了浏览器,我可以在网络选项卡中看到它。
标签: javascript node.js reactjs express cookies