,

Setting up Google OAuth2.0 for authentication in a Node.js Express.js application with Passport.js

Posted by


OAuth 2.0 is an authorization framework that enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf.

In this tutorial, we will be using Google OAuth 2.0 to authenticate users in a Node.js application using Express.js and Passport.js.

  1. Set up a Google Cloud project:
  • Go to the Google Cloud Console (console.cloud.google.com).
  • Create a new project and give it a name.
  • Enable the Google+ API in the library tab.
  • Create OAuth 2.0 credentials by navigating to APIs & Services -> Credentials -> Create Credentials -> OAuth client ID.
  • Set the redirect URI to http://localhost:3000/auth/google/callback (or any URL that you want to redirect to after authentication).
  • Note down the client ID and client secret, as we will need them later in the code.
  1. Set up a new Node.js project:
  • Create a new Node.js project by running npm init in the terminal and following the prompts.
  • Install Express.js and Passport.js by running npm install express passport passport-google-oauth20 in the terminal.
  1. Create the Express.js server:
  • Create a new index.js file and require Express, Passport, and the Passport Google OAuth strategy.
  • Set up an Express server with routes for authentication and user information.
const express = require('express');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;

const app = express();

app.get('/auth/google', passport.authenticate('google', { scope: ['profile'] }));

app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/' }), 
(req, res) => {
    res.redirect('/profile');
});

app.get('/profile', (req, res) => {
    res.send(req.user);
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});
  1. Set up Passport.js with the Google OAuth strategy:
  • Initialize Passport and serialize/deserialize the user.
  • Configure the Google OAuth strategy with the client ID and client secret obtained from the Google Cloud Console.
passport.use(new GoogleStrategy({
    clientID: 'YOUR_CLIENT_ID',
    clientSecret: 'YOUR_CLIENT_SECRET',
    callbackURL: 'http://localhost:3000/auth/google/callback'
}, (accessToken, refreshToken, profile, done) => {
    return done(null, profile);
}));

passport.serializeUser((user, done) => {
    done(null, user);
});

passport.deserializeUser((user, done) => {
    done(null, user);
});

app.use(passport.initialize());

app.use(passport.session());
  1. Run the application:
  • Start the Node.js server by running node index.js in the terminal.
  • Navigate to http://localhost:3000/auth/google in your browser to initiate the authentication flow.
  • Log in with your Google account and authorize the application to access your profile.
  • You will be redirected to the /profile route, which will display your user information.

Congratulations! You have successfully implemented Google OAuth 2.0 authentication in a Node.js application using Express.js and Passport.js. This setup allows users to log in with their Google accounts securely and access protected routes in your application.

0 0 votes
Article Rating
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@FarhaadBukhari
1 month ago

Nice video…

But you can explain in hindi… there's no shame in hindi

@PrayagBhosale-hb5wq
1 month ago

awesome video.. sir could you plz share the code