Google OAuth2.0 Authentication — using Node JS and PassportJS

Pulsara Sandeepa
Nerd For Tech
Published in
6 min readMar 16, 2021
Photo by Kai Wenzel on Unsplash

Google Sign-In, simplifying your integration with Google APIs. A user has the option of revoking access at any time to an application. OAuth was developed as an authentication protocol, so the result of any OAuth flow is that the app obtains an access token. Something about the user’s account can be got or modified. On its own, the permission token says nothing about but who the user is.

In this article, I will discuss how to complete an essential integration with Google Sign-In with Node JS and Passport JS.

Initializing a NodeJS Project

To begin with, let’s create an Express Application. Create a new folder named as your choice and initialize Node.js.

You can give the below command on the command prompt inside the project directory or your favorite IDE terminal. Then it will create a package.json file and fill in the necessary fields.

npm init
Figure01 — you can fill the necessary details about your project

Edit “scripts” of the package.json file as below, then create a server.js file inside the folder created.

"scripts": {
"test": "node server.js",
"start": "nodemon server.js"
}

Install all the necessary packages after initializing the node project. I am downloading the following packages for this purpose.

· express — Light-weighted application for Server and API system.

· nodemon — this package makes it easy of running the server (we don’t have to re-run the server manually after we make a change to our app)

· cookie session — Storing Sessions.

· passport — Authentication Middleware for Node and Express JS

· passport google oauth20 — Strategy for passport authentication to help you log in with your Google Account.

npm install express nodemon cookie-session passport passport-google-oauth20 — save

The above command installs all the packages. After installing, copy the below code to your server.js file to test our application created.

const express = require(‘express’)
const app = express()app.get(‘/’,(req,res)=>{
res.send(‘Hello world’)
})app.listen(5000,()=>{
console.log(‘Serve is up and running at the port 5000’)
})

Start the server using:

npm start

Navigate then to http://localhost:5000/. You can see the “Hello World” is displayed in your browser.

Now we can start our Authentication application. Let’s start😎

What is Passport JS ?

Passport JS is a middleware for express.js. (I will explain about middlewares below). Passport JS supports various login types, Token, Local (username, password), OAuth, OAuth2, etc. We can combine these to authenticate by signing in with Google, FB, or whatever service with a very minimal amount of code.

We can also use this to connect external auth services to choose to login with one of the selected Strategies, e.g., Google, Twitter. It’s much quicker to use Passport JS for authentication than to build one yourself from scratch. So, this is why we use Passport JS. You don’t need Passport JS for this purpose, and it just makes developing quicker.

A middleware may perform the following duties
• It can execute any code.
• It will make adjustments to the request and the objects of the response.
• It will terminate the cycle of request-response.
• In the stack, it will call the next middleware function.

What is a middleware?

Between an initial request and the final desired route, middleware appears in the middle. Middleware features are often invoked in the stack in the order that they are added.
Middleware is widely used to perform URL-encoded tasks or JSON request body parsing, cookie parsing for easy cookie handling.

Create OAuth client ID

First, you’ll need to create a Google Cloud project.

You’ll need to configure your OAuth consent screen. Choose external. Google will then ask for the app’s name and logo, plus some developer contact details.

It will then ask what scopes we want to request — special permissions to read data and take action on behalf of our users. For our example, we don’t need any of these.

Lastly, we’ll add our own Google account as a test user.

Figure02 — credentials page in the GCP

Now we can go to the Credentials screen and create a new OAuth client ID (click the +Create Credentials on top of the credentials screen) for a web application. Give a name for that as you Prefer.

Google will ask us for authorized origins and a redirect URI. We care about local testing, for now, so we can use this below value for both:

http://localhost:5000/google/callback

After creating, you can see a screen showing client ID and client secret as below.

Figure03 — We can see the client ID in this screen

Then Google will give us a client ID and a client secret. For this case, we’ll need the client ID.

Configure Passport JS

Now, let’s start integrating our project with Google Authentication. I am making a new file called passport.js to do so, which stores the credentials that we have.

Here we use GoogleStrategy as we want the authentication with google. You can learn more about GoogleStrategy from passport-google-oauth2 (passportjs.org)

clientID:"use the client ID given by Google", 
clientSecret:"use the client secret given by Google", callbackURL:"URL that the user gets redirected after login into google."

passport.js file should include the following code:

Once the Authentication successful, the user details get saved in the cookie.

Tests on routes

· The route /google redirects the client to Google Login Page.

· The route /google/callback will act as a callback URL which will be called if Google Authentication is Successful.

· The route /success will be called when Google Authentication is successful.

· The route /failed will be called if any failure has occurred during Google Authentication.

Now navigate to http://localhost:5000/google/. You will be redirected to Google’s Login page. On logging in to your Google Account, you will be redirected back to your webpage, and you will see your email address getting displayed on your webpage.

Protecting the route and adding a logout view

You can see an error when you open the route http://localhost:5000/ without logging in that the email address is not located. I am creating a middleware to eliminate the error that checks whether the user is logging in within server.js.

const isLoggedIn = (req, res, next) => {
if (req.user) {
next();
} else {
res.sendStatus(401);
}
}

Once done, pass the middleware to the route /success. So the users who are logged in can only access the /success route.

Let’s create a logout feature now. You will log out of your Google account just by calling req.logout() feature.

server.js file should include the following code:

app.get(“/logout”, (req, res) => {
req.session = null;
req.logout();
res.redirect(‘/’);
})

Just navigate to http://localhost:5000/logout. You will be logged out.

Finally server.js looks like this:

Conclusion

In this article, we learned how to set up google OAuth2.0 with NodeJS and PassportJS. As above, we can also set up the Facebook, Twitter GitHub authentications using other various strategies in PassportJS. I think this article will help you well and let’s meet with another interesting article in the near future.😊

References

Passport.js

Google Cloud Platform

--

--

Pulsara Sandeepa
Nerd For Tech

Tech Enthusiast | Software Engineer | 3x Salesforce Certified