简体   繁体   English

使用password-google-oauth向req.user添加其他数据

[英]adding additional data to req.user with passport-google-oauth

I have a route which meant to authenticate the user using google oauth passport strategy ,( /auth/google ) I also want to pass additional data as query in the url in that route ( /auth/google?someParam=SOME_PARAM ) , this data I want to add to req.user by the time I get it back from google in ( /auth/google/callback ). 我有一条旨在使用google oauth护照策略( /auth/google )对用户进行身份验证的路由,我也想通过该路由( /auth/google?someParam=SOME_PARAM )中的url作为查询来传递其他数据我想在( /auth/google/callback )从Google req.user时将其添加。 The problem is that I have access to this query through /auth/google but google will redirect me to /auth/google/callback which dont have access to this data anymore. 问题是我可以通过/auth/google访问此查询,但是Google会将我重定向到/auth/google/callback ,后者不再有权访问此数据。

note - Because of design limitation I cant do it with external source as database. 注-由于设计限制,我无法使用外部源作为数据库。

passport-google docs 护照-Google 文档

CODE : 代码:

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

You have to store your params in session before sending auth request to google. 您必须先在会话中存储参数,然后才能向Google发送身份验证请求。 Then, after redirect, get your params back from session. 然后,在重定向之后,从会话中恢复参数。

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

You should refer to Google's documentation. 您应该参考Google的文档。 You can use the "state" parameter to pass any data you want to get back once the user is back to your site. 一旦用户回到您的站点,您可以使用“ state”参数传递您想要获取的任何数据。 This is the main use of this parameter. 这是此参数的主要用途。 You can see the details here . 您可以在此处查看详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM