Welcome folks today in this blog post we will be building google login
authentication using the passport
library in node.js and express
in browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to create the node.js
project using the below command as shown below
npm init -y
After that you need to install the below libraries using the npm
command as shown below
npm i express
npm i passport
`
npm i passport-google-oauth2
npm i cookie-session
After that you need to make an index.js
file and copy paste the following code
index.js
1 2 3 4 5 6 7 8 9 10 |
const express = require('express'); const app = express(); app.get('/' , (req , res) => { res.send("<h1>Google Login Using Pasport</h1>"); }); app.listen(4000 , () => { console.log("Server running on port 4000"); }); |
And now you need to make the Passport.js
file which will store the google login
authentication as shown below
Passport.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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); } )); |
As you can see we are including the passport
and passport-google-oauth2
modules at the top and then we are using the google strategy
and here you need to replace the clientid
and clientsecret
Now we need to include this above Passport.js
file inside the index.js
file as shown below
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
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"); }); |