Open Authorization, also known as OAuth, is a protocol used to authorize a user on your website using some third-party service like Google, Github, Facebook, etc. The third-party service shares some data (name, email, profile picture, etc.) with your website and then authorizes the user on its behalf without managing the passwords and usernames for your website, and saving the users a lot of extra trouble.

How OAuth Works

When a user clicks on “Login with Google”, it takes the user to the Google OAuth consent page. When the user agrees to the consent and authenticates his identity on Google, Google will contact your website as a third party service and authorize the user on its behalf and share some data with your website. In this way, the user can be authorized without managing the credentials for your website separately.

Implementing Google OAuth using Node.js

Almost all the programming languages provide different libraries to implement google oauth to authorize users. Node.js provides ‘passport’ and ‘passport-google-oauth20’ libraries to implement google oauth. In this article, we will implement an oauth protocol to authorize users to use node.js.

Create a Project on Google

The first step to implement Google OAuth is to create a project on the google developer console for your website. This project is used to get the API keys used to make requests to Google for open authentication. Goto the following link and create your project.

https://console.developers.google.com

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/02/echo/image7-1.png" data-lazy- height="528" src="data:image/svg xml,” width=”585″>

Configuring Google Project

After you create the project, go into the project and select “OAuth consent screen” from the left side menu.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/02/echo/image9-1.png" data-lazy- height="312" src="data:image/svg xml,” width=”256″>

Click on the ‘create’ button and provide all the details of your project. Click “Save and Continue” to move on.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/02/echo/image8-1.png" data-lazy- height="496" src="data:image/svg xml,” width=”683″>

Now provide the scope of your project. Scopes are the types of permissions to access the user’s data from a google account. You need to set up the permissions to get specific user data from your google account. Click “Save and Continue.”

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/02/echo/image11.png" data-lazy- height="421" src="data:image/svg xml,” width=”701″>

Now add the test users to the project if you want. Test users are the only allowed users who can access your web application in Testing mode. For now, we will not enter any test user and click “Save and Continue” to move on to the summary page of the project.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/02/echo/image10-1.png" data-lazy- height="332" src="data:image/svg xml,” width=”667″>

Review your project on the summary page and save the configuration. Now we will generate credentials for our project. Select the ‘Credentials’ tab on the left side menu and click on the ‘Create credentials’ button on top to generate OAuth 2.0 Client IDs.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/02/echo/image2-1.png" data-lazy- height="398" src="data:image/svg xml,” width=”906″>

From the dropdown menu, select ‘OAuth client ID’ and specify the type of application as ‘Web application’ and your application’s name.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/02/echo/image1-1.png" data-lazy- height="414" src="data:image/svg xml,” width=”671″>

On the same page, we have to provide two URIs, the ‘Authorized Javascript Origins’ and the ‘Authorized redirect URIs’. The ‘Authorized javascript origins’ is the HTTP origin of your web application, and it can not have any path. The ‘Authorized redirect URIs’ is the exact URI with a path where the user will be redirected after google authentication.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/02/echo/image4-1.png" data-lazy- height="497" src="data:image/svg xml,” width=”352″>

After entering all the required entries, click on ‘create’ to create OAuth credentials.

Initiating Node.js Project

So far, we have created a google project to authorize users for our application using google. Now we are going to initiate the node.js project to implement oauth. Create a directory named ‘auth’ and initiate the express project.

Installing Required npm Packages

To implement Google OAuth using node.js, we need to install some npm packages. We will use ‘passport’, ‘express’, ‘path’, and ‘passport-google-oauth20’. Install these packages using npm.

Writing Node.js Code

First of all, we will write two simple html web pages, the one with a button, and authorize the user when clicked on the button. The second page will be authorized, and the user will be redirected to the authorized page after authorization. Create a file ‘public/index.html’.

Now create a file ‘public/success.html’ with the following content.

After creating web pages, now we will write code to authorize the users to use google oauth. Create a file ‘index.js’.

// importing required packages

const express = require(‘express’);

const passport = require(‘passport’);

const path = require(‘path’);

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

const app = express();

// defining parameters

// client id is the parameter that we will get from the google developer console

CLIENT_ID=”xxxxxxx”;

// client secret will also be taken from the google developer console

CLIENT_SECRET=”xxxxx”;

// user will be redirected to the CALLBACK_URL after authorization

CALLBACK_URL=”http://localhost:8000/authorized”;

// port number must be the same as defined in the developer console

PORT=8000;

// configuring passport middleware

app.use(passport.initialize());

app.use(passport.session());

passport.serializeUser( function(id, done) {

  done(null, id);

});

passport.deserializeUser( function(id, done) {

  done(null, id);

});

// following middleware will run whenever passport. Authenticate method is called and returns different parameters defined in the scope.

passport.use(new GoogleStrategy({

  clientID: CLIENT_ID,

  clientSecret: CLIENT_SECRET,

  callbackURL: CALLBACK_URL

  },

  async function(accessToken, refreshToken, profile, email, cb) {

    return cb(null, email.id);

  }

));

// serving home page for the application

app.get(/’, (req, res) =>

{

  res.sendFile(path.join(__dirname ‘/public/index.html’));

});

// serving success page for the application

app.get(/success’, (req, res) =>

{

  res.sendFile(path.join(__dirname ‘/public/success.html’));

});

// user will be redirected to the google auth page whenever hits the ‘/google/auth’ route.

app.get(/google/auth’,

  passport.authenticate(‘google’, {scope: [‘profile’, ‘email’]})

);

// authentication failure redirection is defined in the following route

app.get(/authorized’,

  passport.authenticate(‘google’, {failureRedirect: ‘/}),

  (req, res) =>

  {

    res.redirect(/success’);

  }

);

// running server

app.listen(PORT, () =>

{

  console.log(“Server is running on Port ” PORT)

})

Testing Google OAuth

Now our application is ready, and we can test whether it authorizes the users using google oauth. Go to the root directory and run the application.

Now enter the url of your application into the browser.

http://localhost:8000

It shows the home page with an anchor tag.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/02/echo/image3-1.png" data-lazy- height="203" src="data:image/svg xml,” width=”461″>

When we click on the ‘Authorize Here’, it will redirect to the google oauth page.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/02/echo/image6-1.png" data-lazy- height="535" src="data:image/svg xml,” width=”468″>

Your application name ‘Test’ is displayed on the Google authentication page. When you authorize your account, it will take you to the authorized page.

<img alt="" data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2021/02/echo/image5-1.png" data-lazy- height="216" src="data:image/svg xml,” width=”395″>

Conclusion

Managing usernames and passwords for different web applications is not a happy task for users. Many users leave your web application without registering their account just because they do not want to manage credentials. The authorization process on your web application or website can be simplified by using third-party services like Google, Facebook, etc. These services authorize users on their behalf, and the user does not need to manage credentials separately. In this article, we have implemented the google oauth protocol to authorize users to use Node.js.

About the author

<img alt="Usama Azad" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/02/echo/usama-1-150×150.jpg601cb2b44c5d6.jpg" height="112" src="data:image/svg xml,” width=”112″>

Usama Azad

A security enthusiast who loves Terminal and Open Source. My area of expertise is Python, Linux (Debian), Bash, Penetration testing, and Firewalls. I’m born and raised in Wazirabad, Pakistan and currently doing Undergraduation from National University of Science and Technology (NUST). On Twitter i go by @UsamaAzad14