Google OAuth using Passport.js: How to get started
By: Manish Sharma
Tags: Google Oauth, Passportjs, Authentication, Expressjs, JavaScript

Getting Started

This tutorial will walk you through the process of creating a server side application with Google Authentication using Passport.js as it’s more convenient and quick for the user than creating a new login account.

Firstly we will be setting up out backend server and authentication routes and then will go on with the UI components in the frontend with React.

Tech Stack

Server Side: NodeJs, Express, MongoDB, Passport Google OAuth API

What is OAuth?

OAuth is an open-standard authorization for granting web application access to third-party sign-in services like Google, Facebook, Apple.

Benefits include that OAuth doesn’t share password data but instead uses authorization tokens to prove an identity between consumers and service providers.

For this tutorial, we will be using passport-google-oauth20 middleware to handle Google authentication

Setting up Project

mkdir google-oauth-project

cd google-oauth-project

mkdir server

cd server

npm init -y

Project Structure

|-- google-oauth-project

| |-- server

| | |-- index.js

| | |-- package.json

Server Side Implememtation

Part 1: Register your app as an OAuth provider at Google Developer Console.

Open the Google API Console Credentials page. Click Select a project, then NEW PROJECT, and enter a name for the project, and optionally, edit the provided project ID. Click Create. On the Credentials page, select Create credentials, then OAuth client ID. You may be prompted to set a product name on the Consent screen; if so, click Configure consent screen, supply the requested information, and click Save to return to the Credentials screen. Select Web Application for the Application type. In Authorized redirect URI use http://localhost:5000/auth/google/callback Click Create. On the page that appears, copy the client ID and client secret to your clipboard.

Part 2: Database Setup

I will be using MongoDB to store User login information.

Create a new cluster by going through MongoDB and get your MongoDB URI for connectivity between your application and database.

Part 3: Securing the Keys

For security purposes before hooking in Google Creadentials, save them in keys.js in config folder in server and add the file to .gitignore so that it won’t be committed to git.

In /config/keys.js

Part 4: Dependencies

Installing Dependencies for smooth functioning of code.

Express — To set up the server on the backend. Here we will run the server on port 5000 (http://localhost:5000/) Cors — Supports cross-origin browser Cookie-Session — Storing user session in cookies Mongoose — For database connectivity Passport and Passport-Google-OAuth20 — For google authentication using Passport

"cookie-session": "^1.4.0",

"cors": "^2.8.5",

"express": "^4.17.1",

"mongoose": "^5.10.3",

"passport": "^0.4.1",

"passport-google-oauth20": "^2.0.0"

Part 5: Setting up Authentication Routes

Let’s have a look at the server endpoints for google authentication and put them into practice.

/auth/google — authenticate via passport-google-oauth20 /auth/google/callback — redirect to your redirect URI which you set up in Google Developers Console /auth/login/success — returns user information on authentication success /auth/login/failed — returns login failed message on failed authentication /auth/logout — returns to Home Page

In routes/auth-routes.js

In index.js

Part 6: Creating a User model using Mongoose Schema

Create a user object model that represents the user profile in the database record

/models/user-model.js

Part 7: Setting up Google Startegy using Passport API

Passport API does the login authentication behind the scene so you do not need to handle the complex logic.

When Google replies with the user’s profile info, the server fires passport callback function, which looks up or creates user in our app’s database.

Since we only want one user record no matter how many times the user signs in, first our app needs to check whether our database already has this user with the given Google profile ID. If the answer is yes, we can skip creating a user in our database. However, if it’s not the case, we need to create a new user.

/config/passport.js

Serialization and deserialization are important concepts to know. Serialization is when the user gets encrypted from the database and sends it back to the browser as a cookie. Deserialization is when the user cookie gets decrypted from the browser to the database.

In order to support login sessions, Passport will serialize and deserialize user instance to and from the session.

Congratulations! We did it! We have successfully used Passport.js to set up Google OAuth.

Thank You for reading this blog post.

If you have any feedback or comments, feel free to comment below.