【问题标题】:How to properly use passport-github for REST API authentication?如何正确使用 passport-github 进行 REST API 身份验证?
【发布时间】:2019-07-17 13:29:02
【问题描述】:

我正在构建一个 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
  }
);

【问题讨论】:

    标签: vuejs2 passport.js session-cookies passport-github2


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-08-03
      • 1970-01-01
      • 2015-09-10
      • 2016-07-28
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      • 2012-08-29
      • 2013-01-05
      相关资源
      最近更新 更多