All Blog Articles

Payload CMS - Google Auth in the Admin Panel

josh
joshuaApril 30, 2025
Learn how to secure your Payload CMS admin panel with Google OAuth authentication in this step-by-step tutorial.

Hey everyone! In today's blog post, I'm thrilled to guide you through the process of implementing Google authentication for your Payload backend. This is the first installment of our series on various authentication methods, with a special focus on OAuth 2 authentication. Whether you're an admin, a developer, or just curious about Payload, this post is packed with valuable insights for you. So let’s get started!


This article provides the complete written step-by-step tutorial for implementing Google authentication in your Payload CMS admin panel. For visual learners or those who prefer following along with video instruction, check out our comprehensive video guide on YouTube at https://www.youtube.com/watch?v=tX2ZyWTndSY. The video covers the same content but offers additional context and real-time demonstrations of each step in the process.


Table of Contents


Overview of Google Authentication for Payload Backend

Implementing Google authentication can streamline your user management process, offering a smooth and secure way for users to log into your applications. In this guide, we will walk through the entire setup process, from creating Google credentials to modifying your Payload server configuration. By the end of this article, you’ll be able to implement Google Auth in your own Payload backend.


What You Will Learn

  • How to set up Google Client ID and Secret
  • Installing necessary packages
  • Modifying your server configuration
  • Setting up the Google Auth strategy
  • Implementing and testing the auth strategy
  • Extracting user data from the Google API
  • Modifying your user model


Preparing Google Client ID and Secret

The first step in implementing Google authentication is to create a Google Client ID and Secret. This can be done through the Google Cloud Console. Below are the steps to achieve this:

  1. Go to the Google Cloud Console.
  2. Create a new project or select an existing one.
  3. Navigate to "APIs & Services" > "Credentials."
  4. Click on "Create Credentials" and select "OAuth client ID."
  5. Configure the consent screen as required.
  6. For "Application type," select "Web application."
  7. Set the "Authorized redirect URIs" to your server's URL.

Don't forget to include localhost in your authorized JavaScript origins if you're developing locally. This is crucial; otherwise, the authentication process will fail. Make sure to save your Client ID and Client Secret for later use!


Installing Necessary Packages

Next, you need to install some JavaScript packages that will help manage the authentication process. You can do this by running the following command in your terminal:

npm install express-session jsonwebtoken connect-mongo passport passport-google-oauth20

These packages are essential for handling sessions, JSON web tokens, and implementing the OAuth2 strategy for Google authentication.


Modifying the Server Configuration

Now that you have installed the necessary packages, let's modify your server configuration. Open your server file (usually named server.ts or similar) and follow these steps:

Import Packages

First, import the packages you just installed, as well as the Google Auth strategy that we will create shortly:

import express from 'express';
import session from 'express-session';
import passport from 'passport';
import { OAuth2Strategy as GoogleStrategy } from 'passport-google-oauth20';


Set Up Routes

Next, you need to define two routes in your server configuration:

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

app.get('/auth/google/callback', passport.authenticate('google', {
    successRedirect: '/admin',
    failureRedirect: '/login'
}));

The first route initializes the authentication process, while the second route handles the callback from Google after authentication.


Session Management

To manage user sessions, configure express-session in your server file:

app.use(session({
    secret: 'your_secret_key',
    resave: false,
    saveUninitialized: true,
    store: new MongoStore({ mongooseConnection: mongoose.connection })
}));


Setting Up the Google Auth Strategy

Now let’s set up the Google Auth strategy. Create a new folder named auth and inside it, create a file named googleAuth.js. Here’s how to implement the Google OAuth strategy:

passport.use(new GoogleStrategy({
    clientID: 'YOUR_GOOGLE_CLIENT_ID',
    clientSecret: 'YOUR_GOOGLE_CLIENT_SECRET',
    callbackURL: '/auth/google/callback'
}, async (accessToken, refreshToken, profile, done) => {
    // Logic to find or create user in your database
}));

In this function, you will handle the logic for finding or creating a user in your database based on the profile information returned by Google.


Implementing and Testing the Auth Strategy

With the strategy in place, it’s time to test it. Make sure your application is running, and go to the URL that initializes the Google authentication process. You should see a prompt to log in with your Google account.

google-oauth-account-selection-screen.png

Once you select your account, you should be redirected back to your admin interface, where you can see the user’s information.


Extracting User Data from Google API

When the user logs in, Google returns a profile object containing user data. You can extract necessary fields like the user’s email and profile picture. Here’s how to do that:

passport.use(new GoogleStrategy({
    // ... previous setup
}, async (accessToken, refreshToken, profile, done) => {
    const user = await User.findOne({ googleId: profile.id });
    if (user) {
        done(null, user);
    } else {
        const newUser = await new User({
            googleId: profile.id,
            username: profile.displayName,
            thumbnail: profile._json.picture
        }).save();
        done(null, newUser);
    }
}));

In this code snippet, we check if the user already exists in our database. If not, we create a new user with the information retrieved from Google.


Modifying Your User Model

To accommodate the new fields, you’ll need to modify your user model. Add fields for the Google ID and any other information you want to store:

const userSchema = new mongoose.Schema({
    googleId: String,
    username: String,
    thumbnail: String,
    // Add any other fields you need
});

Now your user model can store the necessary information for users logging in with Google authentication.


Conclusion

Congratulations! You have successfully implemented Google authentication for your Payload backend. This feature not only simplifies the login process for users but also enhances security and user management.

If you followed all the steps outlined in this guide, you should now have a fully functional Google authentication system in your Payload application. If you have any questions or suggestions, feel free to leave a comment below. I always love hearing from you guys!


FAQs

What is OAuth 2.0?

OAuth 2.0 is an authorization framework that enables applications to obtain limited access to user accounts on an HTTP service, such as Google, Facebook, and others.

Why use Google Authentication?

Google Authentication provides a secure and standardized way for users to log in, reducing the need for them to remember multiple passwords and improving the overall user experience.

Can I customize the user data retrieved from Google?

Yes, you can request additional scopes to retrieve more user information, such as their Google Drive files or calendar events, depending on your application's requirements.

For additional resources and a step-by-step guide, check out this link: Payload CMS Google Auth Guide. Don't forget to smash that LIKE button and subscribe for more content!