Node JS Google Authentication with Passport Example
Node Js 02-Apr-2021

Node JS Google Authentication with Passport Example

Goolge login authentication in node js with passport. In this tutorial, you will learn how to implement a google login authentication system in node js using passport js.

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

Before you get started google login node.js passport, you should have basic Knowledge of the followings:

  • Basic knowledge of HTML/CSS
  • A good understanding of JavaScript and Node.js
  • Latest Node.js version installed on your system

First of all, you need to create a client ID and client secret using its Google API Console. So, You need to follow 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

Google Authentication with Passport In Node JS

Follow the following steps and create login system in node js using express js framework with MySQL db:

  • Step 1: Install Node Express JS Setup
  • Step 2: Include Packages and routes in app.js
  • Step 3: Create views
  • Step 4: Run Development Server

Step 1: Install Node Express JS Setup

In this step, execute the following command on terminal to create 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 terminal to install express, ejs, express-session and passport:

npm init
 
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 made a session as like in PHP. In this node js mysql crud tutorial, 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 2: Include Packages and routes in 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');
  });

app.js file code:

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 3: 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 direcotry, you need to create two views file. The views file is the following:

  • login.ejs
  • success.ejs

Application-folder/viwes/pages/auth/login.js

Now, open your login.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">
    <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 login form.

Application-folder/viwes/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 4: Run Development Server

You can use the following command to run 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

Conclusion

In this node express js google auth login example tutorial. You have learned how to create google authentication in node js express with passport.