Login with Google in Node.js Application

Pankaj Kumar - Jun 30 '23 - - Dev Community

In this article, We will create a demo to login with google in our nodejs application. Since login with social is almost availalble at maximum number of mobile or web application. Also I have already covered the login with twitter and facebook over this patform earlier. So let's proceed to create the app step by step.

Step 1: Create client id and secret:

Follow the link to create a app over goole for getting client id and secret Click here). After clicking a page wll open with option to create a new app or to select the previously created app. So click on create button. See the image

Image description

And setup the basic information of your application which google will show what type of consent user gives your app to use information from google. Here in the demo I am going to use the basic info.

Image description

Fill the details of the application as shown over the image. Once you fill the basic informtion then need to generate the client id and secret. Here I will create it for web browser so need to choose this option while creating client id and secret.

Image description

In the above image we can see there is option to choose the option of platform we want to use the social login, the app name and callback url at the bottom. Make sure the path in the redirectURIs should be exact same as we will set in the passport. After submitting this form we will get the client id and secret.

Image description

Now our task of creating Client ID and secret is finished. Now move to next step.

Step 2: Set passport and all code related stuff.

Node let's configure the task at nodejs end. So lets see our server.js file, which is having all the major task at nodejs end.


var express = require('express'),
util = require('util'),
session = require('express-session'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
router = express.Router(),
app = express();

var passport = require('passport');
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));

// session related task & passport intiallization...
app.use(session({ secret: 'jsonworldplaceforjsdemos'}));
app.use(passport.initialize());
app.use(passport.session());

// Passport session setup.
passport.serializeUser(function(user, done) {
done(null, user);
});

passport.deserializeUser(function(obj, done) {
done(null, obj);
});

passport.use(new GoogleStrategy({
clientID: "PUT_CLIEND_ID",
clientSecret: "PUT_CIENT_SECRET",
callbackURL: "http://127.0.0.1:3000/auth/google/callback"
},
function(accessToken, refreshToken, profile, done) {
return done(null, profile);
}
));

// Using FacebookStrategy within Passport here to perform the actual task...
/* GOOGLE ROUTER */
app.get('/google',
passportGoogle.authenticate('google', { scope: ['https://www.googleapis.com/auth/plus.login'] }));

app.get('/auth/google/callback',
passportGoogle.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});

app.get('/', function(req, res){
res.render('index', { user: req.user });
});

function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}

app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});

app.listen(3000,function(){
console.log('server running on port:3000')
});

Enter fullscreen mode Exit fullscreen mode

In the above file, At top we have included the needed nodejs package with passport related packages. And below that we have configured passport. And at bottom we have defined the routing in our app.

Now lets come to the view part, have a look our ejs file. Let's have a look on index.ejs file.


<% if (!user) { %>
<div style="width:500px;height:180px;background-color:#ececec;padding:80px;margin-left:22%;margin-top:9%;">
    <h2 style="font-size:40px;">Welcome! Please log in.</h2>

    <a href="/google"><img src="login-with-google.png" width="171" height="34"></a>
    </div>
<% } else { %>

    <div style="width:500px;height:180px;background-color:#ececec;padding:80px;margin-left:22%;margin-top:9%;">
            <h2>Hello, <%= user.displayName %>.</h2>
        <p >
                <a style="padding-right:10px;" href="/">Home</a> |
                <a style="padding-right:10px;" href="/logout">Log Out</a>
            </p>

                <h3>My Profile</h3>
                            <p>ID: <%= user.id %></p>
                            <p>Username: <%= user.username %></p>
                            <p>Name :<%= user.displayName %></p>

            </div>

<% } %>

Enter fullscreen mode Exit fullscreen mode

In the above file we are managing log in button or profile data after login. Follow the steps provided in the read.me file and run the app with url http://localhost:3000.

That’s all for now. Thank you for reading and I hope this post will be very helpful for implementation of login with google in nodejs application.

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends.

This article is originally posted over jsonworld.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player