Implementing Google Authentication with Express, Passport, and Node.js

Implementing Google Authentication with Express, Passport, and Node.js

·

3 min read

Google authentication is a common way for users to log in to web applications. In this guide, we will walk through the steps of setting up Google authentication using the Passport.js library in a Node.js application with Express.

Express is a fast and flexible web application framework for Node.js that provides a range of features to help you create web and mobile applications. Passport is an authentication middleware for Node.js that supports authentication using various methods, including Google OAuth.

Prerequisites

Before we begin, you should have the following:

  • A basic understanding of Node.js and Express.

  • A Google account and access to the Google Cloud Console.

  • Node.js and npm are installed on your machine.

Setting Up the Project

First, create a new Node.js project and install the necessary dependencies:

$ mkdir google-auth-guide

$ cd google-auth-guide

$ npm init -y

$ npm i express passport passport-google-oauth20

Next, create an app.js file and set up a basic Express server:

const express = require('express'); const app = express();

app.get('/', (req, res) => { res.send('Hello World!'); });

app.listen(3000, () => { console.log('Server listening on port 3000'); });

Run the server with node app.js, and you should see the message "Server listening on port 3000" in the console. If you visit http://localhost:3000 in your browser, you should see the message "Hello World!"

Setting Up Google OAuth

Now, we will set up Google OAuth so that users can log in to our application using their Google account.

First, go to the Google Cloud Console and create a new project. Click "Enable APIs and Services" and search for the "Google+ API". Enable this API for your project.

Next, click on the "Credentials" tab and click "Create credentials" > "OAuth client ID". Select "Web application" as the application type, and enter http://localhost:3000 as the authorized JavaScript origin and authorized redirect URI. Click "Create".

Google will provide you with a client ID and client secret. Save these somewhere safe, as you will need them later.

Now, let's configure Passport to use the Google strategy. In your app.js file, add the following code:

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

passport.use(
  new GoogleStrategy(
    {
      clientID: 'YOUR_CLIENT_ID',
      clientSecret: 'YOUR_CLIENT_SECRET',
      callbackURL: 'http://localhost:3000/auth/google/callback',
    },
    (accessToken, refreshToken, profile, cb) => {
      // Save the user to your database here
      return cb(null, profile);
    }
  )
);

Replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with the client ID and client secret that Google provided you.

Adding Google Login and Logout Routes (Continued)

To make it easy for users to log in and out, you should add a login and logout link to your application.

First, check if the user is authenticated in your application's layout template (e.g. layout.pug):

- if (user)
  a(href="/logout") Logout
- else
  a(href="/auth/google") Login with Google

Then, pass the user object to the template when rendering it. In your routes, add the following code:

app.get('/', (req, res) => {
  res.render('index', { user: req.user });
});

Now, when the user is logged in, they will see a "Logout" link, and when they are logged out, they will see a "Login with Google" link.

Wrapping it up...

We have walked through the steps of setting up Google authentication in a Node.js application with Express and Passport. We have also covered how to protect routes and add a login and logout link to your application.

I hope you have found this tutorial helpful! Let me know if you have any questions or comments.