Search code examples
javascriptnode.jsexpresspassport.jsgoogle-oauth

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

note - Because of design limitation I cant do it with external source as database.

passport-google docs

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

Solution

  • You have to store your params in session before sending auth request to 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;