INTRODUCTION
In this blog or article we are going to learn how to implement authentication via Google in Node.js web application. In this we are using Passport.js as an authentication package for our web application.
PREREQUISITE
- Basic knowledge of HTML/CSS and EJS
- Good Knowledge of JavaScript and NodeJS
- NodeJS should be installed on System
CREATING GOOGLE CLIENT SECRET AND CLIENT ID
We Can create a client ID and client secret using Google API Console. So follow the steps given in video.
CREATING A PROJECT
Create an empty folder and run following command in terminal in particular folder
npm init -y
Now install the following dependencies in your project
npm install express ejs express-session passport passport-google-oauth --save
CODE EXAMPLES
- Create a file 'index.js' in the root folder and add the following code
const express = require('express');
const app = express();
const session = require('express-session');
const passport = require('passport');
require('./googleAuth');
app.use(session({
resave: false,
saveUninitialized: true,
secret: 'anysecret'
}));
app.use(passport.initialize());
app.use(passport.session());
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render('auth');
});
app.get('/success',(req,res)=>{
res.render('profile',{user:req.user});
})
app.get('/error', (req, res) => res.send("error logging in"));
app.get('/auth/google',
passport.authenticate('google', { scope : ['profile', 'email'] }));
app.get('/auth/google/callback',
passport.authenticate('google',{
failureRedirect: '/error',
successRedirect: '/success',
}));
const port = process.env.PORT || 3000;
app.listen(port , () => console.log('App listening on port ' + port));
- Now Create a file 'googleAuth.js' and add the following code
const passport = require('passport');
require('dotenv').config()
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
const GOOGLE_CLIENT_ID =process.env.GOOGLE_CLIENT_ID
const GOOGLE_CLIENT_SECRET =process.env.GOOGLE_CLIENT_SECRET
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) {
return done(null, profile);
}
));
- For EJS create folder 'views' in root folder and create a './views/auth.ejs' file and add the following code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register with Social Media</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="jumbotron text-center text-success">
<h1>User Resgistration </h1>
<p>Login or Register with:</p>
<a href="/auth/google" class="btn btn-primary"><i class="fa-brands fa-google" style="color:red;"></i> Login with Google</a>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</body>
</html>
- Again create a file './views/profile.ejs' and add the code given below
<!doctype html>
<html>
<head>
<title>Profile</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<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>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</body>
</html>
RUNNING PROJECT AND RESULTS
Finally for Running Project just simply type "node index.js" or "npm start" in terminal and project will run and go to browser and type "http://localhost:3000"
0 Comments