Search code examples
reactjsexpressjwtpassport.jsgoogle-oauth

How to get JSON web token in Reactjs after passport OAUTH callback?


My server and passport.js are working correctly; however, instead of sending the JWT token to my react app (port: 3000), it is sending it to itself (port:5000). To make it work, after the token was generated, I redirected back to the react application along with the JWT token.

//req.user = jwt token
res.redirect(`http://localhost:3000/${req.user}`)

It does the job; however, I feel very uncomfortable putting my reusable token as a query string

Is there a more effective way of passing this token? Or perhaps I am doing it wrong.

If it helps, below is my code to better explain my process

React "Sign Up Page"

<a href="http://localhost:5000/api/auth/google">
   <button width={"100%"} height={50}>
     Register with google
   </button>
</a>    

Server "Auth Routes"

router.get(
  "/google",
  passport.authenticate("google", {
    session: false,
    scope: ["profile", "email"]
  })
);

router.get(
  "/google/redirect",
  passport.authenticate("google", {
    session: false,
    failureRedirect: "http://localhost:3000/register"
  }),
  (req, res) => {
    res.redirect(`http://localhost:3000/${req.user}`);
  }
);

I didn't add the passport-setup, because it is working; however, if there is a much more effective way of approaching the problem that includes the passport-setup, then I will be more than happy to add it to the question. I would appreciate any help. Cheers!


Solution

  • I wasn't able to figure out this problem but simply using react-google-login simplifies the entire process.

    Once you get the google token from the react-google-login component, send the token to the backend and make another request to google to make sure that user is valid and continue with the JWT process