App Logo
Authentication

GitHub

Guide on how to set up GitHub authentication using GoBetterAuth.

Note: This guide uses GitHub Apps for user sign-in, which is recommended by GitHub for new integrations.

Obtain GitHub credentials

  1. Go to GitHub Apps.
  2. Click on "New GitHub App".
  3. Fill in the GitHub App name, Homepage URL, and Description.
  4. On the app page, generate a Client secret under "Client secrets".
  5. Note the Client ID and the generated Client Secret.
  6. Under the "Identifying and authorizing users" section, set the Callback URL to:
    # Assuming base path is /api/auth
    http://localhost:8080/api/auth/oauth2/github/callback
    For production, replace localhost with the base URL of your GoBetterAuth server (e.g. https://api.yourdomain.com).
  7. Make sure to check the following checkboxes:
    • Request user authorization (OAuth) during installation
    • Enable Device Flow
  8. Then save the changes and click on the "Permissions & events" tab on the left, under the "Account permissions", set the "Email addresses" to "Read-only" to access the user's email.

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{
        GitHub: &gobetterauthmodels.OAuth2Config{
          ClientID:     os.Getenv("GITHUB_CLIENT_ID"),
          ClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
          RedirectURL:  fmt.Sprintf("%s/auth/oauth2/github/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/github/login?redirect_to=<YOUR_REDIRECT_URL>
  3. You should be redirected to GitHub's authorization page. After authorizing, you will be redirected back to your application.

On this page