passportJS and Google OAuth


the ‘20’ refers to ‘2.0’ passport-google-oauth20 is the Google Strategy
configuration for the Google passport strategy

Google API Setup

  • Create a new project through Google Cloud’s console. The only property you need to specify is the project name.
  • Set up the ‘OAuth Consent Screen’, with user type ‘External’, save.
  • Create Credentials using ‘OAuth client ID’, selecting ‘web application’ for the application type, and passing along your test server URL (http://localhost:5000) to “Authorized JavaScript Origins” and your redirect “Authorized redirect URI”(http://localhost:5000/auth/google/callback).

Google Strategy Setup

First Request Route Handler

‘get’ request to the route ‘/auth/google’

Auth Flow I

  • Google asks user to grant my app permission with their login credentials.
  • User grants permission by logging into their account.
  • The response from the first request contains the user profile and email, as well as a special code embedded in the query string of the response.
  • The user is put ‘on hold’ while the second request is executed.

Second Request Route Handler

The key difference with this handler is that when the initial request hits this handler the query string is appended with a special identifying code.

Auth Flow II

  • The first request is redirected to the callbackURL (“/auth/google/callback”) set up in the Google Strategy configuration with a query component ‘response code’ in the URL.
  • The route handler then calls passport.authenticate(“google”) — this time, with that special identifying code. It is this piece of code that allows passport to assume that this is not an initial request, but that the user is attempting to access a profile from this request.
  • Now the response makes its way back to the Google Strategy, where the final callback function is called and we see our accessToken, refreshToken, and profile printed out in the console. Rejoice.

Next Steps

This concludes the initial setup for Google OAuth using passportJS. The next step in my project will be setting up the database with MongoDB and persisting user information.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store