cookie 中未设置令牌

Ale*_*ran 6 javascript cookies node.js express reactjs

因此,我们遇到一个随机问题,即我们存储在 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)
  }
};
Run Code Online (Sandbox Code Playgroud)

如果有帮助的话,我们正在使用中间件 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 } };
  }
Run Code Online (Sandbox Code Playgroud)

我们使用中间件 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;

Run Code Online (Sandbox Code Playgroud)

如果有人可以帮助我,我将不胜感激。该系统可以工作,但时不时地假设每 50 次登录中有 1 次它不会在浏览器中设置令牌。因此,用户对象是从登录请求返回的,但随后发生的进一步请求会抛出错误,因为 cookie 中没有令牌。随着用户群的增长,该错误变得越来越明显。

EJ *_*son 4

这看起来像是 cookie 问题!

因此,有两种方法可以通过 cookie 来保持浏览器的状态。会话数据存储在服务器上,通常使用某些键来检索与用户状态相关的值。Cookie存储在客户端,并在请求中发送以确定用户状态。ExpressJS 支持使用这两种功能。对于 JWT,你当然要使用 cookie 方法!

让我们首先看看您的 cookie 选项:

// return { name: config.tokenKey, val: token, options: { httpOnly: true } };

const cookieOptions = {
    httpOnly: true
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,这看起来不错。您正在遵循有关将令牌存储为 http only 的最佳实践,但为了正确存储 cookie,您可能需要向 cookie 选项添加更多内容。

这是 Express 文档中 cookie 选项的链接。查看“过期”的说明:

Cookie 的到期日期(格林威治标准时间)。如果未指定或设置为 0, 则创建会话 cookie

本质上,发生的情况是您没有指定过期时间,因此您的 cookie 被设置为会话 cookie。这意味着只要用户关闭浏览器,cookie 就会被销毁。

奖金:

  • 如果您的网站使用 HTTPS,请确保将 cookie 设置为secure: true

  • 您可能还想查看 SameSite 属性(如果它适用于您的团队)。