Lang
Blog

Google Sign-in Functionality through Passport JS

ByMohammad Kaif Lahori
January 10th . 5 min read
Google Sign-in Functionality through Passport JS

In an age where user convenience and security reign supreme, integrating streamlined authentication mechanisms becomes paramount for web applications. Among the myriad of authentication solutions available, leveraging Google Sign-In via Passport.js stands as a robust, user-friendly choice, promising both ease of implementation and robust security protocols.

In this comprehensive guide, we'll delve into the realm of authentication, focusing specifically on harnessing the power of Google Sign-In through Passport.js. Whether you're a seasoned developer seeking a reliable authentication method or a novice looking to fortify your app's login process, this step-by-step walk through will unravel the intricacies of setting up Google Sign-In seamlessly using Passport.js.

Strap in as we embark on a journey to elevate your app's user experience and security paradigm.

Step 1:

Set up Your node js project.

  • First install node js and npm in your system using this cmd:
$ sudo apt-get install nodejs
 $ sudo apt-get install npm
  • Install express and express-generator
$ npm install express
$ npm install -g express-generator
  • Use the express application generator tool, express-generator, to quickly create an application skeleton.
$ npx express-generator
  • Run your project using
$ npm run start

Note: If you add another script to run your application then run your script

Step 2:

Set up your route.

  • Add auth.js file in your route folder then add these lines of code to it
const express = require('express');
 const router = express.Router();
 const router = express.Router();
 router.get('/login', function(req, res, next) {
 // Add your code or logic here
 });
  • Import the auth route to the app file.
 const authRouter = require('./routes/auth');
 app.use('/', authRouter);
 app.use('/', authRouter);

Step 3:

Set up Passport and it’s dependencies

  • Install passport and the passport-google-oidc strategy as dependencies
$ npm install passport
$ npm install passport-google-oidc
$ npm install passport-google-oidc
  • Import passport and googleStrategy in auth route also require your db here.
const passport = require('passport');
const GoogleStrategy = require('passport-google-oidc');
const db = require('../db');

Note: Add a route that will redirect the user when they click "Sign in with Google" router.get('/login/federated/google',passport.authenticate('google'));

Step 4:

Register your App with Google so that it can make use of Google's APIs.

  • Google Cloud Platform console.
  • From the projects list, select a project or create a new one.

1.jpg

2.jpg

  • Configure the OAuth consent screen.

3.jpg

  • Select External and click on create button to make your application available to any user with a Google account. You can complete the app registration process by entering the app name, support email, and developer contact information.

4.jpg

  • Add Scope to access user data that must be stored in your db like profile, email etc.

5.jpg

  • After Submitting all the details make sure to publish your app.

6.jpg

  • Create Credentials, then select OAuth client ID.

7.jpg

  • Select Web application as Application type. Click Add URI under Authorized Redirect URIs. Enter http://<Your Port>/oauth2/redirect/google. Click Create to create the OAuth client. The following screen will display your client ID and secret.

8.jpg

Step 5:

Create an env file and add your client ID and secret

 GOOGLE_CLIENT_ID=__INSERT_CLIENT_ID_HERE__
 GOOGLE_CLIENT_SECRET=__INSERT_CLIENT_SECRET_HERE__

Step 6:

Add the following code in your auth route.

passport.use(new GoogleStrategy({
 clientID: process.env['GOOGLE_CLIENT_ID'],
 clientSecret: process.env['GOOGLE_CLIENT_SECRET'],
 callbackURL: '/oauth2/redirect/google',
 scope: [ 'profile' ]
 }, function verify(issuer, profile, CB) 
 // Add your database operation here Like inserting user data in DB
 }));

Step 7:

Maintain State for security

  • Passport validates state automatically, but this requires the app to have session support.
 $ npm install express-session
 $ npm install connect-sqlite3
  • Add these lines to your app file.
 const session = require('express-session');
 const SQLiteStore = require('connect-sqlite3')(session);
 app.use(session({
 secret: 'keyboard cat',
 resave: false,
 saveUninitialized: false,
 store: new SQLiteStore({ db: 'your db name', dir: './var/db' })
 })); 

Note: Here sqlite database is used if you want to use another DB then add that DB instance.

Step 8:

Redirect Back to the App.

  • Add a new route that authenticates the user when Google redirects them back to the app. Add the following code in auth route.
 router.get('/oauth2/redirect/google', passport.authenticate('google', {
 successRedirect: '/',
 failureRedirect: '/login'
 }));

Step 9:

Establish Session

  • Import passport to app file and add passport authenticate method using sessions.
 const passport = require('passport'); 
 app.use(passport.authenticate('session'));
  • Configure Passport to persist user information in the login session. add the following code in auth route.
 passport.serializeUser(function(user, cb) {
 process.nextTick(function() {
 cb(null, { id: user.id, username: user.username, name: user.name });
 });
 });
 passport.deserializeUser(function(user, cb) {
 process.nextTick(function() {
 return cb(null, user);
 });
 });

Note: Serialize user method is used to store user information in sessions. it is called when a user logs in and deserialize user method is used to retrieve the user information from the sessions. It is called every time a request is made to the server and attaches user information to the request object.

Step 10:

Log Out

  • Add sign-out feature which will terminate the session. add the following in auth route
 router.post('/logout', function(req, res, next) {
 req.logout(function(err) {
 if (err) { return next(err); }
 //Add your entry point route here 
 });
 });

Conclusion

In conclusion, integrating Google Sign-In functionality via Passport.js provides a seamless and secure authentication process for users on your application. By leveraging Passport.js's straightforward configuration and the robust authentication capabilities offered by Google's OAuth service, developers can ensure a user-friendly experience while maintaining stringent security measures.

With the step-by-step guide detailed in this blog, you're now equipped to efficiently implement Google Sign-In using Passport.js. This approach not only streamlines the login process for your users but also grants access to a wealth of Google's services and user information, enriching the functionality of your application.

Share:
0
+0