google authentication with Node.js (part 2)

For google authentication with Node.js after creating project in google console and getting credentials from google, now that we have “Client Id” and “Client secret” , it’s time to connect our express or node js application to google.

Before You Get Started to understand  “google authentication with Node.js”☝️

This tutorial need you to have a good understanding Node.js.

let’s start!

Step 1: Install Dependencies 🖥

It’s on NPM:

That was easy! or you can start with command:

npm i googleapis

Step 2: Configure Google

Next you will need to configure the library with your credentials ,I mean “Client Id” and “Client secret”, so Google knows who is making the requests.

To get credentials — if you don’t already have them — you can read previous article (part 1).

File: google-auth.js

const {google} = require("googleapis");
/*******************/
/** CONFIGURATION **/
/*******************/
const googleConfig = {
clientId: '<GOOGLE_CLIENT_ID>', // e.g. 563322924764-u4o5f5o8fovn7t9f24mh92jefqpjj3hl.apps.googleusercontent.com
clientSecret: '<GOOGLE_CLIENT_SECRET>', // e.g. swQWKv9GJv2bA2l2lCs70sMI
redirect: 'http://localhost:3000/validateWithGoogle' // this must match your google api settings
};

 

Step 3: Get the Google Login URL

In order for us to sign someone in to Google, we need to send them to the Google login page. From here, they will sign in to their account and then they will be redirect to our app with their sign in details.

you can use this function: getGoogleAuthenticationUrl()

/**
 * Part 1: Create a Google URL and send to the client to log in the user.
 */
getGoogleAuthenticationUrl: function () {
    return new Promise(async (resolve, reject) => {
        const auth = await GA.createConnection();
        const authorizeUrl = await GA.getConnectionUrl(auth);
        resolve({
            url: authorizeUrl
        });
    });
},

for using this function in express for example:

router.get('/authenticate', function(req, res, next) {
    gf.getGoogleAuthenticationUrl().then(function (response) {
        res.json(response);
    });
});

this route will make a url for client and we should redirect client to that url.

notice: we have imported google-auth.js before in top of our page like this:

var gf = require('../google-auth');

 

Step 4: Save the Sign In Details

You would have been able to sign in to your google account and Google would have redirected you back to your app (or the callback address you told it to go to). Now all we have to do is make sure the account they signed in with matches a user in our database (or create one).

To do this, Google has given us a parameter on the redirect address called “code”. You will see this as:

https://yourwebsite.com/callback?code=a-bunch-of-random-characters

You need to extract this “code” parameter and give it back to the Google api library to check who the logged in user is. Once you have the “code” parameter and you have sent it to your server, we can get the user’s email and id to use in our app.

we have to use this function: getGoogleAccountFromCode()

/**
 * Part 2: Take the "code" parameter which Google gives us once when the user logs in, then get the user's email and id.
 */
getGoogleAccountFromCode: async function (code) {

    const auth = await GA.createConnection();
    const data = await auth.getToken(code);
    const tokens = data.tokens;
    await auth.setCredentials(tokens);

    const people = GA.getGooglePeopleApi(auth);
    const me = await people.people.get({
        resourceName: 'people/me',
        personFields: 'emailAddresses,names,photos',
    });
    return me.data;

},

for using this function in express for example:

router.get('/validateWithGoogle', async function(req, res, next) {
    let s = await gf.getGoogleAccountFromCode(req.query.code);
    let obj = {
        emailAddresses: s.emailAddresses[0].value,
        photos: s.photos[0].url,
        displayName: s.names[0].displayName,
        familyName: s.names[0].familyName,
        givenName: s.names[0].givenName,
    };
    res.json(obj);
});

now you have two routes: GET /authenticate & GET /validateWithGoogle 😍

Full Version 💎

Here is a full version of the code with all of the comments. It’s also available on github.  Use this for a good overview. If you get stuck, check the examples above with explanations.

const {google} = require("googleapis");

/*******************/
/** CONFIGURATION **/
/*******************/

const googleConfig = {
    clientId: '<GOOGLE_CLIENT_ID>', // e.g. 563322924764-u4o5f5o8fovn7t9f24mh92jefqpjj3hl.apps.googleusercontent.com
    clientSecret: '<GOOGLE_CLIENT_SECRET>', // e.g. swQWKv9GJv2bA2l2lCs70sMI
    redirect: 'http://localhost:3000/validateWithGoogle' // this must match your google api settings
};

/**
 * This scope tells google what information we want to request.
 */
const defaultScope = [
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile',
];

var GA = module.exports = {

    /**
     * Create the google auth object which gives us access to talk to google's apis.
     */
    createConnection: function () {
        return new google.auth.OAuth2(
            googleConfig.clientId,
            googleConfig.clientSecret,
            googleConfig.redirect
        );
    },

    /**
     * Get a url which will open the google sign-in page and request access to the scope provided (such as calendar events).
     */
    getConnectionUrl: function (auth) {
        return auth.generateAuthUrl({
            access_type: 'offline',
            prompt: 'consent', // access type and approval prompt will force a new refresh token to be made each time signs in
            scope: defaultScope
        });
    },

    /**
     * Helper function to get the library with access to the google plus api.
     */
    getGooglePeopleApi: function (auth) {
        return google.people({
            version: 'v1',
            auth: auth,
        });
    },

    /**
     * Part 1: Create a Google URL and send to the client to log in the user.
     */
    getGoogleAuthenticationUrl: function () {
        return new Promise(async (resolve, reject) => {
            const auth = await GA.createConnection();
            const authorizeUrl = await GA.getConnectionUrl(auth);
            resolve({
                url: authorizeUrl
            });
        });
    },

    /**
     * Part 2: Take the "code" parameter which Google gives us once when the user logs in, then get the user's email and id.
     */
    getGoogleAccountFromCode: async function (code) {

        const auth = await GA.createConnection();
        const data = await auth.getToken(code);
        const tokens = data.tokens;
        await auth.setCredentials(tokens);

        const people = GA.getGooglePeopleApi(auth);
        const me = await people.people.get({
            resourceName: 'people/me',
            personFields: 'emailAddresses,names,photos',
        });
        return me.data;

    },
};

Yahoooo!! 🎉 🎊 👏

Your app now supports Google. To get access to any more of Google’s APIs, simply add them to your “scopes” array and when the user goes to sign in, they will be prompted to give you access to that data e.g. Google Calendar data.

Follow me on Instagram

google authentication with Node.js (part 2)
                

Leave a Reply

Your email address will not be published. Required fields are marked *