javascript - cookie 中未设置 token

标签 javascript node.js reactjs express cookies

因此,我们遇到了一个随机问题,即我们存储在 cookie 中用于身份验证的 JWT token 有时不会在浏览器中设置。现在,99% 的用户进入登录网页输入详细信息时,都会向服务器发送请求,服务器会发回用户详细信息和设置到 cookie 中的 JWT token 。现在,cookie 似乎时不时地没有被设置。现在几乎所有浏览器都发生了这种随机现象,但没有任何原因。它发生在我们的本地、临时和生产环境中。 (出于隐私原因我删除了一些代码)

后端身份验证服务是使用 Node 和 ExpressJS 构建的,它使用以下代码设置 token :

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 解析器。这是设置 token 的代码:

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 次它不会在浏览器中设置 token 。因此,用户对象是从登录请求返回的,但随后发生的进一步请求会抛出错误,因为 cookie 中没有 token 。随着用户群的增长,该错误变得越来越明显。

最佳答案

这看起来像是 cookie 问题!

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

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

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

const cookieOptions = {
    httpOnly: true
}

到目前为止,这看起来不错。您正在关注best practices about storing tokens as http only ,但要正确存储 cookie,您可能需要向 cookie 选项添加更多内容。

Here is a link to cookie options in the express docs 。查看“过期”的说明:

Expiry date of the cookie in GMT. If not specified or set to 0, creates a session cookie.

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

奖金:

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

  • 您可能还想查看 SameSite 属性是否适用于您的团队。

关于javascript - cookie 中未设置 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60912459/

相关文章:

javascript - 使父 div 的宽度等于最宽的子元素/div

javascript - NodeJS PTY 计时命令

node.js - 关于 NodeJS 中的嵌套 Promise

javascript - 具有多项选择限制的下拉菜单

javascript - 为什么应该避免使用 onclick HTML 属性而采用标准事件注册模型?

javascript - 从数组中获取元素位置

reactjs - 用于 react 应用程序的条形码扫描仪

javascript - 如何在 React 中正确使用 Ajax

javascript - "white-space: pre;"CSS 样式在 <textarea> HTML 元素中似乎不符合 W3C 规范 - 它总是换行,而不仅仅是换行

mysql - Sequelize 中每个 api 调用期间的动态数据库连接,其中有 'n' 没有数据库