Authentication
OAuth for AI Agents: Composio vs Manual Implementation
The moment your AI agent needs to act on behalf of a user, API keys stop working. You need OAuth. Here is the honest comparison of building OAuth yourself vs. using Composio, with the hidden costs nobody mentions.
Your first AI agent probably used an API key. You hardcoded it into an environment variable, the agent made calls, life was simple. Then your second user signed up. Now the agent needs to read their Gmail, not yours. It needs to post in their Slack workspace, not yours. The API key model breaks the moment you go multi-tenant.
OAuth is the answer. It is also the single largest source of accidental complexity in AI agent products. A proper OAuth implementation for one provider takes a week. Doing it for ten providers, across multiple tenants, while handling token refresh, revocation, scope escalation, and provider-specific edge cases takes a full engineering quarter.
There is an alternative. Composio abstracts OAuth for 60+ apps into a single connection flow. Below we walk through what rolling your own OAuth actually costs, what Composio does, and when each choice makes sense.
Why Agents Need OAuth, Not API Keys
API keys identify a developer. OAuth tokens identify a user. When an AI assistant reads your email to summarize it, the action has to run under your permissions, not the developer's. If a shared API key could read emails, it would read every user's emails, which is a security disaster.
Three scenarios force OAuth:
- Per-user data access. Gmail, Google Calendar, Notion, GitHub private repos, Linear, Asana, Salesforce.
- Per-workspace write access. Slack posts, Discord messages, Trello cards, Jira tickets.
- User-signed transactions. Stripe Connect, Shopify merchant APIs, HubSpot CRM updates.
Building OAuth Yourself: What It Actually Takes
Most tutorials show you a happy-path OAuth 2.0 flow in 50 lines. Production reality is 500 to 2,000 lines per provider, plus shared infrastructure. Here is the full checklist:
1. Register the app with each provider
Every provider has its own developer portal. You register a new app, set redirect URIs, request scopes, sometimes wait for manual approval (Slack app directory, Google sensitive scopes, Microsoft certification). Expect 1 to 5 business days for a sensitive-scope approval. Budget for multiple redirects per environment (local, preview, staging, production) per provider.
2. Build the authorization flow
Construct the authorization URL, include a CSRF token (state param), handle the callback, exchange the code for tokens, store tokens securely. The code looks simple until you handle PKCE for public clients, dynamic scopes, and provider-specific query parameter quirks.
// Simplified GitHub OAuth handler — production needs more
export async function GET(req: Request) {
const url = new URL(req.url);
const code = url.searchParams.get("code");
const state = url.searchParams.get("state");
// 1. Validate state against session (CSRF)
// 2. Exchange code for tokens
const tokenRes = await fetch("https://github.com/login/oauth/access_token", {
method: "POST",
headers: { Accept: "application/json" },
body: new URLSearchParams({
client_id: process.env.GITHUB_CLIENT_ID!,
client_secret: process.env.GITHUB_CLIENT_SECRET!,
code: code!,
}),
});
const { access_token, refresh_token, expires_in } = await tokenRes.json();
// 3. Encrypt and store tokens per user
// 4. Handle errors (revoked app, denied scope, expired code)
// 5. Redirect back to the app with success/failure state
}3. Secure token storage
Never store tokens in plaintext. Use authenticated encryption (AES-256-GCM with a KMS-managed key), rotate the key annually, maintain an audit log for every token read. If you are in a regulated vertical, tokens must live in an HSM-backed store with strict IAM. Getting this wrong leaks every user's account.
4. Token refresh logic
Access tokens expire. Refresh tokens expire too, just slower. Every API call needs to check token freshness, refresh if needed, handle races between concurrent refreshes, and recover when the refresh token itself is revoked. Providers differ: Google rotates refresh tokens, GitHub does not, Slack has complex token types for bots vs users.
5. Revocation and error recovery
Users revoke access from the provider's settings page. Your app does not get a webhook for this. The first sign is an API call that returns 401. You need to detect, mark the connection dead, notify the user, and prompt a reconnect flow. If you do not, the agent silently fails on that user for weeks.
6. Scope escalation
Users often grant minimal scopes initially. Later the agent needs a broader scope. You need a re-authorization flow that feels like a normal reconnect, not like a full onboarding restart. Few teams build this and most users drop off.
7. Multi-tenant isolation
In a SaaS product, customer A's tokens must never touch customer B's agent. Add tenant IDs to every token record, add row-level security to the token table, ensure every agent call loads tokens scoped to the current tenant. Easy to describe, easy to get wrong.
What Composio Does Instead
Composio is a managed service that handles OAuth for 60+ apps behind one API. The entire authorization flow becomes three steps:
// 1. Initiate a connection for a user to Gmail
const connection = await composio.connections.initiate({
integrationId: "gmail",
userId: "user_123",
});
// Send user to connection.redirectUrl
// 2. Composio stores tokens, handles refresh, manages revocation
// 3. Call any Gmail action through a single endpoint
const result = await composio.actions.execute({
actionId: "gmail_send_email",
connectedAccountId: connection.id,
params: {
recipient: "customer@example.com",
subject: "Order confirmed",
body: "Thanks for your order...",
},
});Composio stores the tokens encrypted, refreshes them automatically, handles revocation detection, and exposes every action as a uniformly-shaped function call. Scope management, multi-tenant isolation, and provider-specific edge cases are all abstracted.
Side-by-Side Comparison
| Dimension | Manual | Composio |
|---|---|---|
| Time per provider | 1-5 days | 10 minutes |
| Token storage | You own encryption | Managed, SOC 2 |
| Refresh logic | Per-provider | Automatic |
| Revocation handling | Manual detection | Built-in |
| Multi-tenant | You build | First-class |
| Compliance | Your audit | SOC 2 Type II |
| Provider breakage | You fix | Composio fixes |
| Lock-in | None | Moderate |
The Hidden Cost of Rolling Your Own
Engineers who have not built OAuth at scale routinely underestimate it by 3x. Here is what actually consumes the time:
- Provider drift. Google changes a scope name, Slack deprecates a token type, GitHub enforces new PKCE rules. Expect 2 to 5 maintenance incidents per provider per year.
- Debugging user-specific failures. "Why can this user not connect Notion?" is a multi-hour investigation every time.
- Compliance audits.SOC 2 auditors care how you store OAuth tokens. Composio's existing report is free leverage.
- Support burden. Every provider has its own reconnect flow, and each one generates support tickets when users get confused.
When Rolling Your Own Still Makes Sense
Composio is not always the right call. Three situations justify building OAuth yourself:
- One provider forever. If your product only ever integrates with GitHub, a single hand-built OAuth flow is fine. The ROI of Composio improves with every added provider.
- Regulatory prohibition on third-party token storage. Some healthcare and government contexts forbid tokens from touching third-party infrastructure. Either self-host Composio or build in-house.
- Deep provider-specific features. If you need Gmail's advanced push notifications with custom pubsub topics, you may outgrow the abstraction. Most teams never hit this.
Using Composio Through an MCP Gateway
Composio solves OAuth. A gateway solves everything else: unified billing, unified protocol, unified tool catalog. Combining them is the cleanest architecture for a multi-tool agent product.
ToolRoute routes through Composio for OAuth-heavy tools like Gmail, Slack, and Notion, while routing directly to stateless tools like Tavily or Resend. Your agent speaks one protocol and one API key to ToolRoute. ToolRoute handles the Composio connection handoff behind the scenes. You get the benefits of both abstractions without running two SDKs.
// Agent calls through ToolRoute — Composio is invisible
await fetch("https://toolroute.ai/api/v1/execute", {
method: "POST",
headers: {
Authorization: "Bearer $TOOLROUTE_KEY",
"Content-Type": "application/json",
},
body: JSON.stringify({
tool: "gmail",
operation: "send_email",
user_id: "user_123", // maps to Composio connected account
input: {
to: "customer@example.com",
subject: "Your order",
body: "Thanks for ordering",
},
}),
});Decision Shortcut
Three integrations or more, a multi-tenant product, or any timeline pressure: use Composio. One integration, solo project, no OAuth expertise gap: build it yourself and learn from the pain. Anything in between: build Composio into your architecture from day one and save the migration tax later.
Frequently Asked Questions
Why do AI agents need OAuth instead of API keys?
API keys belong to the developer. OAuth tokens belong to the end user. When an agent reads a user's Gmail or posts to their Slack, the action runs under the user's permissions. API keys would mean every user shares one inbox, which breaks multi-tenancy.
How long does it take to build OAuth for one app yourself?
3 to 5 engineering days for the first integration, then 1 to 2 days per additional provider. Includes authorization URL, callback, token storage, refresh, error recovery, revocation, and scope management. Multi-tenant SaaS adds 2 to 3 days for tenant isolation.
What does Composio cost vs. building OAuth yourself?
Composio has a free tier for development and paid plans from around $49/month for production. Building costs 3 to 5 engineer-days per integration plus maintenance. Above 3 integrations, Composio is almost always cheaper.
Is Composio secure for storing OAuth tokens?
Composio encrypts tokens at rest, uses TLS in transit, and is SOC 2 Type II certified. Storing tokens yourself is secure if you follow standard practices, but most teams underestimate the operational overhead. For regulated industries, audit Composio or use self-hosted.
Can I use Composio through an MCP gateway like ToolRoute?
Yes. ToolRoute exposes Composio's OAuth-backed tools through the same unified API as every other tool. Configure Composio once per user, then call Gmail, Slack, Notion, or any of 60+ apps through a single endpoint with unified billing.
Related Articles
ToolRoute routes OAuth-backed tools through Composio and stateless tools directly, behind one API key. Read the docs or browse the 51-tool catalog.