GitHub sign-in for RDS for Supabase

更新时间:
复制 MD 格式

This guide explains how to integrate GitHub OAuth 2.0 authentication with an RDS for Supabase instance. By configuring GitHub as an identity provider (IdP), you can enable passwordless sign-in for your application, which simplifies the user registration process and enhances security.

Use cases

Consider a developer collaboration platform built on RDS for Supabase that needs to simplify its new user registration process to increase conversion rates. Traditional email and password registration adds friction for users and requires the platform to invest resources in securely storing and managing user credentials, introducing additional development and compliance overhead.

Integrating GitHub as a third-party authentication provider offers the following benefits:

  • Increase user conversion: Most developers have GitHub accounts. One-click sign-in significantly lowers the barrier to entry and is expected to increase the new user registration rate by over 30%.

  • Reduce security risks: Your application no longer stores user passwords. Instead, you delegate credential management and verification to GitHub, leveraging its robust security systems, such as two-factor authentication, to protect user accounts and reduce the risk of credential leaks.

  • Simplify development and maintenance: Avoid the complexity of building and maintaining a custom account system. Your development team can focus on core business features and shorten the product release cycle.

Prerequisites

  • You have created an RDS for Supabase project. For more information, see Create an RDS for Supabase project.

    Note

    If your identity provider, such as GitHub or Google, is located abroad, create your RDS for Supabase instance in an international region for a more stable and faster authentication process.

  • You have a GitHub account.

How it works

This solution uses the standard OAuth 2.0 Authorization Code Flow to authenticate users. The architecture involves interactions between the client application, the RDS for Supabase backend, and the GitHub authorization server.image

Architecture overview:

  • Technology choice: We use OAuth 2.0 because it is an open standard widely adopted for third-party authorization, offering high security and interoperability. RDS for Supabase has built-in support for major OAuth 2.0 providers, simplifying the integration.

  • Key component interactions:

    1. Frontend Application (Client): Initiates the sign-in process and receives a JWT (JSON Web Token) from RDS for Supabase after successful authentication to maintain the session.

    2. RDS for Supabase (backend): Acts as the OAuth 2.0 client and handles all backend communication with GitHub, including exchanging the authorization code for an access token and user information. It also persists user information in the built-in auth.users table.

    3. GitHub (authorization server): Verifies the user's identity and securely provides user authorization information to RDS for Supabase.

  • Network configuration: The RDS for Supabase instance must have public access enabled to make HTTPS requests to the GitHub API endpoints (github.com). For security, you should also configure an allowlist to permit access to the RDS for Supabase instance only from your frontend application server's IP addresses.

Procedure

The following steps guide you through the entire process, from creating a GitHub application to configuring and verifying the RDS for Supabase integration.

Step 1: Create a GitHub OAuth application

In this step, you register an OAuth application on the GitHub platform to obtain the client ID and client secret required for API authentication.

  1. Sign in to your GitHub account and navigate to Settings > Developer settings > OAuth Apps.

  2. Click New OAuth App.

  3. On the registration page, fill in the application information. The key settings are as follows:

    • Application name: A custom name for your application, such as MySaaS Platform.

    • Homepage URL: The live homepage URL of your application, such as https://app.example.com.

    • Authorization callback URL: The URL where GitHub redirects users after they authorize your application. This URL must be the public endpoint of your RDS for Supabase instance with /auth/v1/callback appended. You can find this address in the Network Information section of your RDS for Supabase instance details page. The format is as follows:

      https://<Supabase public endpoint>/auth/v1/callback
      Note The Supabase public endpoint must not include a port number.
  4. After registering the application, the page displays the generated client ID. Click Generate a new client secret to create a secret.

    Important The client secret is displayed only once upon creation. Copy and store it securely, as you will need it for a later step. Leaking this secret poses a severe security risk.

Step 2: Configure authentication parameters

In this step, you enable GitHub authentication in your RDS for Supabase instance and enter the credentials you obtained in the previous step.

  1. On the RDS console, choose AI Application Development. Select a region, and then click the Project ID to open the instance details page.

  2. In the left-side navigation pane, click Auth Configuration.

  3. In the Authentication Providers list, find and click GitHub.

  4. Configure the following parameters:

    • Enable GitHub login: Turn on this switch.

    • GitHub OAuth App Client ID: Enter the client ID you obtained from GitHub.

    • GitHub OAuth App Client Secret: Enter the client secret that you saved.

    • Authorization Callback URL: Re-enter the same authorization callback URL that you configured in your GitHub OAuth Application.

  5. Click Confirm. After the configuration takes effect, the instance restarts automatically.

Step 3: Configure network and security policies

In this step, you configure network access and security policies. This allows the RDS for Supabase instance to access the GitHub public API while restricting access to your instance to authorized applications.

  1. Configure instance public access: On the instance details page, in the Network Information section, make sure the Allow Public Network Access switch is turned on. This setting allows your Supabase instance to make outbound API requests to the GitHub servers.

  2. Configure an access allowlist: On the instance details page, in the Allowlist Information section, click Add Allowlist Group. Add the public egress IP address or CIDR block of your frontend application server to the allowlist. This configuration ensures that only trusted sources can access your Supabase instance's API endpoints.

Step 4: Verify functionality and data

In this step, you use a minimal client application to verify the authentication flow and confirm that user data is synchronized to RDS for Supabase.

  1. Build a verification client Set up a simple frontend project to test the authentication flow. The project includes index.html (page structure), main.js (authentication logic), supabase-config.js (connection configuration), and package.json (dependency management).

    supabase-config.js This file stores the connection credentials for RDS for Supabase.

    // Supabase configuration file
    // Replace the placeholders with your actual Supabase project information
    export const SUPABASE_CONFIG = {
        // RDS for Supabase project URL
        url: 'YOUR_SUPABASE_URL',
        
        // RDS for Supabase anonymous key (anon key)
        anonKey: 'YOUR_SUPABASE_ANON_KEY'
    };
    Note You can obtain YOUR_SUPABASE_URL and YOUR_SUPABASE_ANON_KEY from the API Documentation section of the RDS for Supabase instance details page.

    main.js This file contains the core logic for initiating a sign-in request using the supabase-js SDK.

    import { createClient } from '@supabase/supabase-js';
    import { SUPABASE_CONFIG } from './supabase-config.js';
    
    const supabase = createClient(SUPABASE_CONFIG.url, SUPABASE_CONFIG.anonKey);
    
    // Bind a click event to the sign-in button
    document.getElementById('github-login').addEventListener('click', async () => {
        const { data, error } = await supabase.auth.signInWithOAuth({
            provider: 'github',
            options: {
                redirectTo: window.location.origin // Redirect back to the app home page after authentication
            }
        });
    
        if (error) {
            console.error('GitHub sign-in error:', error.message);
        }
    });
    
    // Listen for authentication state changes to update the UI
    supabase.auth.onAuthStateChange((event, session) => {
        if (event === 'SIGNED_IN') {
            console.log('Signed in:', session.user);
            // Update the UI to show user information here
        } else if (event === 'SIGNED_OUT') {
            console.log('Signed out');
            // Update the UI to show the sign-in interface here
        }
    });

    For the complete client example code, refer to the original documentation.

  2. Execute and verify the flow

    1. In the project's root directory, run npm install to install dependencies, and then run npm run dev to start the local development server.

    2. In your browser, go to the provided local address (for example, http://localhost:5173).

    3. Click Sign in with GitHub. The browser should redirect to the GitHub authorization page.

    4. After authorizing the application, the page automatically redirects back to your application. Check the browser's developer console and confirm that "Signed in" and a user object have been logged.

  3. Confirm backend user data After a successful sign-in, log in to Supabase Studio to confirm that the user data was saved.

    1. On the RDS for Supabase instance details page, in the Network Information section, click the Public Connection Address and log in to Supabase Studio using the project password.

    2. In the left-side navigation pane, select Authentication > Users.

    3. In the user list, you should see a new user record. The Provider column should display github, and the record should contain metadata synchronized from GitHub, such as the email and username.

Costs and risks

Cost breakdown

  • RDS for Supabase instance fees: Enabling GitHub authentication incurs no extra charges. Costs are determined solely by the specifications (compute, storage) of the selected RDS for Supabase instance.

  • Data transfer fees: The OAuth authentication flow generates a small amount of data transfer between RDS for Supabase and the GitHub API over the public internet. These fees are typically negligible.

Key risks

  • Configuration error risk: A mismatch in the authorization callback URL between your GitHub and RDS for Supabase configurations is the most common cause of authentication failures, often resulting in a "redirect_uri_mismatch" error.

  • Credential leak risk: The client secret is highly sensitive information. If it is hard-coded in client-side code or committed to a public code repository, it creates a severe security vulnerability that allows an attacker to impersonate your application. You must manage secrets using server-side environment variables or a key management service.

  • Service dependency risk: Your application's sign-in functionality will depend on the availability of the GitHub OAuth service. If the GitHub service is down, sign-in and registration through this method will be unavailable. Provide an alternative sign-in method (such as email) or a clear error message in your application.

  • Network interruption risk: If public access for the RDS for Supabase instance is disabled, or if Virtual Private Cloud (VPC) or security group rules accidentally block outbound access to github.com, Supabase will be unable to complete the token exchange with GitHub, and the authentication flow will fail.