Add Google Sign-In to Your App

Enable "Sign in with Google" for your application's users through OAuth42's social authentication feature.

What You'll Build

In this tutorial, you'll configure Google as a social identity provider for your OAuth42 application. Your users will be able to click "Sign in with Google" and authenticate using their Google account.

How it works:

  • User clicks "Sign in with Google" in your app
  • OAuth42 redirects to Google for authentication
  • Google authenticates the user and returns to OAuth42
  • OAuth42 creates/links the user account and issues tokens to your app
  • Your app receives the tokens and the user is logged in

Prerequisites

  • An OAuth42 account with an existing application
  • A Google Cloud account (free tier works)
  • Your application already integrated with OAuth42 (see Getting Started with Hosted Auth)

Step 1: Create Google OAuth Credentials

  1. Go to the Google Cloud Console - Credentials
  2. Click Create CredentialsOAuth client ID
  3. If prompted, configure the OAuth consent screen first:
    • User Type: External (for public apps) or Internal (for organization-only)
    • App name: Your application name
    • User support email: Your email
    • Authorized domains: Add api.oauth42.com
    • Developer contact email: Your email
  4. Back on Create OAuth client ID:
    • Application type: Web application
    • Name: "OAuth42 Social Login" (or any name)
    • Authorized redirect URIs: Add your OAuth42 callback URL (see Step 2)
  5. Click Create and copy your Client ID and Client Secret

⚠️ Keep your Client Secret safe! Never expose it in frontend code or commit it to version control.

Step 2: Configure Google OAuth URLs

In the Google Cloud Console, you need to configure both the Authorized JavaScript Origins and Authorized Redirect URIs.

Authorized JavaScript Origins

This is the origin (protocol + domain) where OAuth42 is hosted:

Production:

https://api.oauth42.com

Local Development:

https://localhost:8443

Authorized Redirect URIs

This is where Google will redirect after authentication. OAuth42 handles this automatically:

Production:

https://api.oauth42.com/api/social-auth/callback

Local Development:

https://localhost:8443/api/social-auth/callback

💡 Tip: Add both production and local development URLs so you can test locally and in production.

Step 3: Configure Google in OAuth42 Portal

Now configure Google as a social provider in your OAuth42 application:

  1. Log in to the OAuth42 Portal
  2. Navigate to Applications and select your application
  3. Click the Social Providers tab
  4. Click Add Provider
  5. Select Google from the dropdown
  6. Enter the Client ID you copied from Google Cloud Console
  7. Enter the Client Secret you copied from Google Cloud Console
  8. Click Add Provider to save

✅ Secure Storage: Your Google Client Secret is automatically encrypted with AES-256 before being stored. It's never logged or exposed in plain text.

💡 Tip: The Social Providers tab also shows the OAuth42 callback URL that you need to add to Google Cloud Console. Copy it from there if you haven't added it yet.

Step 4: Add Google Sign-In Button to Your App

If you're using OAuth42's hosted auth pages, the Google Sign-In button appears automatically when you enable the provider. No code changes needed!

For custom login pages, add a Google Sign-In button that initiates the social auth flow:

"use client"

import { useState } from 'react'

export default function LoginPage() {
  const [isLoading, setIsLoading] = useState(false)

  const handleGoogleSignIn = async () => {
    setIsLoading(true)

    // Call OAuth42's social auth init endpoint
    const response = await fetch('/api/auth/social/google', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        provider: 'google',
        client_id: process.env.NEXT_PUBLIC_OAUTH42_CLIENT_ID,
        is_signup: false,
      }),
    })

    const data = await response.json()

    if (data.authorization_url) {
      // Redirect to Google
      window.location.href = data.authorization_url
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-100">
      <div className="max-w-md w-full space-y-6 p-8 bg-white rounded-lg shadow">
        <h1 className="text-2xl font-bold text-center">Sign In</h1>

        <button
          onClick={handleGoogleSignIn}
          disabled={isLoading}
          className="w-full flex items-center justify-center gap-3 py-3 px-4 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
        >
          <svg className="w-5 h-5" viewBox="0 0 24 24">
            <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
            <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
            <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
            <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
          </svg>
          {isLoading ? 'Redirecting...' : 'Continue with Google'}
        </button>

        <div className="relative">
          <div className="absolute inset-0 flex items-center">
            <div className="w-full border-t border-gray-300" />
          </div>
          <div className="relative flex justify-center text-sm">
            <span className="px-2 bg-white text-gray-500">or</span>
          </div>
        </div>

        {/* Your regular email/password login form */}
        <form className="space-y-4">
          <input
            type="email"
            placeholder="Email"
            className="w-full px-4 py-3 border border-gray-300 rounded-lg"
          />
          <input
            type="password"
            placeholder="Password"
            className="w-full px-4 py-3 border border-gray-300 rounded-lg"
          />
          <button
            type="submit"
            className="w-full py-3 px-4 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700"
          >
            Sign In
          </button>
        </form>
      </div>
    </div>
  )
}

Step 5: Create API Route for Social Auth (Custom Login Only)

If using a custom login page, create an API route to initiate the social auth flow:

mkdir -p app/api/auth/social/google
touch app/api/auth/social/google/route.ts

Add the following code to app/api/auth/social/google/route.ts:

import { NextRequest, NextResponse } from 'next/server'

const API_BASE_URL = process.env.OAUTH42_ISSUER || 'https://api.oauth42.com'

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()

    const response = await fetch(`${API_BASE_URL}/api/social-auth/init`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        provider: 'google',
        client_id: body.client_id,
        is_signup: body.is_signup || false,
        state: body.state,
      }),
    })

    const data = await response.json()

    if (!response.ok) {
      return NextResponse.json(data, { status: response.status })
    }

    return NextResponse.json(data)
  } catch (error) {
    console.error('[Social Auth] Error:', error)
    return NextResponse.json(
      { error: 'Failed to initiate social auth' },
      { status: 500 }
    )
  }
}

💡 Using Hosted Auth? Skip this step! OAuth42's hosted auth pages automatically include the Google Sign-In button when you enable the provider.

Step 6: Test Google Sign-In

  1. Start your application
  2. Navigate to your login page
  3. Click "Continue with Google"
  4. You'll be redirected to Google's sign-in page
  5. Sign in with your Google account
  6. Google redirects back to OAuth42
  7. OAuth42 creates/links your user and redirects to your app
  8. You're now logged in!

✅ Success! Your users can now sign in with their Google accounts.

How Account Linking Works

OAuth42 intelligently handles account linking:

New User (Signup Flow)

If the Google email doesn't exist in your app, a new user account is created with their Google profile info (name, email, picture).

Existing User (Login Flow)

If the Google email matches an existing user, the Google identity is linked to their account. They can now sign in with either Google or email/password.

Multiple Social Providers

Users can link multiple social providers (Google, Apple, Twitter) to the same account, giving them flexibility in how they sign in.

Security Considerations

  • PKCE: OAuth42 uses PKCE for all social auth flows, preventing authorization code interception attacks
  • State Parameter: CSRF protection via cryptographically random state tokens
  • Encrypted Storage: Google client secrets are encrypted at rest using AES-256
  • Email Verification: Google provides verified email addresses, reducing fraud risk
  • Token Rotation: Refresh tokens are rotated on each use, limiting exposure from stolen tokens

Troubleshooting

"redirect_uri_mismatch" error

The callback URL in Google Cloud Console doesn't match. Make sure you've added the exact OAuth42 callback URL: https://api.oauth42.com/api/social-auth/callback

"Google social login not configured" error

The Google OAuth credentials are not configured for this application. Go to the OAuth42 Portal → Applications → Your App → Social Providers tab and verify that Google is configured with valid credentials.

"No account found with this email" error

The user is trying to log in but doesn't have an account. Set is_signup: true to allow new account creation, or direct them to sign up first.

Next Steps

Need Help?

Having trouble with Google Sign-In? Check our documentation or reach out to support.