【问题标题】:HttpOnly Cookie based authenticationHttpOnly 基于 Cookie 的身份验证
【发布时间】:2021-08-13 07:15:26
【问题描述】:

export const login = (credentials) => async (dispatch) => {
  try {
    const { data } = await axios.post("/auth/login", credentials);
    dispatch(gotUser(data));
    socket.emit("go-online", data.id);
  } catch (error) {
    console.error(error);
    dispatch(gotUser({ error: error.response.data.error || "Server Error" }));
  }
};

我已经从后端成功发送了一个 httpOnly cookie....我不确定我如何在 react 中验证用户登录....谁能帮我解释一下吗?

我无法理解基于 cookie 的身份验证如何与 react 和 node 一起使用。

router.post("/login", async (req, res, next) => {
  try {
    // expects username and password in req.body
    const { username, password } = req.body;
    if (!username || !password)
      return res.status(400).json({ error: "Username and password required" });

    const user = await User.findOne({
      where: {
        username: req.body.username,
      },
    });

    if (!user) {
      console.log({ error: `No user found for username: ${username}` });
      res.status(401).json({ error: "Wrong username and/or password" });
    } else if (!user.correctPassword(password)) {
      console.log({ error: "Wrong username and/or password" });
      res.status(401).json({ error: "Wrong username and/or password" });
    } else {
      const token = jwt.sign(
          { id: user.dataValues.id },
          process.env.SESSION_SECRET,
          { expiresIn: 86400 }
      );
      const options = {
        httpOnly: true,
        secure: true,
        sameSite: true
      }
      res.cookie("token", token, options);
      res.json({
        ...user.dataValues,
      });
    }
  } catch (error) {
    next(error);
  }
});

【问题讨论】:

    标签: node.js reactjs cookies redux httponly


    【解决方案1】:

    除了为fetch 设置credentials 选项外,您不需要在客户端上执行任何操作,这将导致浏览器在每次请求时将cookie 发送回您的浏览器。

    https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#parameters

    【讨论】:

    • 如果你想看的话,我已经设置了我的登录名。
    • 是的,据我所知,这似乎没问题 - 您可以在浏览器的 DevTools 中验证它。我的观点是所有您必须在客户端做的是确保您在fetch 调用中设置credentials: "include",并且cookie 将与这些请求一起发送回服务器。您实际上不必在客户端执行任何其他操作来处理所有这些,您只需验证服务器上的 cookie 即可。
    猜你喜欢
    • 2020-10-08
    • 2010-11-19
    • 2021-06-24
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 2021-05-26
    • 2014-05-28
    相关资源
    最近更新 更多