Posted in

Implementing OAuth with Google Login: A Complete Guide

Implementing OAuth with Google Login: A Complete Guide

In today’s digital world, allowing users to sign in securely and seamlessly is critical for user experience and data security. One of the most popular authentication methods is OAuth 2.0, especially when combined with Google Login. By integrating Google’s authentication, users can log into your app using their existing Google accounts, eliminating the need to remember yet another password.

This blog will walk you through everything you need to know about implementing OAuth 2.0 with Google Login, from understanding the OAuth flow to writing code for both front-end and back-end applications.

What is OAuth 2.0?

OAuth 2.0 is an open standard for access delegation, commonly used to grant websites or applications access to user information on other websites without giving them passwords.

Key Concepts in OAuth:

  • Client: Your application.
  • Resource Owner: The user.
  • Authorization Server: Google.
  • Access Token: A token that gives your app permission to access the user’s data.
  • Redirect URI: The endpoint in your app where Google will send the user after authentication.

How Google OAuth Login Works

  1. User clicks “Login with Google”.
  2. Your app redirects them to Google’s OAuth 2.0 server.
  3. User grants permission to your app.
  4. Google sends an authorization code to your app.
  5. Your app exchanges the code for an access token.
  6. You use the token to access the user’s profile information.

Setting Up Google API Console

Before coding, you need to register your app with Google:

  1. Go to Google Cloud Console.
  2. Create a new project.
  3. Navigate to APIs & Services > OAuth consent screen.
  4. Set the app name, email, and scopes (like email, profile).
  5. Go to Credentials > Create Credentials > OAuth 2.0 Client IDs.
  6. Choose “Web application” and set your redirect URI (e.g., http://localhost:3000/auth/google/callback).

Save the Client ID and Client Secret.

Implementing Google OAuth in a Node.js App

Let’s build a simple Express-based app that supports Google Login.

1. Install Required Packages

npm install express passport passport-google-oauth20 cookie-session dotenv

2. Project Structure

/google-auth-demo

├── index.js
├── auth.js
├── .env

3. Configure .env

GOOGLE_CLIENT_ID=your_client_id_here
GOOGLE_CLIENT_SECRET=your_client_secret_here
SESSION_SECRET=some_random_string

4. auth.js – Google OAuth Strategy

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

passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "/auth/google/callback"
},
(accessToken, refreshToken, profile, done) => {
return done(null, profile);
}));

passport.serializeUser((user, done) => {
done(null, user);
});

passport.deserializeUser((obj, done) => {
done(null, obj);
});

5. index.js – Main App

const express = require('express');
const passport = require('passport');
const session = require('cookie-session');
require('./auth');

const app = express();

app.use(session({
name: 'session',
keys: [process.env.SESSION_SECRET]
}));

app.use(passport.initialize());
app.use(passport.session());

app.get('/', (req, res) => {
res.send(`<h2>Home</h2><a href="/auth/google">Login with Google</a>`);
});

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

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

app.get('/dashboard', (req, res) => {
if (!req.user) return res.redirect('/');
res.send(`<h1>Hello ${req.user.displayName}</h1><a href="/logout">Logout</a>`);
});

app.get('/logout', (req, res) => {
req.logout(() => {
res.redirect('/');
});
});

const PORT = 3000;
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));

Front-End Considerations

You can also integrate Google Login on the front-end using Google’s JavaScript client:

<script src="https://accounts.google.com/gsi/client" async defer></script>
<div id="g_id_onload"
data-client_id="YOUR_CLIENT_ID"
data-login_uri="http://localhost:3000/auth/google/callback"
data-auto_prompt="false">
</div>
<div class="g_id_signin" data-type="standard"></div>

Use this only if you want a direct Google One Tap or popup-based login approach.

Testing the Flow

  • Start your Node app: node index.js
  • Go to http://localhost:3000/
  • Click “Login with Google”
  • Approve the consent screen
  • You’ll be redirected to /dashboard with user info

Security Best Practices

  • Use HTTPS in production.
  • Validate redirect URIs and tokens.
  • Set appropriate scopes (least privilege principle).
  • Store session data securely.
  • Regularly rotate secrets and tokens.

Real-World Use Cases

  • E-commerce sites: Quick sign-up/login for faster purchases.
  • SaaS dashboards: Manage user identity without storing passwords.
  • Internal tools: Allow only company employees via Google Workspace domain restriction.

Final Thoughts

Implementing OAuth with Google Login is a smart move for most web apps. It simplifies user registration and enhances security. By using Google’s robust identity infrastructure, you reduce the burden of authentication while offering users a convenient way to access your services.

Whether you’re building a personal project or a production-ready enterprise app, OAuth with Google Login offers a modern, secure, and user-friendly authentication solution.