passport / discuss

A forum for discussing topics related to the usage of Passport.js.
1 stars 0 forks source link

Unexpected redirect when using Google oauth2 #41

Closed ofekdeitch closed 4 years ago

ofekdeitch commented 4 years ago

Hey everyone, I used passport on my node.js server. I'm trying to authenticate my users via Google's oauth2. The authentication process is as follows:

  1. User is redirected to <server>/auth/google, which uses passport's middleware thus: passport.authenticate("google", { scope: ["profile", "email"] })
  2. User receives Google's login page and logins
  3. Google redirects user to <server>/auth/google/callback, which uses passport's middleware thus: passport.authenticate("google", { failureRedirect: "/", session: false })
  4. User is redirected to <client>?token=<token>

I am hosting my project's front-end on Netlify and the back-end on NOW. Everything works when running local, yet when running in production there is an unexpected redirect during step 3, in which the user is redirected to <server>/auth/google/t?token=<long-token-string> instead of the path mentioned.

What causes this? Any ideas? Thanks, Ofek

ofekdeitch commented 4 years ago

After reading and debugging passport.js and oauth, I finally found out what was wrong. This was a bug in my code.

I used this in my config file:

export const CLIENT_ORIGIN =
  process.env.NODE_ENV === "production"
    ? "https://<project-name>.netlify.com"
    : ["http://127.0.0.1:3000", "http://localhost:3000"];

So, when running on localhost, setting callbackURL = CLIENT_ORIGIN[1] in the StrategyOptions made sense, but when running in production CLIENT_ORIGIN received the value "https://<project-name>.netlify.com" (a string instead of an array), therefore CLIENT_ORIGIN[1] returned the character "t". As a result, the callbackURL received the value "t", which caused this unpredicted (and undocumented) redirect.