Third Party Login using OAuth & Passport.JS….
Hi Guys hope everything is going fine,in this blog I am going to describe how to do authentication using passport.js. Before we start of with our discussion first thing we should know is what is OAuth actually means :
OAuth stands for open authorization,it is one approach of user authentication ,it allows user to login to our application using third party service like Facebook,Google+ and GitHub. Login through 3rd party API services is really useful for both users and developers ,Users don’t have to fill the forms to login or signup in website,they also don’t have to remember different accounts password for login .For just a few central identifier an user can login anywhere.Also as a developer it frees your time to focus on the code base of your website.So now as we know the benefits of login with third party services,let’s see the whole picture of how the login with third party services actually works:
So let’s see how the third party API login actually happens, when a user click on the button sign in with google+ or sign in with Facebook button for login, google consent screen applies where google asked the user , this application, let’s say X application wants to see your basic profile information or your email id ,if a user click on allow, it will going to redirect them back and log them into our website using their social credentials ,then what we can do on our website, we can create a profile for them based on their Facebook or Google profile,and we can store version of their profile in our own database,So this is the basic understand we should have before we move on the detailed explanation of third party login.
Before starting coding we should have our database mongoDB and google+ API ready so that we can use them for storing and authenticating users in our website respectively,First let me tell you how to create a google +API. For creating a google+ API you have to go to google developer console ,you just google Google developer console, login with your gmail account ,create a project ,after creating a profile go to your dashboard which looks like this:
so your dashboard contains all the details of the api and project means what are the google apis used in your project how frequently they are used in your project what is the limitation of usage etc,so in order to enable API and services provided by google for your project click on the Enable apis and services button, search the API you want to enable click on enable button and it’s done, to use that API in our project we need to create our credentials.In our project we are going to use Google+API or Google People API, so search for it,enable it and click on create credential button ,now it will ask several questions, your email id ,in which type of application you are going to use it etc .In our case we will select web Application(Nodejs,Tomcat),Below is the screenshot for the create credential page in Google developer consent:
After filling all the details required for creating credentials ,you will land in this page:
So, we have successfully created our google API to use them in our application .Now we have to grab the client Id and client secret which are provided by the google developer console ,we will use these two things in our code base in order to use the API service in our application.But what are the two fields present below the details here ,Authorized JavaScript origin and Authorized redirect URIs.
Authorized JavaScript origin is the URI of the client Application,means the port number in which we are running our application, as we are developing the application in our own localhost,we will consider http://localhost:3000 as Authorized JavaScript origin of our Application. Authorized redirect URI is the URI in which the user will be landed in our website after getting authenticated by google,and the path will be appended with the authorized code for access.In our case we used http://localhost:3000/auth/google/direct as Authorized redirect URI .Then click on save button ,Now we are good to go and we can use this google API/service in our application.
Now Let’s develop the backend of our Application ,we will use mongoDB to create a database to store the user details who are logging into our application using third party Api, we are using Robo3t to create the database for our application. In order to connect mongoDB with our application we have to create a project database in Robo3t ,after that we have to use the link of the mongoDB database inside our code base .The link will be like this:
mongodb://localhost:27017/<name of your project>
Actually this is the link which will connect our application with MongoDB.So when we run app.js of our application (the root of our application) by running node app.js we will get this type of connection request in our Robo3t:
We have to click on Connect button after that a database gets automatically created in our Robo3t and the name of the our Database or collection will be the same as what we will give inside our code base will creating it soon.
So after that if we click on myproject folder we will see that there will be a folder named Collections inside that there will be our database:
So you can see that our user database is having the records of all the users who have logged in to our application using third party services.We will discuss about how this database gets created, how to design schema in details when we will actually start coding ,So friends now we are ready with our Api services and database for our application,and it’s time for looking into the coding part of our application.
Before we start coding we should know the big picture of third party login ,I will describe the whole process step by step and I will code accordingly so that the whole process is understandable.So we are using passport.js it’s really a wonderful package that helps us interacting with the browser while a user is logging into our application.Now let’s understand the whole process carefully:
When a user clicks on the login with Facebook or Google Button,the browser redirect user to our custom route first, through which OAuth ( in our case Google+ API ) grants permission from users to allows our website to use their social credentials to log them inside our website,when users clicks on the allow button our express application gets a unique code from google service provider and redirect the user on our redirect URI (http://localhost:3000/auth/google/direct). Then our application exchange the code with OAuth Provider to get the profile of that user and final it fires a callback function from our redirect Uri .Then we lookup or create user in our database, Now there are two important things that we need to know those are serializing and de-serializing user who has logged in to our website ,so what is serializing ? ,serializing is the process in which our application creates a unique cookie and send it to the browser so that whenever browser needs to access some information like profile,image etc about of the user who is logged in ,it will just send our express application that unique cookie so that we should not go through the whole process of authentication again and again.So creating the unique cookie and sending it to the browser is called the serializing users where as when browser sends that unique cookie back to our application for accessing required details of the logged in user it is called de- serializing users.Now we will see there are several points in the whole process where we will be using passport.js,such as passport.js is used when we are sending user to the OAuth provider route for granting permission ,while getting unique code from google after user allows our website to access their social credentials and lastly during serializing and de-serializing logged in user in our application. So let’s start coding now,First thing we will see is the folder structure of our application:
The folder structure of our application is having folders namely config ,node modules ,routes,views etc.config folder is containing keys.js and passport.config.js file ,keys contains the api details information such as the client id ,secret key and link of our project created in our Robo3t and passport.config is having the settings of passport.js. Node modules is created when we do npm i ,we will install few npm packages like mongoose,ejs,passport,express,cookie-session and passport-google-auth20 in order to install those packages we have to run:
npm install cookie-session passport passport-google-auth20 mongoose ejs express
Views folder is having component views and design of three pages of our application login,profile and home page, models folder contains the schema of our database to store information for logged in users in our application .In our case we have one file which contains the user details named user model.Lastly App.js is the root file of our application.
So App.js is the root file of our application,first we have to import express which is a node js framework,Cookie-session is the npm package which is used for creating a cookie session means you may notice that if you login to a website for long time it asks for password after a day or a week this session or period of time is a your cookie session,so cookie-session package creates this session for us.Then we imported passport js which actually communicates with the OAuth server and browser and makes many of our task easier .Then mongoose which is used to create schema of our model to create database for our user logged in to our website,and there are several routing files like auth-route and profile-route which are used to authenticate and show profile to the users by fetching data from their social credentials.we will talk about those files later and lastly keys contains all the api credentials that we had created earlier to use them in our application.Then we have created an instance of express named it app.
app.set(‘view.engine’,’ejs’)
in this line of code we are telling our express application to look at the ejs files of our code base to create the view or ui part of our application,our keys.js file inside config folder have a unique cookie session key which is used to create cookie for the user logged in to our application,we can give any string as our unique cookie session key for our application ,so we create a cookie session ,where MaxAge takes the period or time of cookie session for our users in millisecond we have set that time for one day :
24*60*60*1000 means 24 hours a day,60 mins an hour,60 seconds a min and 1000 millisecond a second.Then we have initialized passport and passport.session for creating the cookie session.Mongoose.connect actually connects our application with the backend (mongoDB) we have kept our project link inside our key.js file from there we are importing it,and when the connection is successful it will show a success message in our console .Then we have used our custom routes we will talk about it later,then we create our base route using app.get, res.render actually renders home.ejs file where we are sending user as payload.Finally we are telling our express application to listen on port number localhost:3000 for requests.Let’s now explore the view part of our application so let’s start with our very first page home.js:
Our HomePage.js is pity much self explanatory ,we have some simple css stuff inside styles tag then we are having a navbar at the top having three buttons when we just land to our application those are profile,homepage and login and once we logged in the login button will be changed to logout button ,so in order to check whether user is logged in or not we are sending the req obj from app.js ,so user will be true when an user is logged in so when user is true we will show logout button else we will show login button.We are also having our body having some header and paragraph ,Allover it’s a very simple view .
So let’s see the login page of our application :
It is almost same as profile page of our application ,in the body of the of our login page we have given a header and a Google+ button linked with /auth/google. This is the actually button by which user can actually login into our application.Let’s see the profile page of our application.
The Profile page of our website is also pity much simple it’s having a header where <%=user.username%> means that we are fetching data from our database user and showing the username of the user logged in ,similarly <%=user.thumbnail%> are fetching the thumbnail of our user logged in.So we have created our views now let’s see the routing part of our application.
Our route folder is having two files auth-route.js and profile-route.js ,so let’s see the auth-route.js file:
So for creating route we have to import Router from express ,and also passport, after that we are creating a ‘/login’ route where we are rendering login.ejs as the view file and sending req.user as the payload means login.ejs is taking the payload data and rendering it in the frontend, similarly ‘/logout’ is the route in which we are logging out the user and redirecting users to ‘/’ route means the home page of our application,Now I think you remember that when a user clicks on the button we redirect user to the page where they are authenticated with google+ where they are asked to allow our application to access user social credentials.
router.get(‘/google’,passport.authenticate(‘google’,{
scope:[‘profile’]}));
So here we are sending our user to ‘/google’ route then passport is authenticating the user using google authentication ,the scope part signifies the social data which our application wants to access for logging in our users,In our case we are accessing the profile info of our user from their social credentials,
router.get(‘google/direct’,passport.authenticate(‘google’),(req,res)=>{
res.redirect(‘/profile’);
});
so when the user clicks on the allow button , our express application gets a unique code from google service provider and redirect the user on our redirect URI (http://localhost:3000/auth/google/direct) then our application exchange the code with OAuth Provider to get the profile of that user and final it fires a callback function from our redirect URI,and send our user to the profile page.Finally we are export the router so that our app.js can use it for routing and authenticating our users, Now let’s see the profile-route of our application:
In profile-route.js we have to give security to our profile route means if a user directly goes to our profile route the user will be redirected to our login page so how will we do this, we are creating a authCheck method which takes three parameters req,res and next ,so if the user is logging the req.user will be true if the req.user is true we will send them to profile but if it is false we will redirect our user to ‘/auth/login’ means to our login page.In our code ,in the else part of authCheck ,next() means we are executing the next part of our code.So when the user is in the homepage page ‘/’ route and want to access the profile page we are adding authCheck function which checks whether the user is logged in to our website or not and accordingly directs the user to the profile or login page of our application.Finally we are export the router so that our app.js can use it for showing the user profile of our application.Now let’s create the schema of the database that will store the user’s social credentials .
In user-schema .js we are importing mongoose from mongoose ,and creating mongoose schema.We are then creating an instance of our mongoose.schema, userSchema having three parameters username,googleId and thumbnail.
const User=mongoose.model(‘user’,userSchema)
User is the mongoose model having the database named user using the schema UserSchema , user is the name to the database that will be created inside our Robo3t. Now let’s explore the config folder of our application which is having two files keys.js and passport-setup.js:
Key.js is the javaScript file which stores all the secret keys of our google services, mongodb and cookie sessions,now let’s see the passport-config file:
In passport-setup.js file we are importing passport,GoogleStrategy from ‘passport-google-oauth20’, importing keys from key.js, User from user-model.js.
Now we will see first passport.use part of our code.In that part we are creating GoogleStrategy which is taking api credentials like clientID,clientSecret ,we are also defining the callback Uri where the callback will happen,so the last thing remaining is storing the data in the database ,serializing and de-serializing the user logged in ,so the call back function will take four parameters namely accesstoken, refreshToken, profile and done .We will use profile which will carry social credentials of the logged in users,we will check whether the user already exists in our database or not if it’s true we will send the currentUser details to the passport for serialization and deserialization of user using the done parameter ,else we will store it into our database, will save and then send it to passport ,so when passport gets the user it takes user.id from the user database, keep it in mind this is not the googleId of the user because googleId is provided by google OAuth only if the user logs in by third party api ,this id is the id of the user that is automatically created by mongodb when the user details is created, so we are sending the user id to browser as a cookie token using passport.serializeUser function so that when ever browser needs to access some information about the logged in user, it will just call the passport.deserializeUser function where our application will check the id with our database and will verify the user so that the whole process of authenticating the user is not required to perform again and again, then will send the required information to the browser.So our application is now complete , we will run node app.js and see our application in http://localhost:3000:
So our application is up and running ,You can find code on my GitHub repo
CODE:
So there are many cool stuffs you can do using these awesome libraries, till then don’t stop exploring new things because exploration many a person better in all aspects of life.
HAPPY CODING…..:)