如何正确使用 passport-github 进行 REST API 身份验证?

How to properly use passport-github for REST API authentication?

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

我已将主页 url 设置为“http://localhost:3000" where the server runs and I want the authorization callback url to be "http://localhost:8080" (which hosts the client). I am redirecting to "http://localhost:3000/auth/github/redirect" instead, and in its callback redirecting to "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
  }
);

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

returns 用户在 get 请求中详细说明的路由:

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

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

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