# OAuth 2.0 Integration and Automatic Token Refresh Mechanism

> This document explains how the MaiAgent platform integrates the OAuth 2.0 authentication protocol and provides an automated Token refresh mechanism to ensure the security and continuous availability of third-party service integrations.

## 1. Why is OAuth Integration Needed?

As an enterprise-grade AI assistant platform, MaiAgent needs to deeply integrate with various third-party services (such as Google Workspace, Salesforce, GitHub, etc.). OAuth 2.0 provides a standardized and secure authorization mechanism that addresses the following key challenges:

| Consideration          | Traditional Password Storage                            | OAuth 2.0 Authorization                                                                   |
| ---------------------- | ------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| **Security**           | Requires storing user credentials, with risk of leakage | No need to store user passwords; uses short-lived access tokens                           |
| **Permission Control** | Typically full account access with no granularity       | Fine-grained scope control, e.g., read-only Gmail or calendar management only             |
| **Revocation**         | Requires password change to revoke access               | Can revoke access for a specific application at any time without affecting other services |
| **User Experience**    | Requires entering passwords on third-party platforms    | Authorization completed on a trusted native interface for a smoother experience           |

Common use cases:

* **Tool Connectors**: AI assistants access Google Drive, Notion, Slack, and other services via OAuth to perform file reading, message sending, and other operations
* **Data Synchronization**: Automatically sync customer data from CRM systems (such as Salesforce) without manual imports
* **Automated Workflows**: Integrate project management tools (such as Jira, Asana) for AI assistants to create tasks and update statuses

***

## 2. MaiAgent OAuth Integration Architecture

{% @mermaid/diagram content="flowchart TD
User\["User"]
Frontend\["MaiAgent Frontend"]
Backend\["MaiAgent Backend"]
OAuth\["Third-party OAuth Service"]
DB\[("Token Storage")]
Celery\["Celery Scheduler"]

```
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. Encrypted Storage" --> DB
Celery -- "8. Periodically Check Token Expiration" --> DB
Celery -- "9. Automatically Refresh Token" --> OAuth" %}
```

### 2.1 Authorization Flow Optimizations

MaiAgent implements the following key optimizations:

* **State Validation**: A unique state parameter is generated 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**: The connector\_id parameter is optional, supporting both organization-level and member-level authorization modes
* **Access Token Validation**: Enforces validation of the access\_token presence in Token responses to ensure authorization flow integrity

### 2.2 Token Security Storage

MaiAgent employs multi-layered security measures to protect OAuth Tokens:

* **Encrypted Storage**: All Tokens (Access Token, Refresh Token) are encrypted before storage
* **Client Credential Management**: Stores the OAuth application's client\_id and client\_secret for Token refresh
* **Token Metadata**: Records Token expiration time, authorization scope, and associated user and connector information
* **Legacy Token Handling**: Automatically excludes legacy Tokens without client credentials, ensuring the system only uses Tokens that can be automatically refreshed

### 2.3 Automatic Token Refresh Mechanism

{% @mermaid/diagram content="sequenceDiagram
participant Celery as Celery Beat Scheduler
participant DB as Token Database
participant OAuth as OAuth Service Provider
participant Service as Third-party Service

```
loop Runs every hour
    Celery->>DB: Query Tokens about to expire<br/>(remaining validity < 1 hour)
    DB-->>Celery: Return list of Tokens to refresh

    loop For each Token
        Celery->>OAuth: Request new Access Token<br/>using Refresh Token
        OAuth-->>Celery: Return new Token information
        Celery->>DB: Update Token and record refresh time
    end
end

Note over Celery,DB: Error Handling Mechanism
Celery->>DB: Log failed Token refreshes
Celery->>Service: Notify administrator of re-authorization needed" %}
```

**Key features of the automatic refresh mechanism**:

1. **Proactive Refresh Strategy**: Refreshes Tokens before expiration to avoid service interruption
2. **Smart Query Optimization**: Only queries Tokens with complete client credentials, improving refresh efficiency
3. **Error Handling and Retry**: Implements exponential backoff retry strategy for failed refreshes
4. **Audit Logging**: Detailed records of each Token refresh time, result, and error messages

### 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 administrator intervention
* **Authorization Metadata**: Includes member-related context information in the OAuth state for accurate authorization flow tracking
* **Simplified Redirect URI**: Optimized OAuth callback URI structure for improved integration flexibility and maintainability
* **Frontend State Management**: Uses sessionStorage to manage member OAuth redirect logic, ensuring continuity of the authorization flow

***

## 3. OAuth Integration Best Practices

### 3.1 Scope Design Principles

When configuring OAuth applications, follow the "principle of least privilege":

* **Request only necessary permissions**: If you only need to read Google Calendar, don't request Gmail write permissions
* **Clearly inform users**: Explain why these permissions are needed before authorization
* **Support incremental authorization**: Guide users through additional authorization when extra permissions are needed

### 3.2 Token Lifecycle Management

MaiAgent's Token management follows these best practices:

* **Access Token**: Short-lived (typically 1 hour), used for actual API calls
* **Refresh Token**: Long-lived (potentially months to permanent), used to obtain new Access Tokens
* **Automatic Refresh Timing**: Automatically refreshes 1 hour before Token expiration to ensure uninterrupted service
* **Failure Notification**: Automatically notifies users to re-authorize when a Refresh Token becomes invalid

### 3.3 Security Considerations

* **HTTPS Enforcement**: All OAuth-related communication must use HTTPS
* **State Parameter Validation**: Prevents CSRF attacks and ensures authorization request integrity
* **Encrypted Token Storage**: Uses industry-standard encryption algorithms to protect sensitive data
* **Regular Auditing**: Records all Token usage for security review

***

## 4. Technical Advantages of MaiAgent's OAuth Integration

### 4.1 Development and Integration Advantages

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

### 4.2 Security and Compliance Advantages

* **Zero Password Storage**: Completely eliminates the security risk of storing user passwords
* **Fine-grained Permission Control**: Different authorization scopes can be configured for different services
* **Instant Revocation**: Administrators or users can revoke authorization at any time with immediate effect
* **Audit Trail**: Complete records of all authorization and Token usage activities

### 4.3 User Experience Advantages

* **Seamless Refresh**: Token auto-refresh is completely transparent to users without affecting their experience
* **Smooth Authorization**: Authorization is completed on a trusted native interface with no risk of password leakage
* **Continuous Availability**: Service continues to operate as long as the Refresh Token is valid

***

## 5. Related Documentation

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

### Reference Links

* [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: Querying This Documentation

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

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

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

The question should be specific, self-contained, and written in natural language.
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.
