Node JS Google Authentication with Passport Tutorial

Node.js is a powerful JavaScript runtime environment that allows you to create dynamic web applications. It is also a great platform for creating secure authentication systems. In this tutorial, we will be using the Passport.js library to create a Google authentication system for our Node.js application.

1. Setting Up the Project

First, we need to create a new Node.js project. We can do this by running the following command in the terminal:

npm init

This will create a package.json file in the current directory.

2. Installing Dependencies

Next, we need to install the necessary dependencies for our project. We will be using the Passport.js library for authentication, so we need to install it first. We can do this by running the following command in the terminal:

npm install passport

We also need to install the passport-google-oauth20 library, which will allow us to authenticate with Google. We can do this by running the following command in the terminal:

npm install passport-google-oauth20

3. Setting Up the Google OAuth

Now that we have our dependencies installed, we need to set up the Google OAuth. To do this, we need to create a new project in the Google Developer Console. Once you have created the project, you will need to generate a Client ID and Client Secret.

Once you have the Client ID and Client Secret, you will need to add them to your Node.js application. We can do this by creating a new file called config.js and adding the following code:

module.exports = {
google: {
clientID: ‘YOUR_CLIENT_ID’,
clientSecret: ‘YOUR_CLIENT_SECRET’
}
};

4. Setting Up the Passport Strategy

Now that we have our Google OAuth credentials, we need to set up the Passport strategy. We can do this by creating a new file called passport.js and adding the following code:

const passport = require(‘passport’);
const GoogleStrategy = require(‘passport-google-oauth20’).Strategy;
const config = require(‘./config’);

passport.use(
new GoogleStrategy(
{
clientID: config.google.clientID,
clientSecret: config.google.clientSecret,
callbackURL: ‘/auth/google/callback’
},
(accessToken, refreshToken, profile, done) => {
// This is where you would add your user to the database
// and return the user object
return done(null, profile);
}
)
);

5. Setting Up the Routes

Now that we have our Passport strategy set up, we need to create the routes for our authentication system. We can do this by creating a new file called routes.js and adding the following code:

const express = require(‘express’);
const passport = require(‘passport’);

const router = express.Router();

router.get(‘/auth/google’, passport.authenticate(‘google’, { scope: [‘profile’] }));

router.get(
‘/auth/google/callback’,
passport.authenticate(‘google’, { failureRedirect: ‘/login’ }),
(req, res) => {
// Successful authentication, redirect home.
res.redirect(‘/’);
}
);

module.exports = router;

6. Setting Up the Server

Finally, we need to set up the server for our application. We can do this by creating a new file called server.js and adding the following code:

const express = require(‘express’);
const passport = require(‘passport’);
const routes = require(‘./routes’);

const app = express();

// Initialize Passport
app.use(passport.initialize());

// Set up routes
app.use(‘/’, routes);

// Start the server
app.listen(3000, () => {
console.log(‘Server is running on port 3000’);
});

Now that we have our server set up, we can start it by running the following command in the terminal:

node server.js

And that’s it! You now have a fully functioning Google authentication system for your Node.js application.
[ad_1]

Goolge login authentication in node js express with passport. In this tutorial, you will learn how to implement a google login authentication system in node js express 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.

Google Authentication with Passport In Node JS Express

  • Step 1: Create Google Console App
  • Step 2: Install Node Express JS Setup
  • Step 3: Include Packages and routes in app.js
  • Step 4: Create views
  • Step 5: Start Node js Googel Auth App Server

Step 1: Install Node Express JS Setup

Create a client ID and client secret from 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

Step 2: 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 -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 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 3: 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');
  });

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

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 5: Start Node js Googel Auth App 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.

Recommended Node Js Tutorials

[ad_2]

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

GSTIN is 03EGRPS4248R1ZD.

Contact
Jassweb, Rai Chak, Punjab, India. 143518
Item added to cart.
0 items - 0.00