App Logo
Authentication

Google

Guide on how to set up Google authentication using GoBetterAuth.

Obtain Google credentials

  1. Go to the Google Cloud Console.
  2. Create a new project or select an existing one.
  3. Search for "APIs & Services", then go to "Credentials" in the left menu, click "Create Credentials" > "OAuth client ID".
  4. Choose "Web application", give it a name.
  5. Add authorized redirect URIs:
    # Assuming base path is /api/auth
    http://localhost:8080/api/auth/oauth2/google/callback
    For production, replace localhost with the base URL of your GoBetterAuth server (e.g. https://api.yourdomain.com).
  6. Note the Client ID and Client Secret.

Configure the provider

import (
  "os"
  "fmt"
  
  gobetterauth "github.com/GoBetterAuth/go-better-auth"
  gobetterauthconfig "github.com/GoBetterAuth/go-better-auth/config"
  gobetterauthmodels "github.com/GoBetterAuth/go-better-auth/models"
)

config := gobetterauthconfig.NewConfig(
  // Other config options...
  gobetterauthconfig.WithSocialProviders(
    gobetterauthmodels.SocialProvidersConfig{
      Default: gobetterauthmodels.DefaultOAuth2ProvidersConfig{
        Google: &gobetterauthmodels.OAuth2Config{
          ClientID:     os.Getenv("GOOGLE_CLIENT_ID"),
          ClientSecret: os.Getenv("GOOGLE_CLIENT_SECRET"),
          RedirectURL:  fmt.Sprintf("%s/auth/oauth2/google/callback", os.Getenv("GO_BETTER_AUTH_BASE_URL")),
        },
      },
    },
  ),
  // Set the trusted origins so that redirects to your webapp are allowed and adds an extra layer of security.
  gobetterauthconfig.WithTrustedOrigins(
    gobetterauthmodels.TrustedOriginsConfig{
      Origins: []string{"YOUR_FRONTEND_URL e.g. http://localhost:3000"},
    },
  ),
)

Test the integration

  1. Start your GoBetterAuth server.
  2. In your webapp, create a button when clicked on, it navigates the user to:
    # (replace localhost with your GoBetterAuth server URL in production).
    http://localhost:8080/api/auth/oauth2/google/login?redirect_to=<YOUR_REDIRECT_URL>
  3. You should be redirected to Google's authorization page. After authorizing, you will be redirected back to your application.

On this page