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:
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
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.
Scheduled Refresh Rules
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
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 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 - Learn how to integrate Remote MCP services through OAuth
Composio Integration - OAuth integration examples for the Composio platform
Zapier Integration - OAuth integration guide for the Zapier platform
References
Last updated
Was this helpful?