0

我正在构建一个 vue.js 客户端,该客户端需要使用 express 服务器通过 github oauth 进行身份验证。使用服务器端渲染很容易做到这一点,但 REST API 对我来说很麻烦。

我已将主页 url 设置为服务器运行的“ http://localhost:3000 ”,并且我希望授权回调 url 为“ http://localhost:8080 ”(托管客户端)。我改为重定向到“ http://localhost:3000/auth/github/redirect ”,并在其回调中重定向到“ http://localhost:8080 ”。我面临的问题是我无法通过 res.redirect 将用户数据发送到 vuejs 客户端。我不确定我是否以正确的方式做这件事。

router.get("/github", passport.authenticate("github"));

router.get(
  "/github/redirect",
  passport.authenticate("github", { failureRedirect: "/login" }),
  (req, res) => {
    // res.send(req.user);
    res.redirect("http://localhost:8080/"); // req.user should be sent with this
  }
);
4

1 回答 1

0

我已经实施了以下方法作为解决方法:-

在 get 请求中返回用户详细信息的路由:

router.get("/check", (req, res) => {
if (req.user === undefined) {
  res.json({});
} else {
  res.json({
    user: req.user
  });
}
});

客户端应用程序在重定向后立即点击此 api 以及一些必要的标头:

checkIfLoggedIn() {
  const url = `${API_ROOT}auth/check/`;
  return axios(url, {
    headers: { "Content-Type": "application/json" },
    withCredentials: true
  });
}

要启用凭据,我们必须在配置 cors 时传递以下选项:

var corsOption = {
  origin: true,
  credentials: true
};

app.use(cors(corsOption));
于 2019-07-21T06:36:51.673 回答