Node + OAuth + google plus

In this blog, we will learn how to use open authentication while working with Node JS. We will be using Yarn package manager for managing node dependencies.
Let’s initialize Yarn and proceed with installing necessary dependencies.
Install yarn using node package manager.

Create a project directory and execute the following commands in terminal.

Passport.js is a library in node environment to implement OAuth with ease. Let’s install passport as our dependency.

Let’s install other dependencies like express and dev dependencies like nodemon.

After installing all the above dependencies package.json should look like below (versions may vary)

package.json

The folder structure of our application looks like below.

Let’s create server.js file to configure node server and manage middleware

server.js

In order to use google plus oauth, we need to register our application with google using google cloud console.

Head over to credentials menu in the above screen and create an application, with host details, for development we can use http://localhost:<port>.

On creation of client we will be presented with a screen as below with client id and secret

Let’s now resume our coding, export client credentials from auth.js.

we need to persist the user data to a data store on successful OAuth for the first time. In this blog, we would use mongo DB and mongoose for Object-Document mapping.

Mongoose uses models to persist data to Mongo DB. Let’s create a user model object.

We now need to configure mongo DB server connections which would be used to store user account data and social profile details.

Last but not the least, let’s configure passport OAuth configuration.

Now that we are done with passport configuration let’s go ahead and define our application routes/endpoints.

we have registered localhost:9090/oauth as trusted javascript origin and localhost:9090/oauth/redirect as redirect URI in google cloud console. so let us define these routes.

Finally, Let’s configure views of the application.

Index.ejs

Profile.ejs

variables in profile.ejs are passed in the routes like below

Now let’s configure routes and mongoose in server.js

server.js

Now let’s start the server using npm start command, in order to use npm start command we need to add script to package.json

open terminal and run npm start Now let’s open localhost:9090 in browser

on logging in successfully, we will get profile data which is shown

 we have successfully retrieved the social profile of a user and persisted in our mongo DB