> For the complete documentation index, see [llms.txt](https://docs.maiagent.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.maiagent.ai/tech/en/advanced-genai-tech/oauth-integration.md).

# OAuth 2.0 Integration and Automatic Token Refresh

OAuth 2.0 integration and automatic token refresh: authorization architecture, refresh token management, and best practices for connecting MaiAgent to third-party services such as Google Workspace, Sa

> This document explains how the MaiAgent platform integrates the OAuth 2.0 authentication protocol and provides automatic token refresh to ensure secure and continuous access to third-party service integrations.

## 1. Why Is OAuth Integration Needed?

As an enterprise Agent platform, MaiAgent needs deep integration with various third-party services, such as Google Workspace, Salesforce, and GitHub. OAuth 2.0 provides a standardized, secure authorization mechanism that addresses the following key challenges:

| Consideration          | Traditional Password Storage                                   | OAuth 2.0 Authorization                                                                                      |
| ---------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| **Security**           | Requires storing user credentials, creating a risk of exposure | Uses short-lived access tokens without storing user passwords                                                |
| **Permission Control** | Usually grants full account access, without granular control   | Allows precise control over authorization scopes, such as read-only Gmail access or calendar management only |
| **Revocation**         | Requires changing the password to revoke access                | Allows access for a specific application to be revoked at any time without affecting other services          |
| **User Experience**    | Requires entering a password on a third-party platform         | Completes authorization through a trusted native interface for a smoother experience                         |

Common use cases:

* **Tool Connector**: Agents access services such as Google Drive, Notion, and Slack through OAuth authorization to perform operations such as reading files and sending messages
* **Data Synchronization**: Automatically synchronizes customer data from CRM systems such as Salesforce without manual imports
* **Automated Workflows**: Integrates project management tools such as Jira and Asana so Agents can help create tasks and update statuses

***

## 2. MaiAgent OAuth Integration Architecture

```mermaid
flowchart TD
    User["User"]
    Frontend["MaiAgent Frontend"]
    Backend["MaiAgent Backend"]
    OAuth["Third-Party OAuth Service"]
    DB[("Token Storage")]
    Scheduler["Scheduled Task"]

    User -- "1. Authorization request" --> Frontend
    Frontend -- "2. Redirect to authorization page" --> OAuth
    OAuth -- "3. User grants authorization" --> OAuth
    OAuth -- "4. Return authorization code" --> Backend
    Backend -- "5. Exchange for Access Token" --> OAuth
    OAuth -- "6. Return token information" --> Backend
    Backend -- "7. Encrypt and store" --> DB
    Scheduler -- "8. Check tokens nearing expiration every 20 minutes" --> DB
    Scheduler -- "9. Automatically refresh tokens" --> OAuth
```

### 2.1 Authorization Flow Optimizations

MaiAgent implements the following key optimizations:

* **State Validation**: Generates a unique state parameter for each authorization request to prevent CSRF attacks
* **Member-Level Authorization**: Supports individual OAuth authorization for organization members, enabling more granular permission management
* **Flexible Callback Handling**: Makes the connector\_id parameter optional to support organization-level or member-level authorization
* **Access Token Validation**: Requires the presence of access\_token in token responses to ensure the authorization flow is complete

### 2.2 Secure Token Storage

MaiAgent uses multiple layers of security to protect OAuth tokens:

* **Encrypted Storage**: Encrypts all tokens (Access Tokens and Refresh Tokens) before storing them
* **Client Credential Management**: Stores the OAuth application's client\_id and client\_secret for token refresh
* **Token Metadata**: Records token expiration times, authorization scopes, and associated user and connector information
* **Legacy Token Handling**: Automatically excludes legacy tokens without client credentials, ensuring the system uses only tokens that can be refreshed automatically

### 2.3 Automatic Token Refresh

Access tokens typically have a short lifetime. MaiAgent obtains new tokens before expiration in two ways, so Agents and connectors do not need to ask users to authorize again each time: **scheduled refresh** and **refresh on use**.

```mermaid
sequenceDiagram
    participant Scheduler as Scheduled Task
    participant DB as Token Database
    participant OAuth as OAuth Provider

    loop Every 20 minutes
        Scheduler->>DB: Query tokens that have expired or expire within 30 minutes,<br/>and have been active in the last 7 days (up to 50 per run)
        DB-->>Scheduler: List of tokens to refresh
        loop Process each token
            Scheduler->>OAuth: Exchange Refresh Token for a new Access Token
            alt Refresh succeeds
                OAuth-->>Scheduler: New token information
                Scheduler->>DB: Update token and expiration time
            else Authorization server returns 400/401
                Scheduler->>DB: Disable this authorization (reauthorization required)
            else Other error
                Scheduler->>DB: Keep unchanged and retry at the next scheduled run
            end
        end
    end
```

#### Scheduled Refresh Rules <a href="#scheduled-refresh-rules" id="scheduled-refresh-rules"></a>

| Item                                          | Rule                                                                                                                                                                                                                   |
| --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Frequency                                     | Once every 20 minutes                                                                                                                                                                                                  |
| Tokens to Refresh                             | Tokens that have expired or will expire within 30 minutes                                                                                                                                                              |
| Coverage                                      | Member-authorized connectors, member-authorized MCP tools, and contact-authorized connectors                                                                                                                           |
| Activity Requirement                          | Member tokens: updated within the last 7 days, with both the member and their organization still active; contact tokens: used within the last 7 days (authorization time is used for tokens that have never been used) |
| Prerequisites                                 | The token has a Refresh Token and a stored OAuth Client ID; disabled connectors or tools are skipped                                                                                                                   |
| Batch Size                                    | Up to 50 tokens, processed in expiration order; only one refresh task runs at a time                                                                                                                                   |
| Individual Refresh Failure                    | Logs the error without retrying during the same run; retries at the next scheduled run if the token still meets the requirements                                                                                       |
| Entire Task Failure                           | Retries after a fixed 60-second interval, up to 3 times                                                                                                                                                                |
| Authorization Server Rejection (HTTP 400/401) | Disables this authorization; the user must authorize again                                                                                                                                                             |
| No New Refresh Token in the Response          | Keeps the original Refresh Token                                                                                                                                                                                       |

Tokens inactive for more than 7 days are not refreshed on a schedule. A member's tokens also stop being refreshed after the member is deactivated or leaves the organization. Subsequent use follows the “Refresh on Use” process below; if the Refresh Token is no longer valid, reauthorization is required.

#### Refresh on Use <a href="#on-use-refresh" id="on-use-refresh"></a>

When an Agent needs a token that has expired or will expire within 60 seconds, the platform obtains a new token before making the call. If refresh fails, the call cannot obtain a token. After a connector's authorization fails to refresh, further attempts are paused: the delay starts at 60 seconds and doubles with each failure, up to 1 hour. MCP tool tokens (member-authorized or shared across an organization) are also refreshed before use under the same 60-second rule.

### 2.4 Member-Level Authorization Support

MaiAgent now supports more granular member-level OAuth authorization:

* **Independent Authorization Flow**: Each organization member can complete OAuth authorization independently, without an organization administrator's involvement
* **Authorization Metadata**: Includes member-related context in OAuth state for accurate tracking of the authorization flow
* **Simplified Redirect URIs**: Optimizes the OAuth callback URI structure for greater integration flexibility and maintainability
* **Frontend State Management**: Uses sessionStorage to manage member OAuth redirects and maintain continuity throughout the authorization flow

***

## 3. OAuth Integration Best Practices

### 3.1 Authorization Scope Design Principles

Follow the principle of least privilege when configuring OAuth applications:

* **Request Only Required Permissions**: If you only need to read Google Calendar, do not request Gmail write permissions
* **Clearly Inform Users**: Explain why these permissions are needed before authorization
* **Support Incremental Authorization**: Guide users through authorization again when additional permissions are needed

### 3.2 Token Lifecycle Management

MaiAgent follows these token management best practices:

* **Access Token**: Short-lived (usually 1 hour), used for actual API calls
* **Refresh Token**: Long-lived (from several months to potentially indefinite), used to obtain new Access Tokens
* **Automatic Refresh Timing**: Checks every 20 minutes and refreshes tokens expiring within 30 minutes; also refreshes before use if expiration is within 60 seconds. See [2.3](#scheduled-refresh-rules) for the rules
* **Invalid Refresh Token**: When the authorization server rejects a refresh, the authorization is disabled and the user must authorize again

### 3.3 Security Considerations

* **HTTPS Required**: All OAuth-related communications must use HTTPS
* **State Parameter Validation**: Prevents CSRF attacks and ensures the integrity of authorization requests
* **Encrypted Token Storage**: Uses industry-standard encryption algorithms to protect sensitive data
* **Regular Audits**: Records all token usage to support security reviews

***

## 4. Technical Advantages of MaiAgent OAuth Integration

### 4.1 Development and Integration Advantages

* **Standardized Interface**: Follows the OAuth 2.0 standard and is compatible with most third-party services
* **Simplified Configuration**: Administrators only need to provide basic OAuth application information to complete integration
* **Automated Maintenance**: Token refresh is fully automated and requires no manual intervention
* **Flexible Deployment**: Supports multiple authorization modes at the organization and member levels

### 4.2 Security and Compliance Advantages

* **No Password Storage**: Completely avoids the security risks of storing user passwords
* **Granular Permission Control**: Allows different authorization scopes for different services
* **Immediate Revocation**: Administrators or users can revoke authorization at any time, with changes taking effect immediately
* **Audit Trail**: Records all authorization and token usage activity in full

### 4.3 User Experience Advantages

* **Seamless Refresh**: Automatic token refresh is transparent to users and does not interrupt their experience
* **Smooth Authorization**: Completes authorization through a trusted native interface without concerns about password exposure
* **Continuous Availability**: Services can continue operating as long as the Refresh Token remains valid

***

## 5. Related Technical Documentation

* [Remote MCP Service Overview](/tech/en/mcp/remote-mcp.md) - Learn how to integrate Remote MCP services through OAuth
* [Composio Integration](/tech/en/mcp/composio.md) - OAuth integration examples for the Composio platform
* [Zapier Integration](/tech/en/mcp/zapier.md) - OAuth integration guide for the Zapier platform

### References

* [OAuth 2.0 RFC 6749](https://datatracker.ietf.org/doc/html/rfc6749)
* [OAuth 2.0 Security Best Current Practice](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics)
* [PKCE for OAuth Public Clients (RFC 7636)](https://datatracker.ietf.org/doc/html/rfc7636)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.maiagent.ai/tech/en/advanced-genai-tech/oauth-integration.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
