所以我们有一个随机问题,我们存储在 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);
};
如果有人可以帮助我,将不胜感激。系统可以工作,但时不时地假设每 50 次登录中有 1 次没有在浏览器中设置令牌。因此,用户对象是从登录请求返回的,但随后发生的进一步请求会引发错误,因为 cookie 中没有令牌。随着用户群的增长,该错误变得越来越明显。
侃侃尔雅
小怪兽爱吃肉
相关分类