2
votes

I am working on the authentication system of a web app, using Next.js for the client app and Node.js for the API.

  • I have my Next.js app on port 3000
  • I externalized the API of my application, on port 5000

That's why I used JWT for the local signin/signup strategies. (I'm planning to use the same API for the mobile application later)

I am now wondering what is the best approch for a Google Authentication. I have set it up, but I don't know how to give the token to the client.

Here is the process:

  • On Signin page (http://localhost:3000/signin), the user clicks on "Google authentication". It redirects to 'http://localhost:5000/auth/google"
  • Passport handles it, it redirects to Google OAuth page. User authorize the application.
  • Google redirects to the callback URL (http://localhost:5000/auth/google/redirect)

In the callback route, I can create a JWT. But how can I give it back to the client ? I have thought of passing it through URL, but I am wondering if it is safe ? Is there another way to do it / Am I missing the point ?

router.get('/google/redirect', (req, res, next) => {
  return passport.authenticate('google', (err, user) => {
    if (err) {
      return res.redirect('http://localhost:3000/signin')
    }
    console.log(user)
    // Create JWT and redirect to http://localhost:3000/signin/oauth?token=xxx ?
  })(req, res, next)
})

I can show more code if needed, but it works (code is not the blocking point).

Thank you in advance !

1
Cookie sounds like one of options. Another is a hidden input that your client reads. - Wiktor Zychla
@WiktorZychla My client app (Next.js) and my api (node.js) don't share the same URL. I can not create a cookie from the API and access it from the client, tha'ts why I used JWT. - Erwan
CrossPOST the token then. - Wiktor Zychla

1 Answers

1
votes

all you have to do is setting up cookie session. When google sends responds to /google/redirect, passport.authenticate will call req.login() and this will call the serializeUser

  passport.serializeUser(
  (user, done ) => {
    done(null, user.id); // stores the id<4kb
  }
);

this function will create, passport:{user:userId}. this is the unique identifying information about the user. This where you need session. Because passport.js will automatically look for req.session and attaches the passport object to the req.session.

Since we are storing only userId, usually cookie-session package. this package will set req.session object, passport.js will attach the passport object and the cookie-session will store this on the client.