How to handle OAuth for AI Agents without exposing tokens: Composio auth-only mode
Coding agents have made integrations seem a lot easier to build. You can open Claude Code, ask it to add a "Connect your Gmail" button to your app, and within ten minutes you have an OAuth flow, a callback route and a database table to store the tokens. You test it with your own account, everything works, and you move on to building the next feature.
If you've ever shipped an OAuth integration to production, you know how much work is still left. You need to register your application with each OAuth provider, and depending on the provider and the permissions you're requesting, the approval process can take months.
You also have to wade through poorly written documentation, figure out how each provider handles token expiration and refresh tokens, and make sure you're storing and handling users' tokens securely. Maintaining these integrations can easily become a full-time job as you add more providers.
Claude can generate most of the code for you, but unless you already know about Google's seven-day refresh token expiry for apps in Testing mode, you might spend hours figuring out why your users keep getting disconnected. There are also less obvious problems, like two tool calls trying to refresh the same token at the same time, which can leave you with an invalid token and force the user to reconnect their account.
Things get even more complicated when you're building an agent that reads emails, GitHub issues and web pages containing text written by other people. You have to be careful what the model can access because credentials can accidentally end up in its context window, execution logs, or error messages, and someone could plant instructions in an email or webpage to trick the agent into exposing them.
TL;DR
Coding agents can generate OAuth flows, but you still have to handle provider approvals, token refreshes, credential storage, and security.
Composio's auth-only mode handles authentication while letting you use your own tools, MCP servers and application logic.
Users connect their accounts through a hosted Connect Link, and your tools make authenticated API calls through
proxy_execute.Composio attaches the credentials and returns the API response without exposing OAuth tokens to your application or agent.
You can reuse the same authentication implementation across providers and focus on building your integrations.
What you need from an auth service: DIY auth vs managed auth vs auth-proxy
Ideally, you'd have a service that handles getting applications approved by OAuth providers, securely storing user tokens, and refreshing them before they expire. If you're building an agent, you'd also want to keep the tokens outside the agent's environment so that the model never has access to them in the first place.
There are generally three ways to handle authentication for integrations.
The first is to build and maintain everything yourself. This gives you full control over how authentication works in your application, but you're also responsible for provider approvals, handling token refreshes and securing the tokens you store.
The second is to use a managed auth service that handles the OAuth flow, stores the tokens and refreshes them when needed. Whenever your application needs to make an API call, it retrieves the user's access token from the service and makes the request. This saves considerable development and maintenance work, although anyone with access to the service's secret key could potentially retrieve the user's tokens.
The third is to use a proxy that makes authenticated API calls on your behalf. When your application needs to fetch a user's GitHub profile, for example, it sends a
GET /userrequest through the proxy, which attaches the user's credentials, makes the API call and returns the response. Your application can interact with GitHub without ever retrieving or handling the user's access token.
Build it yourself | Managed auth | Auth proxy | |
|---|---|---|---|
Automatic token refresh | No | Yes | Yes |
External token storage | No | Yes | Yes |
Application handles raw tokens | Yes | Yes | No |
Risk of exposing tokens to the agent | Yes | Yes | Reduced |
Composio handles the OAuth flows and token storage and refreshes, and lets you make authenticated API calls through its proxy. You can also use its managed OAuth applications for supported integrations instead of registering and getting your own applications approved by each provider. When you need your own branding on the consent screen, custom scopes or dedicated rate limits, you can switch to your own OAuth app later, though existing users will need to reconnect.
The diagram below shows how the authentication flow changes when you use Composio. Instead of registering an OAuth app, implementing callbacks and managing tokens yourself, you can generate a Connect Link for your users and make authenticated API calls through Composio's proxy.

How does auth-proxy mode work?
Composio gives you a hosted page called a Connect Link where your users can sign in to a provider and grant access to their accounts. As shown below, your app calls authorize() to generate the link. After the user approves access, GitHub redirects back to Composio, which exchanges the code for tokens and stores them against the connected account. Once the connection is active, your app can identify the account without receiving the token and make authenticated API calls through proxy_execute.

Connecting the user
To connect an account, create a Composio session with the user ID you already use in your application and generate a Connect Link for the provider.
from composio import Composio
<p>composio = Composio()
session = composio.create(user_id="user_123", toolkits=["github"])</p>
<p>connection_request = session.authorize("github")
print(connection_request.redirect_url) # send this to your user</p>
<p>connected_account = connection_request.wait_for_connection(60) # seconds</p>import { Composio } from '@composio/core';<p></p>
<p>const composio = new Composio();
const session = await composio.create('user_123', { toolkits: ['github'] });</p>
<p>const connectionRequest = await session.authorize('github');
console.log(connectionRequest.redirectUrl); // send this to your user</p>
<p>const connectedAccount = await connectionRequest.waitForConnection(60000);</p>You can send this link to your user, who can then sign in to GitHub and grant the required permissions. Your application waits for the connection status to become ACTIVE and handles unsuccessful connection states such as FAILED, EXPIRED or REVOKED.
Composio stores the access and refresh tokens in encrypted storage against the connected account for user_123 and takes care of refreshing them. The credential fields are redacted when you retrieve the connected account through the API, keeping the raw tokens outside your application when using auth-only mode.
Making an API call
You can continue using the provider's API documentation to construct your requests and make them through Composio's proxy_execute method.
response = session.proxy_execute(
toolkit="github",
endpoint="/repos/composiohq/composio/issues/1",
method="GET",
parameters=[
{
"name": "Accept",
"value": "application/vnd.github.v3+json",
"in": "header",
},
],
)const response = await session.proxyExecute({
toolkit: 'github',
endpoint: '/repos/composiohq/composio/issues/1',
method: 'GET',
parameters: [
{ name: 'Accept', value: 'application/vnd.github.v3+json', in: 'header' },
],
});The endpoint is relative to the provider's API base URL, and since Composio already has the user's credentials, you don't need to provide an Authorization header. You can specify the HTTP method, pass a JSON body for write operations and include any additional headers or query parameters that the provider supports.

As the diagram above shows, Composio finds the connected account using the user ID and toolkit, checks that the request is going to the provider's domain, and attaches the token server-side. It then sends the request to GitHub and returns the status, data and headers to your tool when the result is completed. A completed result means the provider returned an HTTP response, so check the status code to determine whether the request succeeded. A blocked result may also occur after an upstream operation has executed, so do not automatically retry it.
if response["result_type"] == "completed":
print(response["status"])
print(response["data"])
print(response["headers"])
else:
print("Request blocked:", response)if (response.resultType === 'completed') {
console.log(response.status); // GitHub's status code
console.log(response.data); // GitHub's JSON body
console.log(response.headers); // GitHub's response headers
} else {
console.log('Request blocked:', response);
}For requests that return files, Composio provides a short-lived download URL in binary_data. You can also handle HTTP errors as you normally would when working with GitHub's API. A 401 could indicate that the user's credentials are no longer valid, while a 429 indicates that you've hit GitHub's rate limit.
Composio does not automatically retry these requests, which is particularly useful for write operations where retrying a timed-out request could result in duplicate issues or other unintended changes.
Using auth-only mode with agents

If you've already built your own tools for an agent, you can use proxy_execute within their implementations. In the diagram above, the agent calls your get_issue tool, which sends the request through Composio. Composio attaches the token and returns GitHub's response to your tool, while the token stays outside your application.
def get_issue(user_id: str, repo: str, number: int):
session = composio.create(user_id=user_id, toolkits=["github"])<p></p>
<pre><code>response = session.proxy_execute(
toolkit="github",
endpoint=f"/repos/{repo}/issues/{number}",
method="GET",
)
if response["result_type"] != "completed":
raise RuntimeError("Proxy request blocked")
if not 200 <= response["status"] < 300:
raise RuntimeError(f"GitHub returned {response['status']}")
return response["data"]</code></pre><pre data-language="TypeScript"><code>async function getIssue(userId: string, repo: string, number: number) {
const session = await composio.create(userId, { toolkits: ['github'] });
const response = await session.proxyExecute({
toolkit: 'github',
endpoint: /repos/${repo}/issues/${number},
method: 'GET',
});
if (response.resultType !== 'completed') {
throw new Error('Proxy request blocked');
}
if (response.status < 200 || response.status >= 300) {
throw new Error(GitHub returned ${response.status});
}
return response.data; }
When the agent calls get_issue, Composio makes the authenticated request to GitHub and the tool returns the issue to the model. Since your application doesn't retrieve the user's access token, you avoid accidentally exposing it through the model's context window, application logs or error messages.
You should also obtain the user_id from your application's authenticated session and inject it into the tool at execution time rather than letting the model specify it. This prevents the model from selecting another user's connected account. You still need to enforce permissions on which operations the agent can perform, since a prompt injection could attempt to misuse the tools even without access to the underlying credentials.
Building the same integration with and without Composio
To see how much code Composio replaces, let's implement the get_issue tool from the previous section using GitHub's API directly. For this example, we're using a GitHub App with expiring user access tokens, which is the default for new GitHub Apps.
import os, secrets, time, httpx
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import RedirectResponse<p></p>
<p>app = FastAPI()
CLIENT_ID = os.environ["GITHUB_CLIENT_ID"]
CLIENT_SECRET = os.environ["GITHUB_CLIENT_SECRET"]</p>
<h1>1. Redirect the user to GitHub</h1>
<p>@app.get("/connect/github")
def connect(request: Request):
state = secrets.token_urlsafe(32)
request.session["oauth_state"] = state
return RedirectResponse(
f"<<a href="https://github.com/login/oauth/authorize?client_id=%7BCLIENT_ID%7D&state=%7Bstate%7D">https://github.com/login/oauth/authorize?client_id={CLIENT_ID}&state={state}</a>>"
)</p>
<h1>2. Exchange the authorization code for tokens</h1>
<p>@app.get("/callback/github")
def callback(request: Request, code: str, state: str):
if state != request.session.pop("oauth_state", None):
raise HTTPException(400, "state mismatch")
tokens = httpx.post(
"<<a href="https://github.com/login/oauth/access_token">https://github.com/login/oauth/access_token</a>>",
data={"client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "code": code},
headers={"Accept": "application/json"},
).json()
save_tokens(current_user_id(request), tokens)
return RedirectResponse("/settings?connected=github")</p>
<h1>3. Retrieve and refresh the access token</h1>
<p>def get_token(user_id: str) -> str:
with db.transaction():
row = db.select_for_update("tokens", user_id=user_id)
if row.expires_at > time.time() + 60:
return decrypt(row.access_token)
tokens = httpx.post(
"<<a href="https://github.com/login/oauth/access_token">https://github.com/login/oauth/access_token</a>>",
data={
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"grant_type": "refresh_token",
"refresh_token": decrypt(row.refresh_token),
},
headers={"Accept": "application/json"},
).json()
if "error" in tokens:
mark_disconnected(user_id)
raise NeedsReconnect("github")
save_tokens(user_id, tokens)
return tokens["access_token"]</p>
<h1>4. Fetch the GitHub issue</h1>
<p>def get_issue(user_id: str, repo: str, number: int):
response = httpx.get(
f"<<a href="https://api.github.com/repos/%7Brepo%7D/issues/%7Bnumber%7D">https://api.github.com/repos/{repo}/issues/{number}</a>>",
headers={
"Authorization": f"Bearer {get_token(user_id)}",
"Accept": "application/vnd.github.v3+json",
},
)
return response.json()</p>We've left out quite a bit of the implementation here. You still need to create a database table for the tokens, implement encryption and manage the encryption keys, configure session middleware, and build a UI that lets users reconnect their accounts when their credentials are no longer valid. You also need to register your application with GitHub and securely store its client secret before you can run any of this.
If you decide to add Slack or Google Drive to your application, you'll have to implement much of this again, depending on how each provider handles authentication and token refreshes.
Here's the same implementation using Composio.
from composio import Composio<p></p>
<p>composio = Composio()</p>
<p>def connect_github(user_id: str) -> str:
session = composio.create(user_id=user_id, toolkits=["github"])
return session.authorize("github").redirect_url</p>
<p>def get_issue(user_id: str, repo: str, number: int):
session = composio.create(user_id=user_id, toolkits=["github"])
response = session.proxy_execute(
toolkit="github",
endpoint=f"/repos/{repo}/issues/{number}",
method="GET",
)
if response["result_type"] != "completed":
raise RuntimeError("Proxy request blocked")</p>
<pre><code>if not 200 <= response["status"] < 300:
raise RuntimeError(f"GitHub returned {response['status']}")
return response["data"]</code></pre><pre data-language="TypeScript"><code>import { Composio } from '@composio/core';
const composio = new Composio();
async function connectGitHub(userId: string) { const session = await composio.create(userId, { toolkits: ['github'] }); const connectionRequest = await session.authorize('github'); return connectionRequest.redirectUrl; }
async function getIssue(userId: string, repo: string, number: number) {
const session = await composio.create(userId, { toolkits: ['github'] });
const response = await session.proxyExecute({
toolkit: 'github',
endpoint: /repos/${repo}/issues/${number},
method: 'GET',
});
if (response.resultType !== 'completed') {
throw new Error('Proxy request blocked');
}
if (response.status < 200 || response.status >= 300) {
throw new Error(GitHub returned ${response.status});
}
return response.data; }
Since Composio handles the OAuth flow, credential storage and token refreshes, you don't need to implement any of that in your application. You can use Composio's managed OAuth application for GitHub, generate a Connect Link for your users and start making API calls once they've connected their accounts.
The same approach works for other supported providers, so adding Slack would largely involve looking up the Slack API endpoints you need and making those requests through proxy_execute. You can reuse the authentication implementation across integrations while continuing to build your own tools around each provider's API.
Security
One of the more time-consuming parts of building OAuth integrations is securing the credentials. Depending on the permissions your users grant, someone who gains access to their tokens could read their emails, access private GitHub repositories, or send messages on Slack. You need to encrypt the tokens, manage the encryption keys, restrict database access, and make sure credentials don't accidentally end up in application logs or error trackers. If you're selling to enterprise customers, you'll also have to document these security measures and go through security reviews.
Composio encrypts provider credentials at rest using AES-256-GCM, stores API keys and session keys as hashes, and uses TLS for data in transit. It has also completed a SOC 2 Type II audit and is ISO/IEC 27001:2022 certified, which saves you some of the work involved in meeting enterprise security requirements.
When you manage OAuth yourself, your application needs to decrypt and read the access tokens to make API calls. This leaves several opportunities for credentials to leak, whether through a compromised dependency, a vulnerability in your application or accidentally logging a request header. With Composio's auth-only mode, your application never retrieves the tokens. Even when you fetch a connected account through the API, the credential fields are redacted.
There are additional security considerations when building agents. For instance, if an agent can specify the URL that a tool makes an authenticated request to, a prompt injection could trick it into sending the credentials to an external server. Composio restricts proxy requests to the provider's API domain and isolates connected accounts by user ID. As long as you obtain the user ID from your application's authenticated session, the agent cannot select another user's connected account. Direct proxy access is also disabled for agents by default, and you can configure tools to require user approval before execution.
For customers with stricter data residency and infrastructure requirements, Composio offers BYOC deployments within your own AWS, Google Cloud or Azure account. You can also use customer-managed encryption keys to manage credential decryption through your own KMS and enable Zero Data Retention to limit the data retained in execution logs.
Keeping your own permissions, approvals and audit logs
If you've already built permission checks, approval workflows, and audit logs into your agent, you can use Composio for authentication without changing how any of these work. With auth-only mode, your tools continue to run within your application, and you use proxy_execute wherever you would normally make an authenticated HTTP request.
For example, suppose you've built a tool that lets your agent comment on a GitHub issue, but you need to check the user's permissions, get their approval and record the action in your audit log.
def comment_on_issue(ctx, repo: str, number: int, body: str):
require_permission(ctx.user, "github.comment")<p></p>
<pre><code>proposal = propose(ctx, f"Comment on {repo}#{number}: {body}")
if not proposal.approved:
return "dismissed"
session = composio.create(
user_id=ctx.user.id,
toolkits=["github"],
)
response = session.proxy_execute(
toolkit="github",
endpoint=f"/repos/{repo}/issues/{number}/comments",
method="POST",
body={"body": body},
)
if response["result_type"] != "completed":
audit_log.write(
ctx.user, "github.comment", repo, number, "blocked"
)
raise RuntimeError("Proxy request blocked")
audit_log.write(
ctx.user, "github.comment", repo, number, response["status"]
)
if not 200 <= response["status"] < 300:
raise RuntimeError(f"GitHub returned {response['status']}")
return response["data"]</code></pre><pre data-language="TypeScript"><code>async function commentOnIssue(ctx: Ctx, repo: string, number: number, body: string) {
await requirePermission(ctx.user, 'github.comment');
const proposal = await propose(ctx, Comment on ${repo}#${number}: ${body});
if (!proposal.approved) return 'dismissed';
const session = await composio.create(ctx.user.id, { toolkits: ['github'] });
const response = await session.proxyExecute({
toolkit: 'github',
endpoint: /repos/${repo}/issues/${number}/comments,
method: 'POST',
body: { body },
});
if (response.resultType !== 'completed') { await auditLog.write(ctx.user, 'github.comment', repo, number, 'blocked'); throw new Error('Proxy request blocked'); }
await auditLog.write(ctx.user, 'github.comment', repo, number, response.status);
if (response.status < 200 || response.status >= 300) {
throw new Error(GitHub returned ${response.status});
}
return response.data; }
Your application checks the user's permissions and waits for their approval before making the request through Composio. Once the request completes, you can record the response in your existing audit log. If your application supports undo operations, you can also use the proxy to make the corresponding API requests, provided the operation can be reversed through the provider's API.
You retain control over which actions your agent can perform, when it needs approval and what gets recorded in your application, while Composio handles authentication for the API requests.
Pricing
You can start using Composio for authentication for free, with unlimited connected accounts when you use your own OAuth applications. If you'd rather use Composio's pre-approved OAuth applications, your first 1,000 connections are also free.
The Pro plan starts at $29 per month, with the entire subscription amount available as usage credits.
Hobby | Pro | |
|---|---|---|
Monthly price | Free | $29 |
Monthly usage credits | — | $29 |
Tool calls included | 100,000 | 100,000 |
Managed OAuth app calls included* | 20,000 | 20,000 |
Proxy execution allowance | 1,000 | 1,000 |
Custom OAuth connections | Unlimited | Unlimited |
Managed OAuth connections included | 1,000 | 1,000 |
Managed OAuth app calls count toward the total tool call allowance.
To put this into perspective, if you have 1,000 users making 100 authenticated API requests each month, you can handle all 100,000 requests for $29 per month using your own OAuth application. If you use Composio's managed GitHub OAuth application, which saves you from registering and maintaining your own, the same usage would cost $59.80 per month.
Beyond the included allowances, proxy execution adds $0.20 per 1,000 requests to the applicable tool execution rate. Additional managed OAuth connections cost $0.10 per account as a one-time charge, so your authentication costs don't increase simply because you have more connected accounts.
You can also set spending caps on the Pro plan to keep your monthly bill within budget. Enterprise plans are available for teams that need custom usage limits, customer-managed encryption keys, SSO or dedicated deployment options.
For a full breakdown, see Composio's pricing page.
Conclusion
Claude can write your OAuth flow in ten minutes. What takes weeks is everything after that: getting the app approved, handling refresh for each provider, keeping the tokens safe, and now keeping them away from an agent that reads whatever it's given.
Auth-only mode hands that part to Composio. Your users connect through a Connect Link, your tools describe the request they want to make, and the response comes back without the token ever touching your code. You keep your own tools, your own MCP server and your own logic, and adding the next provider means changing a toolkit name and an endpoint.
If you want to try it, start with the managed auth for your own tools guide, then read the proxy execute docs for the full request and response shape.
