【问题标题】:adding additional data to req.user with passport-google-oauth使用 passport-google-oauth 向 req.user 添加其他数据
【发布时间】:2019-02-28 20:31:03
【问题描述】:

我有一条路线,旨在使用 google oauth 护照策略对用户进行身份验证,(/auth/google) 我还想在该路线 (/auth/google?someParam=SOME_PARAM) 的 url 中作为查询传递附加数据,我想要这个数据当我从谷歌(/auth/google/callback)取回它时,添加到req.user。问题是我可以通过/auth/google 访问此查询,但谷歌会将我重定向到/auth/google/callback,它不再有权访问此数据。

注意 - 由于设计限制,我无法将外部源用作数据库。

护照谷歌docs

代码:

// auth.js 

router.get(
  "/",
  (req, res, next) => {
    let siteName = req.query.siteName;
    let pageName = req.query.pageName;
    console.log("siteName", siteName);
    return next();
  },
  passport.authenticate("google", {
    scope: ["https://www.googleapis.com/auth/plus.login"]
  })
);

module.exports = router;




// authCb.js

router.get(
  "/",
  passport.authenticate("google", {
    scope: ["https://www.googleapis.com/auth/plus.login"],
    failureRedirect: "/"
  }),
  (req, res) => {
    console.log(req.user);
    res.send(req.user);
  }
);

module.exports = router;





// app.js

app.use("/auth/google", auth);
app.use("/auth/google/callback", authCb);

【问题讨论】:

    标签: javascript node.js express passport.js google-oauth


    【解决方案1】:

    在向 google 发送身份验证请求之前,您必须将参数存储在会话中。 然后,在重定向之后,从会话中取回你的参数。

    // auth.js 
    router.get(
      "/",
      (req, res, next) => {
        req.session.lastQuery = req.query;
        return next();
      },
      passport.authenticate("google", {
        scope: ["https://www.googleapis.com/auth/plus.login"]
      })
    );
    
    module.exports = router;
    
    // authCb.js
    
    router.get(
      "/",
      passport.authenticate("google", {
        scope: ["https://www.googleapis.com/auth/plus.login"],
        failureRedirect: "/"
      }),
      (req, res) => {
        const { lastQuery } = req.session;
        console.log(lastQuery);
      }
    );
    
    module.exports = router;
    

    【讨论】:

    • 谢谢!我会试一试,让你知道结果如何(:
    【解决方案2】:

    您应该参考 Google 的文档。一旦用户返回您的站点,您可以使用“状态”参数传递您想要返回的任何数据。这是这个参数的主要用途。 可以查看详情here

    【讨论】:

    • API 是这样工作的:/auth/google?state=state_value 吗?因为文档并不清楚。他们也没有指定我以后如何访问这些数据?对不起,如果有明显的答案,我就是看不到它
    • state={whatever value you sent} 被附加到redirect_uri。因此,当用户被送回您的站点时,您可以通过 URI 参数访问它。
    猜你喜欢
    • 2015-10-18
    • 2019-09-05
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多