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.
Set up Your node js project.
$ sudo apt-get install nodejs
$ sudo apt-get install npm
$ npm install express
$ npm install -g express-generator
$ npx express-generator
$ npm run start
Note: If you add another script to run your application then run your script
Set up your route.
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
});
const authRouter = require('./routes/auth');
app.use('/', authRouter);
app.use('/', authRouter);
Set up Passport and it’s dependencies
$ npm install passport
$ npm install passport-google-oidc
$ npm install passport-google-oidc
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.
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__
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
}));
Maintain State for security
$ npm install express-session
$ npm install connect-sqlite3
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.
Redirect Back to the App.
router.get('/oauth2/redirect/google', passport.authenticate('google', {
successRedirect: '/',
failureRedirect: '/login'
}));
Establish Session
const passport = require('passport');
app.use(passport.authenticate('session'));
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.
Log Out
router.post('/logout', function(req, res, next) {
req.logout(function(err) {
if (err) { return next(err); }
//Add your entry point route here
});
});
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.