Skip to content

API Playground: OAuth Tutorial

The API Playground provides an interactive, educational experience for understanding OAuth 2.1 authentication flows. This guide walks you through using the OAuth Tutorial to learn how OAuth works and generate working code examples for your applications.

Overview

The OAuth Tutorial in the Playground helps you:

  • Understand OAuth 2.1 by walking through each step of the flow
  • Register OAuth clients using Dynamic Client Registration (DCR)
  • Complete real authentication flows with OAuth providers (Google, GitHub, etc.)
  • Exchange authorization codes for access tokens
  • Generate working code that you can copy and use immediately

Prerequisites

Before using the OAuth Tutorial, ensure:

  1. OAuth Provider is Configured: Your proxy must have an OAuth provider configured (Google, GitHub, Azure AD, etc.)
  2. OAuth Proxy is Enabled: The proxy's "OAuth Proxy" feature must be turned on
  3. Redirect URI Registered: http://localhost:8080/playground/callback must be registered with your OAuth provider

Accessing the Playground

  1. Log in to the AI Security Gateway dashboard
  2. Click Playground in the left navigation menu
  3. Select the OAuth Tutorial tab

Step-by-Step OAuth Flow

Step 1: Select a Proxy

Choose an OAuth-enabled proxy from the dropdown list. Only proxies with OAuth Proxy enabled will show an "OAuth Ready" indicator.

If no proxies appear:

  • Navigate to Proxies and create or edit a proxy
  • Enable the "OAuth Proxy" toggle
  • Configure your OAuth provider settings
  • Return to the Playground

Step 2: Register OAuth Client (DCR)

Dynamic Client Registration creates OAuth credentials for your application.

  1. Enter Client Name: A friendly name for your client (e.g., "My Dev App")
  2. Enter Redirect URI: Use the default http://localhost:8080/playground/callback
  3. Click Register OAuth Client

Result: You'll receive:

  • Client ID: Your application's unique identifier
  • Client Secret: Keep this secure (only shown once)
  • Authorization URL: Where users authenticate
  • Token URL: Where you exchange codes for tokens

⚠️ Important: Save these credentials! You'll need them to configure your MCP client (Cursor, Claude Desktop, etc.) or for your own applications.

Step 3: Authorize Client

Initiate the OAuth authorization flow to obtain an authorization code.

  1. Click Build Authorization URL to generate the authorization link
  2. Review the generated URL (includes PKCE parameters for security)
  3. Click Open Authorization Page to authenticate
  4. Log in with your OAuth provider (Google, GitHub, etc.)
  5. Grant permissions when prompted
  6. You'll be redirected to the callback page

Step 4: Copy Authorization Code

After successful authentication, the callback page displays your authorization code.

  1. Copy the authorization code using the copy button
  2. Close the callback tab and return to the Playground tab
  3. Paste the code into the "Authorization Code" field
  4. Click Exchange for Access Token

💡 Tip: The authorization code expires quickly (usually within minutes). Complete the token exchange promptly.

Step 5: Exchange for Token

The token exchange converts your authorization code into an access token.

Success Result:

  • Access Token: Bearer token for API authentication
  • Token Type: Usually "Bearer"
  • Expires In: Token lifetime in seconds
  • Refresh Token: For obtaining new access tokens (if provided)
  • Scope: Granted permissions

Step 6: Validate Token

Verify your access token is valid and view its claims.

  1. The access token is automatically populated
  2. Click Validate Token
  3. Review the validation result

Validation shows:

  • Token validity status
  • Expiration time
  • Associated user email
  • Granted scopes

Step 7: Generate Code

Generate working code examples using your OAuth credentials.

  1. Select your preferred language (curl, Python, JavaScript, Go)
  2. Choose a request type (Health Check, List Tools, Chat Completion)
  3. Click Generate Code
  4. Copy the generated code and run it in your terminal or application

Code Examples

The Playground generates ready-to-use code in multiple languages:

curl

bash
curl -X GET "http://localhost:9001/health" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -H "Content-Type: application/json"

Python

python
import requests

headers = {
    "Authorization": "Bearer YOUR_ACCESS_TOKEN",
    "Content-Type": "application/json"
}

response = requests.get("http://localhost:9001/health", headers=headers)
print(response.json())

JavaScript

javascript
const response = await fetch("http://localhost:9001/health", {
  headers: {
    "Authorization": "Bearer YOUR_ACCESS_TOKEN",
    "Content-Type": "application/json"
  }
});
const data = await response.json();

Understanding the OAuth Flow

The tutorial demonstrates the OAuth 2.1 Authorization Code flow with PKCE:

┌──────────┐                                    ┌──────────────┐
│   You    │                                    │ OAuth        │
│  (User)  │                                    │ Provider     │
└────┬─────┘                                    └──────┬───────┘
     │                                                 │
     │  1. Click "Start Authorization"                 │
     │──────────────────────────────────────────────  │
     │                                                 │
     │  2. Redirect to provider login                  │
     │ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ▶│
     │                                                 │
     │  3. Login & grant permissions                   │
     │◀─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─│
     │                                                 │
     │  4. Redirect with authorization code            │
     │◀────────────────────────────────────────────────│
     │                                                 │
     │  5. Exchange code for token                     │
     │─────────────────────────────────────────────────▶│
     │                                                 │
     │  6. Receive access token                        │
     │◀────────────────────────────────────────────────│

PKCE (Proof Key for Code Exchange)

The Playground automatically implements PKCE for enhanced security:

  1. Code Verifier: A random string generated by the client
  2. Code Challenge: SHA256 hash of the verifier
  3. Verification: Server validates the verifier matches the original challenge

This prevents authorization code interception attacks.

Troubleshooting

"OAuth Proxy is not enabled for this proxy"

Cause: The selected proxy doesn't have OAuth Proxy configured.

Solution:

  1. Go to Proxies → select your proxy → Edit
  2. Scroll to "OAuth Proxy" section
  3. Enable the OAuth Proxy toggle
  4. Configure your OAuth provider
  5. Save and return to Playground

"Token exchange failed: invalid_grant"

Cause: Authorization code has expired or already been used.

Solution:

  • Authorization codes are single-use and expire quickly
  • Start the authorization flow again from Step 3
  • Complete the token exchange within 1-2 minutes of receiving the code

"redirect_uri_mismatch" error

Cause: The redirect URI registered with your OAuth provider doesn't match.

Solution:

  1. Go to your OAuth provider's console (Google Cloud Console, GitHub Settings, etc.)
  2. Add http://localhost:8080/playground/callback as an authorized redirect URI
  3. Save changes and wait a few minutes for propagation

"DCR failed" or "Registration not supported"

Cause: The OAuth provider doesn't support Dynamic Client Registration.

Solution:

  • Manually create OAuth credentials in your provider's console
  • Note: Some providers (like Google) require manual app registration
  • Use the manually created client_id and client_secret in your applications

Callback page shows "Authorization Failed"

Cause: User denied permissions or an error occurred during authentication.

Solution:

  • Check the error message displayed
  • Ensure you're granting the requested permissions
  • Verify your OAuth provider app is properly configured
  • Try again from Step 3

Generated code returns 401 Unauthorized

Cause: Token has expired or is invalid.

Solution:

  • Check if the token has expired (see validation results)
  • Complete the OAuth flow again to get a fresh token
  • Ensure you're using the correct access token (not the authorization code)

Configuration

Supported OAuth Providers

The Playground works with any OAuth 2.1 compliant provider:

ProviderDCR SupportNotes
Google❌ ManualRequires manual app registration
GitHub❌ ManualRequires manual OAuth app creation
Azure AD✅ YesSupports DCR
Okta✅ YesSupports DCR
Auth0✅ YesSupports DCR
Generic OAuthVariesDepends on provider configuration

Default Scopes

The Playground uses minimal scopes for security:

  • openid - Basic OpenID Connect authentication

You can configure additional scopes in your proxy's OAuth settings for production use.

Best Practices

  1. Development Only: The Playground is designed for learning and development, not production use
  2. Secure Your Tokens: Never commit access tokens to version control
  3. Minimal Scopes: Request only the permissions your application needs
  4. Token Rotation: Implement refresh token flows for long-lived applications
  5. HTTPS in Production: Always use HTTPS for OAuth in production environments

Next Steps

After completing the OAuth Tutorial:

  1. Configure MCP Clients: Use the DCR credentials to set up Cursor IDE or Claude Desktop
  2. Build Applications: Use the generated code as a starting point for your integrations
  3. Production Setup: Configure proper redirect URIs and scopes for production deployments