Using Google's OAuth, Passport.js , and Express for Authorization - Part 1

mlittle17

Mac Little

Posted on July 13, 2020

Using Google's OAuth, Passport.js , and Express for Authorization - Part 1

When we build applications, we always keep the user in mind: "the user should be able to do this" or "is this easy for the user", but who exactly is this user anyway?

Well, depending on the application, it may not matter.

For example, if our application just renders a random SAT word to the screen every refresh, the user isn't super important. But what if they wanted to save their favorite words for studying later?

In this scenario, remembering individual users, allowing them to save and then access information at a later date becomes pretty critical. And sure, we could just create a login page and let the user create a profile, but how can we confirm they are who they say they are? And do we really want to be in charge of storing a user's password?

That's where third-party authentication from popular services like Google come in. In modern web applications, there are a variety of ways we can authenticate a user (email or text confirmation, for example), but for this series we're going to focus on two things:

  1. Using the Google OAuth API for authentication in your Node.js project, with Express as your middleware.

  2. Utilizing Passport.js to use that data you get back from Google to supercharge your applications with authentication you can trust.

Today, we'll focus on the first part: making an API call to Google to get some user information that we ca use in Part 2 to create a new profile for our application. This will be particularly helpful if you're not super familiar with the Google's Developer Console.

This tutorial also assumes you have a pretty basic understanding of Node.js and Express middleware.

1. Enable External under OAuth Consent Screen

The very first step we need to take is configuring how to we want our app to be made available. If we select Internal, it will only be available to users within our organization (i.e. a company or school's Google account), so we want to select External.

Alt Text

2. Go to the Google Developer's Console and enable your OAuth 2.0 Credentials

Next, let's get our credentials.

Google provides a wealth of APIs that you can use, whether it be for Maps or YouTube. In fact, they have so many APIs that it can be quite overwhelming.

The good news is that we don't even need to look into their API list for this project.

Speaking of which, make sure are inside a Project folder. If you don't have one, just navigate to the top left of the nav bar and click the dropdown and click New Project.

Next, click Credentials in the left nav bar, once you're in the credentials area, click Create Credentials, then OAuth client ID.

Alt Text

Select "Web Application" for Application type and then name your Web client. We'll ignore "Authorized JavaScript origins" and "Authorized redirect URIs" for now, but we'll definitely be coming back to those.

Once you hit Create, your Client ID and Client Secret will be generated. With these two keys, you'll be able to first send a user to Google to login. Since you've consented with your login, they'll then return data like a user's email or profile image back to you in order for you to build a profile on your site.

3. Set up your coding environment

Even if you've already set up a boilerplate with something like Create React App, we still need to install a few dependencies to make everything flow together.

// will install express for our middleware
npm i express

// will install passport that interacts with Google
npm i passport-google

Typically, it's best practice to leave your app.js file (the file that runs your server) alone. Meaning, if you want to add any routes or methods, put them in another file. However, to keep everything in front of us for now and make it a little easier to follow along, I'm going to share what our app.js file should look like thus far:

// bringing express into our project
const express = require('express');

// bringing passport into our project
const passport = require('passport');

// bringing a Google "plugin" or Strategy that interacts with Passport
const GoogleStrategy = require('passport-google');

// initializing our app by invoking express
const app = express();

// assigning the port to 8000
const port = 8000;

// calling the listen method on app with a callback that will execute if the server is running and tell us what port
app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

While it doesn't look like much, we now have a file set up that will not only allow us to access Google's sign-in page, but also take that data do something like store it in our own database, giving our users the ability to have their own unique profile.

Best of all, we have to do very little data collection ourselves, whether that be a login form or password generation/storage.

Next Week

Next week, we'll talk about how to combine Google and Passport's powers. In the mean time, here's a little code snippet that gives you a slight idea on how they work together. The "callback" is a placeholder for a slightly more complicated function, but just know it is responsible for doing something with our Google data once we get it back.

Given some of the variables we've listed in our app.js and some of the things we set up in the developer console, how is this snippet working?

passport.use(new GoogleStrategy({
  // options for the google strategy
  callbackURL: '/auth/google/redirect',
  clientID: process.env.GOOGLECLIENTID,
  clientSecret: process.env.GOOGLECLIENTSECRET,
}, callback);
💖 💪 🙅 🚩
mlittle17
Mac Little

Posted on July 13, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related