NodeJs Authentication via Google using PassportJs

Posted By : Nisheet Sharma | 24-Apr-2018

NodeJs: Authentication through Google using PassportJs


PassportJs is a extremely flexible authentication middleware. One of those authentication strategies, is authentication through Google.
We can authorize an user via their Google Accounts.

Steps to Implement the Google Oauth process into our node application:

1. You will first and foremost, need to create a Google Developer Account to access the Google API Console.
Go to https://console.developers.google.com/ and create a Google Developer account if you don't have one,
and you'll have to register your Project/Application in the dashboard.
Once you have setup your application, you can also setup Oauth 2.0 credentials needed for this process.
Then you'll receive a clientID and clientSecret.

2. Now, we'll install the PassportJs module using:
npm install passport

3. Lastly, lets install the Google Oauth Passport Strategy:
npm install passport-google-oauth


When all the dependencies are installed, we'll work on configuring the Google Authentication Process,
as we want in our application.

Lets create a new File, that'll configure and return a new Google PassportJs Strategy.

First, we'll require the modules passport and passport-google-oauth into our js file, as follows.

            //File: GooglePassportStrategy.js

            const passportjs = require('passport');
            const GooglePassportStrategy = require('passport-google-oauth').OAuth2Strategy;      
        

Now, we'll configure the Strategy to suit our needs.

Here we will make use of the clientID and clientSecret we got from Google Developer Account.

        var googleOptions = {
            clientID: 'CLIENT_ID_GENERATED_IN_GOOGLE_DEV_ACCOUNT',
            clientSecret: 'CLIENT_SECRET_GENERATED_IN_GOOGLE_DEV_ACCOUNT',
            callbackURL: "http://127.0.0.1:8080/oauth/google/callback"
          };
    

We'll have to define an API endpoint for callback, that Google will revert the user back to, once authorized.
So, here we assume we have an endpoint /oauth/google/callback, that will serve as the callback url.

In addition to the googleOptions, we'll need a callback function, that will get executed once,
Google has successfully authorized the user.
It should have the following arguments:
1. accessToken - This is the OAuth token generated by Google for the User.
2. refreshToken - This is the Refresh token, that can be used to renew the Oauth token via Google
3. profile - The profile argument will contain the user's google account profile data.
4. cb - This argument is the Callback function. The function will take two parameters, first is error for error responses,
second is user, for passing user's document object, if the user has been verified/registered successfully.

        var onAuthentication = (accessToken, refreshToken, profile, cb) => {
            
            //Let us assume, our application has a User model that stores all the user's data, needed by us.
            User.findOne({ googleOauthId: profile.id },
                function (err, userDoc) {
                    
                    if (err) { 
                        //If we encounter an error, signal that to passport module using cb(err)
                        return cb(err); 
                    }
                    if (!userDoc) {
                        // If the user doesn't exist create one
                        User.create({
                            googleOauthId: profile.id,
                            email: profile.email
                        }, (err, newUserDoc) {
                            if(err) return cb(err);
                            //If user obj is successfully created pass it to the callback.
                            return cb(null, newUserDoc);
                        });
                    }
                    else {
                        // If user already exists in our database, pass their details forward.
                        return cb(null, userDoc);
                    }
                }
            );
        };
    

Once, we have configured the strategy as above.
Then, create a new Google Oauth Authentication Strategy, using the passport-google-oauth module.
As shown below:

        var googleOauthStrategy = new GooglePassportStrategy(googleOptions, onAuthentication);
    

Lastly, we'll signal the PassportJs module to use our custom configured Google Oauth Authentication Strategy, as defined above.

        passportjs.use(googleOauthStrategy);
    

Now, lets define our oauth routes.
First, the api endpoint, we'll use to start the Google authentication process.

          app.get('/oauth/google',
          passportjs.authenticate('google', { scope: ['https://www.googleapis.com/auth/plus.login'] }));
    

This, will first redirect the User to the above mentions scope url. Where, user will log into their Google Account,
and when Google has authenticated them successfully, Google will redirect the user to the endpoint defined below.


The API endpoint, we'll use as Google's callback url, the one we passed as googleOptions while setting up the configuration.

          app.get('/oauth/google/callback',
          passportjs.authenticate('google', { failureRedirect: '/oauth/failure' }),
            function(req, res) {
              // The user's details will be appended to the req by PassportJs
              // So, you use it here.
              doSomethingAndRedirectUserToWelcomePage(req.user);
            });
    

About Author

Author Image
Nisheet Sharma

Nisheet is a Full Stack Developer (MEAN). He is familiar with C, C++, Java, Html, Css, JavaScript, MySql, MongoDb, AngularJs, NodeJs, ExpressJs.

Request for Proposal

Name is required

Comment is required

Sending message..