How to Integrate OAuth Providers with AutoGPT: A Complete Developer Guide

AutoGPT OAuth integration requires implementing a BaseOAuthHandler subclass, registering it via the ProviderBuilder API, and executing a PKCE authorization flow to obtain secure, user-scoped access tokens.

AutoGPT's platform natively supports OAuth 2.0 for both API access and single sign-on (SSO), enabling third-party services to run agents and manage integrations on behalf of users. This guide explains how to integrate OAuth providers with AutoGPT using the official Python SDK, the provider registry system, and PKCE security standards.

Prerequisites for AutoGPT OAuth Integration

Before implementing the OAuth flow, ensure you have the following components configured:

  • Registered OAuth Application: Obtain a Client ID, Client Secret, and approved Redirect URIs from the AutoGPT platform.
  • PKCE Support: The platform mandates Proof-Key-for-Code-Exchange (PKCE) for every authorization request to prevent interception attacks.
  • BaseOAuthHandler Implementation: Create a Python class inheriting from BaseOAuthHandler (defined in backend/integrations/oauth/base.py) that handles token exchange and refresh logic.

The OAuth configuration model in autogpt_platform/backend/backend/sdk/provider.py (lines 24-31) defines the OAuthConfig structure that validates these prerequisites.

Step 1: Create the OAuth Handler

Implement a handler class that specifies your provider name and token management methods. This class must expose PROVIDER_NAME as a class attribute and implement asynchronous exchange_code and refresh_token methods.


# my_oauth_handler.py

from backend.integrations.oauth.base import BaseOAuthHandler
from backend.integrations.oauth.types import TokenResponse
import httpx

class MyOAuthHandler(BaseOAuthHandler):
    PROVIDER_NAME = "my_provider"  # Unique identifier in the registry

    async def exchange_code(self, code: str, code_verifier: str) -> TokenResponse:
        async with httpx.AsyncClient() as client:
            resp = await client.post(
                "https://platform.agpt.co/api/oauth/token",
                json={
                    "grant_type": "authorization_code",
                    "code": code,
                    "redirect_uri": self.redirect_uri,
                    "client_id": self.client_id,
                    "client_secret": self.client_secret,
                    "code_verifier": code_verifier,
                },
            )
            data = resp.json()
            return TokenResponse(
                access_token=data["access_token"],
                refresh_token=data["refresh_token"],
                expires_at=data["access_token_expires_at"],
                scopes=data["scopes"],
            )

    async def refresh_token(self, refresh_token: str) -> TokenResponse:
        # POST to /api/oauth/token with grant_type=refresh_token

        # Return new TokenResponse with updated tokens

        pass

The TokenResponse object encapsulates the access token, refresh token, expiration timestamp, and granted scopes returned by the AutoGPT token endpoint.

Step 2: Register the Provider with the SDK

Use the ProviderBuilder DSL in autogpt_platform/backend/backend/sdk/provider.py to register your OAuth handler and define supported authentication types.


# provider_registration.py

from backend.sdk.provider import ProviderBuilder, OAuthConfig
from my_oauth_handler import MyOAuthHandler

my_provider = (
    ProviderBuilder("my_provider")
    .with_oauth(
        oauth_handler=MyOAuthHandler,
        scopes=["EXECUTE_GRAPH", "READ_GRAPH"],  # Request minimal necessary permissions

        client_id_env_var="MY_PROVIDER_CLIENT_ID",
        client_secret_env_var="MY_PROVIDER_CLIENT_SECRET",
    )
    .with_supported_auth_types({"oauth2"})
    .build()
)

The .with_oauth() method stores an OAuthConfig instance containing your handler class, requested scopes, and environment variable names for credentials.

Step 3: Add the Provider to AutoGPT's Registry

When the backend initializes, autogpt_platform/backend/backend/sdk/registry.py automatically discovers providers containing oauth_config attributes. The registration process inserts your handler into AutoRegistry._oauth_handlers and maps credential environment variables to AutoRegistry._oauth_credentials (lines 71-85).

No manual registration call is required beyond building the provider with ProviderBuilder, as the registry introspects provider classes at startup.

Step 4: Implement the PKCE Flow

Generate PKCE parameters to secure the authorization request. AutoGPT requires the S256 code challenge method.


# pkce.py

import hashlib
import base64
import secrets

def generate_pkce():
    """Generate PKCE verifier and challenge for AutoGPT OAuth."""
    verifier = secrets.token_urlsafe(32)
    digest = hashlib.sha256(verifier.encode()).digest()
    challenge = base64.urlsafe_b64encode(digest).decode().rstrip("=")
    return verifier, challenge

Store the verifier securely during the authorization process; you will need it to exchange the authorization code for tokens.

Step 5: Build the Authorization URL

Construct the authorization endpoint URL with required PKCE parameters and scopes.

import urllib.parse

def build_auth_url(client_id, redirect_uri, pkce_challenge, state, scopes):
    """Construct AutoGPT OAuth authorization URL."""
    base = "https://platform.agpt.co/auth/authorize"
    params = {
        "client_id": client_id,
        "redirect_uri": redirect_uri,
        "scope": " ".join(scopes),
        "state": state,
        "code_challenge": pkce_challenge,
        "code_challenge_method": "S256",
        "response_type": "code",
    }
    return f"{base}?{urllib.parse.urlencode(params)}"

Redirect the user to this URL to begin the consent flow.

Step 6: Handle the OAuth Callback

After user authorization, AutoGPT redirects to your specified redirect_uri with an authorization code. Validate the response and exchange the code for tokens:

  1. Verify the state parameter matches the value stored before redirect (CSRF protection).
  2. Extract the code query parameter.
  3. Retrieve the stored PKCE verifier.
  4. Invoke MyOAuthHandler.exchange_code(code, verifier) to obtain access_token and refresh_token.

Step 7: Store and Use Access Tokens

AutoGPT persists OAuth credentials using the OAuth2Credentials model defined in backend/data/model.py (lines 21-31). When executing API calls, retrieve credentials from the provider and initialize your API client.

provider = AutoRegistry.get_provider("my_provider")
creds = provider.get_test_credentials()  # Or fetch user-stored credentials

api_client = provider.get_api(creds)     # Factory method from your provider builder

result = await api_client.some_endpoint()

The OAuth2Credentials object contains the access token, refresh token, and expiration metadata required for authenticated requests.

Step 8: Refresh Tokens Automatically

Access tokens typically expire after one hour. Implement automatic refresh by checking token_expires_at and calling your handler's refresh_token method before making API requests.

async def get_valid_token(creds, handler):
    if creds.expires_at < time.time() + 300:  # Refresh if expiring in 5 minutes

        new_tokens = await handler.refresh_token(creds.refresh_token)
        # Update stored credentials with new_tokens

    return creds.access_token

Step 9: Revoke Tokens on Logout

To securely terminate sessions, revoke tokens using the AutoGPT revocation endpoint:

await httpx.AsyncClient().post(
    "https://platform.agpt.co/api/oauth/revoke",
    json={
        "token": creds.access_token,
        "token_type_hint": "access_token",
        "client_id": os.getenv("MY_PROVIDER_CLIENT_ID"),
        "client_secret": os.getenv("MY_PROVIDER_CLIENT_SECRET"),
    },
)

Security Best Practices for AutoGPT OAuth

Follow these guidelines to maintain secure OAuth integrations:

  • Never expose client_secret in frontend code: Store secrets in environment variables server-side only.
  • Always use PKCE: The platform requires PKCE with the S256 method to prevent authorization code interception.
  • Validate state parameters: Mitigate CSRF attacks by verifying state matches between request and callback.
  • Request minimal scopes: Reduce attack surface by requesting only necessary permissions (e.g., EXECUTE_GRAPH rather than full access).
  • Use HTTPS redirect URIs: Ensure all callback endpoints use TLS to protect authorization codes.
  • Refresh and revoke promptly: Implement token rotation and revocation workflows to minimize exposure of compromised tokens.

Key Files and References

Understanding these source files accelerates debugging and customization:

Summary

  • Implement BaseOAuthHandler: Create a subclass with exchange_code and refresh_token methods to handle AutoGPT's token endpoints.
  • Use ProviderBuilder: Register OAuth capabilities via .with_oauth() in autogpt_platform/backend/backend/sdk/provider.py.
  • Enforce PKCE: Generate and validate PKCE verifiers and challenges for every authorization flow.
  • Request appropriate scopes: Use EXECUTE_GRAPH, READ_GRAPH, or IDENTITY based on your integration needs (API access vs. SSO).
  • Secure token storage: Leverage OAuth2Credentials from backend/data/model.py and implement automatic refresh logic.
  • Follow security protocols: Never expose client secrets, always validate state parameters, and use HTTPS for all redirect URIs.

Frequently Asked Questions

What is PKCE and why does AutoGPT require it for OAuth integration?

PKCE (Proof Key for Code Exchange) is a security extension that prevents authorization code interception attacks by requiring a dynamically generated secret (the code verifier) that is never transmitted over the network until the token exchange. AutoGPT mandates PKCE with the S256 method for all OAuth integrations to ensure that authorization codes cannot be exchanged by malicious interceptors, even in public client scenarios.

How do I handle token expiration when integrating OAuth providers with AutoGPT?

Monitor the expires_at field in the TokenResponse object returned by your BaseOAuthHandler. Before making API calls, compare the current timestamp against expires_at; if the token expires within 300 seconds (5 minutes), call your handler's refresh_token method with the stored refresh token to obtain new credentials. Update your persistent storage with the new access_token and expires_at values.

What OAuth scopes should I request for different AutoGPT integration scenarios?

Request EXECUTE_GRAPH to run agents and execute workflows on behalf of users, READ_GRAPH to access graph definitions and execution history, and READ_STORE to retrieve data from the AutoGPT store. For SSO implementations where AutoGPT acts as an identity provider, request the IDENTITY scope to access the user profile endpoint at /external-api/v1/me. Always request the minimal set of scopes necessary for your specific use case.

Where does AutoGPT store OAuth credentials and how are they accessed?

AutoGPT stores OAuth credentials as OAuth2Credentials objects defined in backend/data/model.py. The system retrieves these credentials from the AutoRegistry (in autogpt_platform/backend/backend/sdk/registry.py) using the provider name. When a block needs to make an authenticated request, it calls provider.get_api(creds), which returns a configured client factory initialized with the stored access token and refresh logic.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →