As a user, It’s very often we would have used Google accounts to login to a web application. The process would have been so simple. But in reality, a lot of works are done behind that single click. This blog will explain to you how to implement Google authentication with Node and Express JS. To implement this, we will be using a third-party library called Passport JS. Passport JS is authentication middleware for Node and Express JS. Passport JS can be used with any Express JS applications. Passport JS provides 500 + strategies.
To begin with, let’s create an Express Application. The below commands create a new folder and initialize Node.js.
mkdir passport_sta
cd passport_sta/
npm init -y
touch index.js
After initializing, install all the required packages. Here I am installing the following packages.
express — Light-weighted framework for webservers and APIs.
cookie session — To store Sessions.
passport — Authentication Middleware for Node and Express JS
passport google oauth20 — Passport Authentication strategy that helps you to login with your Google Account.
npm install express cookie-session passport passport-google-oauth20 --save
The above command installs all the packages. After installing, copy the below code to your index.js
file.
index.js
const express = require('express')
const app = express()app.get('/',(req,res)=>{
res.send('Hello world')
})app.listen(8000,()=>{
console.log('Serve is up and running at the port 8000')
})
Now start the server using node index.js
. Then navigate to http://localhost:8000/. You should see Hello world getting displayed in the browser.
#node #express #passport #security #programming