In today’s world, many web applications require users to have an account to access all of their features. However, the process of creating an account can be cumbersome and time-consuming for users. Therefore, many developers choose to integrate social login options, such as Google Sign-In, to make it easier for users to access their applications.
Goolge login authentication in node js express. In this tutorial, you will learn how to implement Google Sign-In in a Node.js Express application using the Passport.js authentication middleware.
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.
How to Sign In with oauth2 Google in Node.js Express
By following these steps, you can easily add oauth2 Google Sign-In to your Node.js application and make it easier for users to access your application.
- Step 1: Set up a Google Cloud Platform (GCP) project
- Step 2: Create a Google Sign-In client ID
- Step 3: Create Node Express App and Install required packages
- Step 4: Set up Passport.js
- Step 5: Create views
- Step 6: Start Node js Googel Auth App Server
Step 1: Set up a Google Cloud Platform (GCP) project
To use Google Sign-In, we need to set up a GCP project and enable the Google Sign-In API. Here are the steps to follow:
- Go to the Google Cloud Console and create a new project by clicking on the “Create Project” button.
- Give your project a name and click on the “Create” button.
- Once the project is created, click on the “Navigation Menu” in the top-left corner of the console, and navigate to “APIs & Services” -> “Dashboard”.
- Click on the “+ ENABLE APIS AND SERVICES” button and search for “Google Sign-In API” in the search bar.
- Select the API and click on the “Enable” button.
Step 2: Create a Google Sign-In client ID
Now that the API is enabled, we need to create a client ID that will allow our Node.js application to authenticate with Google Sign-In. Here are the steps to follow:
- In the GCP Console, navigate to “APIs & Services” -> “Credentials”.
- Click on the “+ CREATE CREDENTIALS” button and select “OAuth client ID”.
- Choose “Web application” as the application type.
- Give your client ID a name.
- Add the authorized JavaScript origins and redirect URIs for your application.
- Click on the “Create” button.
- Note down the client ID that is generated. We will need it in the next step.
Note: If Google doesn’t support http://localhost:3000, then use http://127.0.0.1:3000
Step 3: Create Node Express App and Install required packages
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
You will use the Passport.js library to authenticate users with Google Sign-In. Here are the packages Yneed to install:
- passport
- passport-google-oauth20
To install the packages, run the following command in your project directory:
npm init -y npm install express ejs express-session passport passport-google-oauth --save
Your node express js app structure looks like:
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 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.
To render HTML pages for login and profile
Social Authentication package for Node.js
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:
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));
The above given code sets up a Node.js Express server that uses Passport.js and Google OAuth 2.0 for authentication.
First, the necessary packages are imported using require()
: Express, Express session, Passport, and the Passport Google OAuth 2.0 strategy. The Google Client ID and Client Secret are also declared.
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';
The view engine is set to EJS, and an Express session middleware is used with a secret string.
app.set('view engine', 'ejs'); app.use(session({ resave: false, saveUninitialized: true, secret: 'SECRET' }));
A route is set up for the home page, which renders a view that will display the Google Sign-In button.
app.get('/', function(req, res) { res.render('pages/auth'); });
A variable userProfile
is declared to store the user’s profile data after authentication. Passport is initialized and used as middleware, and two routes are set up to handle successful and failed authentication.
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"));
Two functions serializeUser
and deserializeUser
are defined to handle the serialization and deserialization of the user’s session data.
passport.serializeUser(function(user, cb) { cb(null, user); }); passport.deserializeUser(function(obj, cb) { cb(null, obj); });
A new Google OAuth 2.0 strategy is created with the client ID, client secret, and callback URL. When the user successfully authenticates, their profile data is stored in the userProfile
variable, and the done()
function is called to pass the data to the deserializeUser
function.
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); } ));
Two routes are set up to initiate and handle the Google Sign-In flow. The passport.authenticate
middleware is used to authenticate the user with the Google OAuth 2.0 strategy.
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'); });
Finally, the server is started on the specified port or on the default port 3000.
const port = process.env.PORT || 3000; app.listen
Step 5: 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 6: 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 example tutorial. You have learned how to implement Google Sign-In in a Node.js Express application. We set up a Google Cloud Platform project, created a client ID, installed the required packages, set up Passport.js, created the authentication routes, and protected the routes that require authentication. By following these steps, you can easily add Google Sign-In to your Node.js application and make it easier for users to access your application.