Open In App

Google Authentication using Passport in Node.js

Last Updated : 14 Apr, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The following approach covers how to authenticate with google using passport in nodeJs. Authentication is basically the verification of users before granting them access to the website or services. Authentication which is done using a Google account is called Google Authentication. We can do Google authentication using OAuth API which is provided by Google on their developer portal.

Creating Node Project And Installing Module:

Step 1: Creating Node project using the following command.

npm init

Keep pressing enter and enter “yes/no” accordingly at the terminus line.

Step 2: Installing required modules.

npm install express passport passport-google-oauth2 cookie-session

Step 3: Creating two files index.js and passport.js

Project Structure:

Step 4: Create basic server.

index.js




const express = require('express');
const app = express();
  
app.get('/' , (req , res) => {
    res.send("<h1>GeeksForGeeks</h1>");
});
  
app.listen(4000 , () => {
    console.log("Server running on port 4000");
});


Output:

Step 5: Now go to google platform and generate your credentials.

Step 6: creating login functionality.

passport.js




const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth2').Strategy;
  
passport.serializeUser((user , done) => {
    done(null , user);
})
passport.deserializeUser(function(user, done) {
    done(null, user);
});
  
passport.use(new GoogleStrategy({
    clientID:"YOUR ID", // Your Credentials here.
    clientSecret:"YOUR SECRET", // Your Credentials here.
    callbackURL:"http://localhost:4000/auth/callback",
    passReqToCallback:true
  },
  function(request, accessToken, refreshToken, profile, done) {
    return done(null, profile);
  }
));


index.js




const express = require('express');
const app = express();
const passport = require('passport');
const cookieSession = require('cookie-session');
require('./passport');
  
app.use(cookieSession({
    name: 'google-auth-session',
    keys: ['key1', 'key2']
}));
app.use(passport.initialize());
app.use(passport.session());
    
  
app.get('/', (req, res) => {
    res.send("<button><a href='/auth'>Login With Google</a></button>")
});
  
// Auth 
app.get('/auth' , passport.authenticate('google', { scope:
    [ 'email', 'profile' ]
}));
  
// Auth Callback
app.get( '/auth/callback',
    passport.authenticate( 'google', {
        successRedirect: '/auth/callback/success',
        failureRedirect: '/auth/callback/failure'
}));
  
// Success 
app.get('/auth/callback/success' , (req , res) => {
    if(!req.user)
        res.redirect('/auth/callback/failure');
    res.send("Welcome " + req.user.email);
});
  
// failure
app.get('/auth/callback/failure' , (req , res) => {
    res.send("Error");
})
  
app.listen(4000 , () => {
    console.log("Server Running on port 4000");
});


Step to Run Application: Run the application using the following command from the root directory of the project:

node index.js

Output: 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads