Skip to Content

OAuth2 Internal Processing Flow

This document provides a detailed explanation of AIP’s internal processing when integrating OAuth2 authentication with Custom MCP servers. It serves as a technical companion to the OAuth2 Authentication & DCR Guide.

How to Use This Document

The OAuth2 Authentication & DCR Guide focuses on “how to integrate.” In most cases, that is sufficient. However, the following situations require understanding AIP’s internal processing flow.

Diagnosing integration failures — When the OAuth popup doesn’t appear or authentication fails, understanding the internal flow enables you to pinpoint exactly which stage the problem occurred at — Discovery, Token Exchange, or token renewal. For example, if the OAuth popup doesn’t appear at all, it indicates a Discovery stage failure; if the popup appears but an error occurs after login, it points to a Token Exchange issue.

Security review and audit response — This document provides the information needed when enterprise security teams review the safety of the OAuth implementation. For the question “What happens if the Authorization Code is intercepted?”, you can use this document as evidence to explain that AIP automatically applies PKCE (Proof Key for Code Exchange) to prevent code interception attacks. You can also verify the details of security mechanisms such as CSRF prevention through State tokens, server-side management of Client Secrets, and communication encryption via TLS.

MCP server developer implementation decisions — When MCP server developers implement an Authorization Server, they need to know what requests AIP actually sends and what responses it expects. For example, this document serves as a reference for decisions such as whether to include code_challenge_methods_supported in the ASM, how to validate the code_verifier at the Token Endpoint, and what the required format and fields are for DCR registration requests. If PKCE is not supported, AIP proceeds without it, but implementing PKCE support is recommended as it strengthens security.

Understanding the token lifecycle — This document provides the information needed to understand and respond to token-related issues that occur during operation, such as Access Token expiration, Refresh Token renewal, and Client Secret changes. It covers the flow of AIP automatically renewing Access Tokens using Refresh Tokens, the re-authentication procedure when Refresh Tokens themselves expire, and the reconfiguration steps when Client Secrets are changed.

Overall Flow Overview

When an MCP Server URL is entered, AIP processes it in the following order:

  1. Metadata Discovery — Determines the authentication method through OAuth Discovery.
  2. Client Registration or Manual Input — Automatically registers via DCR or requests Client ID/Secret from the user.
  3. Authorization URL Generation — Initiates the Authorization Code Flow with PKCE.
  4. OAuth Popup — The user logs in to the service.
  5. Callback Handling and Token Exchange — Exchanges the Authorization Code for an Access Token.
  6. Token Storage — Stores tokens per user and completes the integration.

Step 1: OAuth Discovery and Auth Type Determination

Metadata Discovery Order

When an MCP Server URL is entered, the AIP backend queries metadata in the following order:

Protected Resource Metadata (PRM) Discovery

AIP sends a POST request to the MCP server to check authentication requirements.

  • 401 response + WWW-Authenticate header: Extracts the resource_metadata URL from the header to fetch the PRM.
  • Non-401 response: Directly queries the /.well-known/oauth-protected-resource endpoint.

The authorization_servers field is extracted from the PRM to locate the Authorization Server.

Authorization Server Metadata (ASM) Discovery

Based on the Authorization Server URL obtained from the PRM, AIP queries the ASM. The following paths are tried in priority order:

  1. RFC 8414: /.well-known/oauth-authorization-server/{path}
  2. OIDC (path insertion): /.well-known/openid-configuration/{path}
  3. OIDC (path appending): /{path}/.well-known/openid-configuration

The ASM response includes authorization_endpoint, token_endpoint, scopes_supported, registration_endpoint (optional), and other fields.

Auth Type Determination

The authentication method is determined based on the ASM discovery result:

ConditionResult
ASM discovery failsNoAuth — No OAuth flow is initiated
ASM has registration_endpointOAuthWithDCR — Automatic client registration
ASM has no registration_endpointOAuth — Manual Client ID/Secret input

The ASM’s issuer field is validated per RFC 8414. For compatibility with services where the subdomain differs (e.g., Slack), a fallback with relaxed issuer matching is applied.

Discovery Execution Timing

OAuth Discovery (PRM → ASM query) is executed twice:

  1. When the MCP Server URL is entered — Executed to determine the authentication method (NoAuth / OAuthWithDCR / OAuth). Based on this result, the UI to display to the user is determined (automatic progression / Client ID·Secret input dialog / continue without an OAuth flow).
  2. When Client ID/Secret is submitted (or during DCR registration) — Executed again to generate the Authorization URL. At this point, the latest values such as authorization_endpoint, token_endpoint, and scopes_supported are fetched from the ASM and used in the authorization request.

The second execution ensures the latest metadata is used, as there may be a time gap between the first discovery and the actual authorization request.

Step 2: Client Registration or Manual Input

OAuthWithDCR (Automatic Registration)

AIP sends a client registration request in RFC 7591 format to the ASM’s registration_endpoint:

POST {registration_endpoint} Content-Type: application/json { "client_name": "Custom MCP Client of AI Platform", "redirect_uris": ["https://{aip-domain}/integration/oauth/callback"], "grant_types": ["authorization_code", "refresh_token"], "scope": "read write", "token_endpoint_auth_method": "client_secret_basic" }

On success, client_id and client_secret are automatically obtained, and processing proceeds to Step 3.

If DCR registration fails, AIP automatically falls back to the manual input method. The Client ID/Secret input dialog is displayed to the user.

OAuth (Manual Input)

A Client ID/Secret input dialog is displayed to the user. The dialog includes the following information:

  • MCP Server URL — The target server address
  • OAuth Callback URL — The Redirect URI that the user must register in the external service’s OAuth App (copy button provided)
  • Required Scope List — Permissions retrieved from the ASM’s scopes_supported
  • Client ID / Client Secret input fields

The user creates an OAuth App on the external service, registers the Callback URL, and enters the issued Client ID and Secret.

On authentication failure, the dialog reappears with the error message displayed and previous input values pre-filled for convenient retry.

Step 3: Authorization URL Generation

Once the Client ID/Secret is secured (via DCR auto-issuance or manual input), the AIP backend generates the Authorization URL.

PKCE (Proof Key for Code Exchange)

When the ASM’s code_challenge_methods_supported includes S256, AIP automatically applies PKCE:

  1. Code Verifier generation — A cryptographically secure random string
  2. Code Challenge generationBASE64URL(SHA256(code_verifier))
  3. The Code Verifier is stored server-side only; only the Code Challenge is included in the Authorization URL

MCP server developers are strongly recommended to include code_challenge_methods_supported: ["S256"] in their Authorization Server Metadata. Without this field, AIP proceeds without PKCE, but implementing PKCE is strongly recommended to prevent Authorization Code interception attacks.

State Token

A one-time State token is generated to prevent CSRF attacks. The State token is a cryptographically secure random value, and session information required for authentication is managed exclusively on the AIP server side. The token is valid for approximately 10 minutes and is immediately deleted after being consumed once during the callback.

Authorization URL Parameters

The final Authorization URL includes the following parameters:

ParameterDescription
client_idClient ID from DCR or manual input
redirect_uriAIP’s OAuth callback URL
response_typecode (Authorization Code Flow)
stateOne-time CSRF prevention token
code_challengePKCE Challenge (when supported)
code_challenge_methodS256 (when supported)
scopeFrom ASM’s scopes_supported
resourceRFC 8707 Resource Indicator (when supported)

Step 4: OAuth Popup

A browser popup opens with the generated Authorization URL, and the user logs in to the external service. Upon successful login, the service redirects to AIP’s callback URL with code and state parameters.

Step 5: Callback Handling and Token Exchange

Callback Reception

GET /integration/oauth/callback?state={state}&code={code}

AIP performs the following:

State Validation

Retrieves the stored session information using the received state value. Authentication fails if the State is invalid or expired.

Token Exchange

Using the stored information (Client ID, Client Secret, Code Verifier), AIP requests a code exchange at the Token Endpoint:

POST {token_endpoint} Content-Type: application/x-www-form-urlencoded grant_type=authorization_code &code={authorization_code} &client_id={client_id} &client_secret={client_secret} &redirect_uri={callback_url} &code_verifier={code_verifier}

Token Reception

The Token Endpoint responds with:

FieldDescription
access_tokenAccess token for API calls
refresh_tokenToken for renewal (optional)
expires_inAccess token expiration time in seconds

Step 6: Token Storage and Integration Completion

Auth Ticket

Upon successful token exchange, AIP generates an Auth Ticket. The Auth Ticket is a one-time temporary token that is passed to the frontend to complete the integration installation.

The Auth Ticket includes:

ItemPurpose
Access TokenMCP server API calls
Refresh TokenToken renewal on expiration
Client ID / Client SecretAuthentication for token renewal requests
Token EndpointTarget URL for token renewal requests

Per-User Token Management

Tokens are stored independently per user. When multiple users each authenticate against the same MCP server, each user has their own tokens.

Token Renewal

When an Access Token expires, AIP automatically renews it using the stored Refresh Token:

POST {token_endpoint} Content-Type: application/x-www-form-urlencoded grant_type=refresh_token &refresh_token={refresh_token} &client_id={client_id} &client_secret={client_secret}

On successful renewal, a new Access Token (and possibly a new Refresh Token) is stored. If the Refresh Token has expired or been revoked, the user must re-authenticate via OAuth.

Security Considerations

PKCE (Proof Key for Code Exchange)

AIP automatically applies PKCE when the Authorization Server supports it. PKCE prevents Authorization Code interception attacks and is the security mechanism recommended by the MCP specification.

  • The Code Verifier is stored server-side only and is never exposed to the client.
  • The Code Challenge is a SHA-256 hash, making it impossible to reverse-engineer the original Verifier.

State Token

  • Generated as a cryptographically secure random value.
  • Valid for approximately 10 minutes and immediately deleted after single use.
  • Prevents CSRF (Cross-Site Request Forgery) attacks.

Client Secret Storage

  • Manually entered Client Secrets are included in the Auth Ticket and managed server-side only.
  • Stored alongside the Access Token as they are needed for token renewal.
  • All communication occurs over TLS (HTTPS).

Redirect URI Validation

The AIP callback URL must be exactly registered in the external service’s OAuth App. If the Redirect URI does not match, the Authorization Server will reject the request.

Troubleshooting

DCR Registration Failure with Manual Input Fallback

When DCR registration fails, AIP automatically displays the manual input dialog. Common failure causes:

  • The Authorization Server does not support the DCR request format.
  • The registration_endpoint exists in the ASM but does not actually function.
  • Network errors or timeouts.

Token Exchange Failure

When the callback is received but token exchange fails:

  • Verify that the Client ID/Secret are correct.
  • Confirm that the OAuth App’s Redirect URI exactly matches the AIP callback URL.
  • Check that the Authorization Server’s token endpoint is functioning properly.

Token Renewal Failure

  • If the Refresh Token has expired or been revoked, the user is prompted to re-authenticate.
  • If the Client Secret has been changed, delete the MCP integration and reconfigure with new Client ID/Secret.

State Expiration

If login in the OAuth popup takes more than 10 minutes, the State token expires. In this case, the integration setup must be restarted.

Last updated on