How to implement Google Authentication in Node JS using Passport Tutorial?

15-Dec-2022

.

Admin

How to implement Google Authentication in Node JS using Passport Tutorial?

Hello Friends,

In this example, you will learn how to implement google authentication in node js using the passport tutorial. I would like to share with you google authentication for the node js application using a passport. I would like to show you google authentication using a passport in node.js. Here you will learn to build a notes app with google authentication in node.js.

As well as learn how to handle Session, passport, and ejs in node express js. And this google login node.js passport tutorial will help you step by step to create a google auth login system in node express js framework with passport js.

Step 1: Install Node Express JS Setup


Create a client ID and client secret from Google API Console. So, You need to follow the below steps once you open Google API Console:

  • From the project drop-down, select an existing project, or create a new one by selecting Create a new project
  • In the sidebar under “APIs & Services”, select Credentials
  • In the Credentials tab, select the Create credentials drop-down list, and choose OAuth client ID.
  • Under Application type, select Web application.
  • In Authorized redirect URI use http://localhost:3000/auth/google/callback
  • Press the Create button and copy the generated client ID and client secret
  • Note: If Google doesn’t support http://localhost:3000, then use http://127.0.0.1:3000

    Step 2: Install Node Express JS Setup

    In this step, execute the following command on the terminal to create a directory:

    mkdir gAuth

    After open gAuth directory with any text editor. And use the following command to enter your gAuth app directories, So open your cmd and run the following command:

    cd gAuth

    Now, execute the following command on the terminal to install express, ejs, express-session, and passport:

    npm init -y

    npm install express ejs express-session passport passport-google-oauth --save

    Your node express js app structure looks like:

    express-flash

    Flash is an extension of connect-flash with the ability to define a flash message and render it without redirecting the request.
    In this node js MySQL crud tutorial express flash is used to display a warning, error, and information message

    express-session

    Express-session is used to make a session as like in PHP. In this node js MySQL crud tutorial, the session is needed as the express requirement of express-flash.

    EJS

    To render HTML pages for login and profile

    passport

    Social Authentication package for Node.js

    passport-google-oauth

    Google authentication module by Passport.js

    Step 3: Include Packages and routes in the app.js

    In this step, you need to create a file app.js in the root folder of your app and add the following code:

    // app.js

    /* EXPRESS */

    const express = require('express');

    const app = express();

    const session = require('express-session');

    app.set('view engine', 'ejs');

    app.use(session({

    resave: false,

    saveUninitialized: true,

    secret: 'SECRET'

    }));

    app.get('/', function(req, res) {

    res.render('pages/auth');

    });

    const port = process.env.PORT || 3000;

    app.listen(port , () => console.log('App listening on port ' + port));

    The above code will set up our web server, Now you will add the code related to the passport at the bottom of the app.js file:

    // app.js

    /* PASSPORT SETUP */

    const passport = require('passport');

    var userProfile;

    app.use(passport.initialize());

    app.use(passport.session());

    app.set('view engine', 'ejs');

    app.get('/success', (req, res) => res.send(userProfile));

    app.get('/error', (req, res) => res.send("error logging in"));

    passport.serializeUser(function(user, cb) {

    cb(null, user);

    });

    passport.deserializeUser(function(obj, cb) {

    cb(null, obj);

    });

    To implement Google Authentication in our app. So, Add the following code at the bottom of your app.js file, use your client Id and Secret instead of placeholders:

    // app.js

    /* Google AUTH */

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

    const GOOGLE_CLIENT_ID = 'our-google-client-id';

    const GOOGLE_CLIENT_SECRET = 'our-google-client-secret';

    passport.use(new GoogleStrategy({

    clientID: GOOGLE_CLIENT_ID,

    clientSecret: GOOGLE_CLIENT_SECRET,

    callbackURL: "http://localhost:3000/auth/google/callback"

    },

    function(accessToken, refreshToken, profile, done) {

    userProfile=profile;

    return done(null, userProfile);

    }));

    app.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] }));

    app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/error' }),

    function(req, res) {

    // Successful authentication, redirect success.

    res.redirect('/success');

    });

    Full app.js file code here:

    const express = require('express');

    const app = express();

    const session = require('express-session');

    const passport = require('passport');

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

    const GOOGLE_CLIENT_ID = 'our-google-client-id';

    const GOOGLE_CLIENT_SECRET = 'our-google-client-secret';

    app.set('view engine', 'ejs');

    app.use(session({

    resave: false,

    saveUninitialized: true,

    secret: 'SECRET'

    }));

    app.get('/', function(req, res) {

    res.render('pages/auth');

    });

    var userProfile;

    app.use(passport.initialize());

    app.use(passport.session());

    app.get('/success', (req, res) => res.send(userProfile));

    app.get('/error', (req, res) => res.send("error logging in"));

    passport.serializeUser(function(user, cb) {

    cb(null, user);

    });

    passport.deserializeUser(function(obj, cb) {

    cb(null, obj);

    });

    passport.use(new GoogleStrategy({

    clientID: GOOGLE_CLIENT_ID,

    clientSecret: GOOGLE_CLIENT_SECRET,

    callbackURL: "http://localhost:3000/auth/google/callback"

    },

    function(accessToken, refreshToken, profile, done) {

    userProfile=profile;

    return done(null, userProfile);

    }));

    app.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] }));

    app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/error' }),

    function(req, res) {

    // Successful authentication, redirect success.

    res.redirect('/success');

    });

    const port = process.env.PORT || 3000;

    app.listen(port , () => console.log('App listening on port ' + port));

    Step 4: Create views

    In this step, you need to create directory name pages and then create auth directory inside pages. So go to the views directory in your app and create the pages/auth directory.

    Inside the pages/auth directory, you need to create two views files. The views file is the following:

  • login.ejs
  • success.ejs
  • Application-folder/views/pages/auth/login.js

    Now, open your login.ejs file and update the following code into your file:

    <!doctype html>

    <html>

    <head>

    <title>How to implement Google Authentication in Node JS using Passport Tutorial?</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

    <style>

    body {

    padding-top:70px;

    }

    </style>

    </head>

    <body>

    <div class="container">

    <div class="jumbotron text-center text-primary">

    <h1><span class="fa fa-lock"></span> Social Authentication</h1>

    <p>Login or Register with:</p>

    <a href="/auth/google" class="btn btn-danger"><span class="fa fa-google"></span> SignIn with Google</a>

    </div>

    </div>

    </body>

    </html>

    This login.ejs file contains the login form.

    Application-folder/views/pages/auth/success.js

    Next, open your success. ejs file and update the following code into your file:

    <!doctype html>

    <html>

    <head>

    <title>Google SignIn</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <!-- load bootstrap css -->

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <!-- load fontawesome -->

    <style>

    body {

    padding-top:70px;

    }

    </style>

    </head>

    <body>

    <div class="container">

    <div class="jumbotron">

    <h1 class="text-primary text-center"><span class="fa fa-user"></span> Profile Information</h1>

    <div class="row">

    <div class="col-sm-6">

    <div class="well">

    <p>

    <strong>Id</strong>: <%= user.id %><br>

    <strong>Email</strong>: <%= user.emails[0].value %><br>

    <strong>Name</strong>: <%= user.displayName %>

    </p>

    </div>

    </div>

    </div>

    </div>

    </div>

    </body>

    </html>

    Step 5: Start Node js Googel Auth App Server

    You can use the following command to run the development server:

    //run the below command

    npm start

    after run this command open your browser and hit

    http://127.0.0.1:3000

    OR

    http://localhost:3000

    I hope it can help you...

    #Node JS