Goolge login in node js with passport example; In this tutorial, i will show you complete guide on how to implement a google login authentication system in node js express using passport js.
Google Login with Passport + Node JS
- Step 1 – Create Google Login Console App
- Step 2 – Install Node Express JS Setup
- Step 3 – Import Packages and routes in app.js
- Step 4 – Create views
- Step 5 – Start Development Server
Step 1 – Create Google Login Console App
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
Step 2 – Install Node Express JS Setup
Run following command on terminal to create node js express directory:
mkdir GoogleAuth
Then open GoogleAuth directory with any text editor. And use the following command to enter your GoogleAuth app directories, So open your cmd and run the following command:
cd GoogleAuth
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
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 – Import Packages and routes in app.js
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'); });
Complete source code of app.js file; as shown below:
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
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
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>
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 Development Server
Run the following command on cmd 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
Node express js google auth login example tutorial. You have learned how to create google authentication in node js express with passport.
Be First to Comment