How To Implement Google OAuth 2 with Passport in Express Application

Upscalix
5 min readMar 6, 2024

--

OAuth (Open Authorization) protocol is an open standard commonly used for users to provide information to a website or application from other websites or applications without giving them their credentials.

In this discussion, we will implement Google OAuth in our application with Passport JS. This flexible and modular authentication middleware will simplify the OAuth implementation process in our node-based application.

1. Create a Google Client ID and Secret

The first step to add Google OAuth to our application is to create a Google OAuth client ID through Google Console: https://developers.google.com/identity/protocols/oauth2. You can go to this link to read an overview of what Google OAuth 2.0 is and also go to the Google API console through the provided step that Google is giving.

Once in the console, go to the credential tab, click the “CREATE CREDENTIAL” button, and choose the OAuth client ID.

On the form, we will choose web application as our application type and then fill out the application name and add redirect URI as the path that Google will redirect after they authenticate the user.

After creation, Google will show us the client ID and client secret we will use in our application. Please. We can check the client ID and secret later by clicking on your application name in a credential tab in the Google Console.

After we create the client ID and secret, we need to add information on the tab OAuth consent screen, like the application name, support email, logo, and application domain, which will show up in the consent screen when the user logs in.

2. Implement Google OAuth 2.0 with a Passport in the Express App

Now that we have the Google client ID and secret, we can continue implementing it with a passport in our application. We can check passport documentation on Google OAuth 2.0 strategy here: https://www.passportjs.org/packages/passport-google-oauth20/

To implement Google Oauth with a passport in our application, we need to add a couple of dependencies: express-session, passport, and Google Oauth passport. To add these dependencies, we can use npm I express-session passport passport-google-oauth20.

First, we need to set the passport to our application and configure passport strategies for Google OAuth; in this example, I will add a passport.js file on util to add our configuration for the passport.

const passport = require('passport'); 
const GoogleStrategy = require('passport-google-oauth20').Strategy;

Then we can add our passport strategy for Google OAuth, user serialize and deserialize.

const passport = require('passport'); 
const GoogleStrategy = require('passport-google-oauth20').Strategy;

const googleClientId = 'your google client id'
const googleClientSecret = 'your google client secret'

passport.use(
new GoogleStrategy(
{
clientID: googleClientId,
clientSecret: googleClientSecret,
callbackURL: `http://localhost:3001/auth/google/redirect`,
},

function (accessToken, refreshToken, profile, done) {
// User find or create to db
return done(null, profile);
}
)
);

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

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

The callback URI in the Google OAuth strategy is the same as the one we add in the Google Console for redirecting URI and note that Google Client ID and secret are not to be hardcoded in the application and should be added in environment variables.

We can also add code to search or create a user into a database to save the login information of our user, or we can add the code as middleware later in the authentication route.

Now that we have set up our passport configuration and strategy, we need to initialise the passport on the index root of our application. Note that the session secret should also be placed on environment variables and not hardcoded in the application.

const express = require('express') 

const session = require('express-session')
const passport = require('passport')
require('./utils/passport')

const app = express()
app.use(
session({
resave: false,
saveUninitialized: false,
secret: 'sesion secret',
})
);

app.use(passport.initialize())
app.use(passport.session());

// routes
app.get('/', (req, res) => {
res.send('<a href="auth/google">Authenticate with google</a>')
})

app.listen(3001, () => console.log('listening on 3001'))

After we set the passport configuration, we need to add routes for Google Authentication and redirect after authentication.

const express = require('express') 
const session = require('express-session')
const passport = require('passport')

require('./utils/passport')

const app = express()
app.use(
session({
resave: false,
saveUninitialized: false,
secret: 'sesion secret',
})
);

app.use(passport.initialize())
app.use(passport.session());

// routes
app.get('/', (req, res) => {
res.send('<a href="auth/google">Authenticate with google</a>')
})

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

app.get(
'/auth/google/redirect',
passport.authenticate('google', {
failureRedirect: '/'
}),
// middleware for user add or create
function(req, res) {
res.send('success')
}
);

app.listen(3001, () => console.log('listening on 3001'))

You can make a more sophisticated login page on the client side, but for this example, we will send a link to our Google login URI “/auth/google”.

In the first URI, we need to add scope on the authentication to let Google know what user info we want Google to send us back, and on the redirect URI, we can add middleware after authentication if we add other functionalities in our authentication.

Now that the implementation is done, we can go to the login page to test if Google OAuth is working on our application; in this example, we need to go to http://localhost:3001/.

When we click authenticate, we should be directed to the Google consent screen to choose which user to log in to.

After completing Google authentication, the user will be redirected to the URI we provided before.

Passport also provides other strategies for other OAuth and another type of authentication like jwt that you can check at https://www.passportjs.org/packages/.

This article is written by Hamzah, Upscalix’s Fullstack Developer.

--

--