基于 HttpOnly Cookie 的身份验证

时间:2021-05-25 03:13:42

标签: node.js reactjs cookies redux httponly

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);
  }
});

1 个答案:

答案 0 :(得分:1)

除了为 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div> 设置 credentials 选项外,您不需要在客户端上执行任何操作,这将导致浏览器在每次请求时将 cookie 发送回您的浏览器。

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