@devries-cameron20 / composio-1 / commits / 4f2f8e61d
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Add Authentication documentation section

- Add custom-auth-configs page for OAuth setup and white-labeling - Add programmatic-auth-configs page for SDK-based auth config creation - Add custom-auth-params page for injecting custom credentials - Add connected-accounts page for managing user connections lifecycle - Add user-management page covering User IDs, org patterns, and best practices - Add supporting images for OAuth configuration examples 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

Sushmithamallesh committed Dec 30, 2025 at 13:28 UTC 4f2f8e61d55ff0da8ac4556752e8b9af4143c4d4
15 files changed +1246 -1
fumadocs/content/docs/connected-accounts.mdx new
+299
@@ -0,0 +1,299 @@
1 +---
2 +title: Connected Accounts
3 +description: Manage and monitor user connections to toolkits
4 +---
5 +
6 +Connected accounts are authenticated connections between your users and toolkits. After users authenticate (see [Authenticating tools](/docs/authenticating-tools)), you can manage these accounts throughout their lifecycle.
7 +
8 +Composio automatically handles token refresh and credential management. This guide covers manual operations: listing, retrieving, refreshing, enabling, disabling, and deleting accounts.
9 +
10 +## List accounts
11 +
12 +Retrieve all connected accounts with optional filters:
13 +
14 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
15 + <Tab value="Python">
16 +```python
17 +# List all accounts for a user
18 +accounts = composio.connected_accounts.list(
19 + user_ids=[user_id]
20 +)
21 +
22 +# Filter by status
23 +active_accounts = composio.connected_accounts.list(
24 + user_ids=[user_id],
25 + statuses=["ACTIVE"]
26 +)
27 +```
28 + </Tab>
29 + <Tab value="TypeScript">
30 +```typescript
31 +// List all accounts for a user
32 +const accounts = await composio.connectedAccounts.list({
33 + userIds: [userId]
34 +});
35 +
36 +// Filter by status
37 +const activeAccounts = await composio.connectedAccounts.list({
38 + userIds: [userId],
39 + statuses: ['ACTIVE']
40 +});
41 +```
42 + </Tab>
43 +</Tabs>
44 +
45 +## Get account details
46 +
47 +Retrieve a connected account by ID:
48 +
49 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
50 + <Tab value="Python">
51 +```python
52 +account = composio.connected_accounts.get(connected_account_id)
53 +
54 +print(f"Status: {account.status}")
55 +print(f"Toolkit: {account.toolkit.slug}")
56 +```
57 + </Tab>
58 + <Tab value="TypeScript">
59 +```typescript
60 +const account = await composio.connectedAccounts.get(connectedAccountId);
61 +
62 +console.log('Status:', account.status);
63 +console.log('Toolkit:', account.toolkit.slug);
64 +```
65 + </Tab>
66 +</Tabs>
67 +
68 +### Get account credentials
69 +
70 +Get account credentials for use with your own tools:
71 +
72 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
73 + <Tab value="Python">
74 +```python
75 +# Get the connected account's authentication state
76 +if account.state:
77 + # The state contains the auth scheme and credentials
78 + auth_scheme = account.state.auth_scheme
79 + credentials = account.state.val
80 +
81 + print(f"Auth scheme: {auth_scheme}")
82 + print(f"Credentials: {credentials}")
83 +```
84 + </Tab>
85 + <Tab value="TypeScript">
86 +```typescript
87 +// Get the connected account's authentication state
88 +if (account.state) {
89 + // The state contains the auth scheme and credentials
90 + const authScheme = account.state.authScheme;
91 + const credentials = account.state.val;
92 +
93 + console.log('Auth scheme:', authScheme);
94 + console.log('Credentials:', credentials);
95 +}
96 +```
97 + </Tab>
98 +</Tabs>
99 +
100 +<Callout type="warn">
101 +If credentials return as `REDACTED` instead of actual values, the **Mask Connected Account Secrets** setting is enabled on your account. This setting redacts all sensitive credential data (tokens, secrets, API keys) for security purposes.
102 +
103 +To view actual credentials, navigate to **Settings → Project Settings → Project Configuration** and disable "Mask Connected Account Secrets".
104 +</Callout>
105 +
106 +## Refresh credentials
107 +
108 +Manually refresh credentials for a connected account:
109 +
110 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
111 + <Tab value="Python">
112 +```python
113 +try:
114 + refreshed = composio.connected_accounts.refresh(connected_account_id)
115 + print(f"Redirect URL: {refreshed.redirect_url}")
116 +
117 + # Wait for the connection to be established
118 + composio.connected_accounts.wait_for_connection(refreshed.id)
119 +except Exception as e:
120 + print(f"Failed to refresh tokens: {e}")
121 +```
122 + </Tab>
123 + <Tab value="TypeScript">
124 +```typescript
125 +try {
126 + const refreshed = await composio.connectedAccounts.refresh(connectedAccountId);
127 + console.log('Redirect URL:', refreshed.redirect_url);
128 +
129 + // Wait for the connection to be established
130 + await composio.connectedAccounts.waitForConnection(refreshed.id);
131 +} catch (error) {
132 + console.error('Failed to refresh tokens:', error);
133 +}
134 +```
135 + </Tab>
136 +</Tabs>
137 +
138 +## Enable and disable accounts
139 +
140 +Change account status without deleting. Set to INACTIVE to pause access, or ACTIVE to restore. Useful for:
141 +- Pausing access during subscription lapses
142 +- Temporary disconnection
143 +
144 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
145 + <Tab value="Python">
146 +```python
147 +# Disable an account
148 +disabled = composio.connected_accounts.disable(connected_account_id)
149 +print(f"Account disabled status: {disabled.success}")
150 +
151 +# Re-enable when needed
152 +enabled = composio.connected_accounts.enable(connected_account_id)
153 +print(f"Account enabled status: {enabled.success}")
154 +```
155 + </Tab>
156 + <Tab value="TypeScript">
157 +```typescript
158 +// Disable an account
159 +const disabled = await composio.connectedAccounts.disable(connectedAccountId);
160 +console.log('Account disabled status:', disabled.success);
161 +
162 +// Re-enable when needed
163 +const enabled = await composio.connectedAccounts.enable(connectedAccountId);
164 +console.log('Account enabled status:', enabled.success);
165 +```
166 + </Tab>
167 +</Tabs>
168 +
169 +<Callout type="warn">
170 +INACTIVE accounts cannot execute tools. Tool execution will fail until the status is changed.
171 +</Callout>
172 +
173 +## Delete accounts
174 +
175 +Permanently remove a connected account and revoke all credentials:
176 +
177 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
178 + <Tab value="Python">
179 +```python
180 +# Delete a connected account
181 +composio.connected_accounts.delete(connected_account_id)
182 +print("Account deleted successfully")
183 +```
184 + </Tab>
185 + <Tab value="TypeScript">
186 +```typescript
187 +// Delete a connected account
188 +await composio.connectedAccounts.delete(connectedAccountId);
189 +console.log('Account deleted successfully');
190 +```
191 + </Tab>
192 +</Tabs>
193 +
194 +<Callout type="warn">
195 +Deletion is permanent. Users must re-authenticate to reconnect.
196 +</Callout>
197 +
198 +## Multiple accounts
199 +
200 +Users can connect multiple accounts for the same toolkit (e.g., personal and work Gmail).
201 +
202 +<Callout type="info">
203 +Use `link()` for creating accounts, as it provides hosted authentication and allows multiple accounts by default. See [Connect Link authentication](/docs/authenticating-tools#hosted-authentication-connect-link).
204 +</Callout>
205 +
206 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
207 + <Tab value="Python">
208 +```python
209 +# First account
210 +try:
211 + first_account = composio.connected_accounts.initiate(
212 + user_id=user_id,
213 + auth_config_id=auth_config_id
214 + )
215 + print(f"First account redirect URL: {first_account.redirect_url}")
216 + connected_first_account = first_account.wait_for_connection()
217 + print(f"First account status: {connected_first_account.status}")
218 +except Exception as e:
219 + print(f"Error initiating first account: {e}")
220 +
221 +# Second account - must explicitly allow multiple
222 +try:
223 + second_account = composio.connected_accounts.initiate(
224 + user_id=user_id,
225 + auth_config_id=auth_config_id,
226 + allow_multiple=True # Required for additional accounts
227 + )
228 + print(f"Second account redirect URL: {second_account.redirect_url}")
229 + connected_second_account = second_account.wait_for_connection()
230 + print(f"Second account status: {connected_second_account.status}")
231 +except Exception as e:
232 + print(f"Error initiating second account: {e}")
233 +```
234 + </Tab>
235 + <Tab value="TypeScript">
236 +```typescript
237 +// First account
238 +try {
239 + const firstAccount = await composio.connectedAccounts.initiate(
240 + userId,
241 + authConfigId
242 + );
243 + console.log('First account redirect URL:', firstAccount.redirectUrl);
244 + const connectedFirstAccount = await firstAccount.waitForConnection();
245 + console.log('First account status:', connectedFirstAccount.status);
246 +} catch (error) {
247 + console.error('Error initiating first account:', error);
248 +}
249 +
250 +// Second account - must explicitly allow multiple
251 +try {
252 + const secondAccount = await composio.connectedAccounts.initiate(
253 + userId,
254 + authConfigId,
255 + {
256 + allowMultiple: true // Required for additional accounts
257 + }
258 + );
259 + console.log('Second account redirect URL:', secondAccount.redirectUrl);
260 + const connectedSecondAccount = await secondAccount.waitForConnection();
261 + console.log('Second account status:', connectedSecondAccount.status);
262 +} catch (error) {
263 + console.error('Error initiating second account:', error);
264 +}
265 +```
266 + </Tab>
267 +</Tabs>
268 +
269 +### Execute with a specific account
270 +
271 +When you have multiple accounts, specify which one to use with `connected_account_id`:
272 +
273 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
274 + <Tab value="Python">
275 +```python
276 +# Execute tool with a specific connected account
277 +result = composio.tools.execute(
278 + "GMAIL_GET_PROFILE",
279 + user_id=user_id,
280 + connected_account_id=connected_account_id, # Specify which account to use
281 + version="20251111_00",
282 + arguments={}
283 +)
284 +print(f"Tool executed: {result}")
285 +```
286 + </Tab>
287 + <Tab value="TypeScript">
288 +```typescript
289 +// Execute tool with a specific connected account
290 +const result = await composio.tools.execute('GMAIL_GET_PROFILE', {
291 + userId: userId,
292 + connectedAccountId: connectedAccountId, // Specify which account to use
293 + version: '20251111_00',
294 + arguments: {}
295 +});
296 +console.log('Tool executed:', result);
297 +```
298 + </Tab>
299 +</Tabs>
fumadocs/content/docs/custom-auth-configs.mdx new
+246
@@ -0,0 +1,246 @@
1 +---
2 +title: Custom Auth Configs
3 +description: Customize auth configs for any toolkit
4 +---
5 +
6 +Many toolkits support a level of customization for the auth config, specifically OAuth applications.
7 +
8 +This guide will walk you through the process of customizing the auth config for toolkits where you can configure your own developer app.
9 +
10 +## Creating a custom auth config
11 +
12 +To create a custom auth config, click **Create Auth Config** in your dashboard, then navigate to **Authentication management** → **Manage authentication with custom credentials**.
13 +
14 +You'll need to customize the auth config when you want to use different values than the defaults - such as your own subdomain, base URL, client ID, client secret, etc.
15 +
16 +<Tabs items={['Example: PostHog', 'Example: Hubspot']}>
17 + <Tab value="Example: PostHog">
18 +You may change the subdomain for the PostHog toolkit to match your own instance.
19 +
20 +<Figure src="/images/custom-auth-posthog.png" alt="PostHog Auth Config Settings" caption="PostHog Auth Config Settings" size="sm" />
21 + </Tab>
22 + <Tab value="Example: Hubspot">
23 +For Hubspot you may customize everything here. For each auth scheme there is a different set of fields.
24 +
25 +If you choose to use your own developer app for the OAuth2 scheme, you will have to provide the client ID and client secret.
26 +
27 +<Figure src="/images/custom-auth-hubspot.png" alt="Hubspot Auth Config Settings" caption="Hubspot Auth Config Settings" size="sm" />
28 + </Tab>
29 +</Tabs>
30 +
31 +Toolkits that support OAuth2 allow using your own developer app. This is the recommended approach for most cases.
32 +
33 +<Callout type="info" title="Use your own developer app!">
34 +We recommend using your own developer app for the OAuth2 scheme as it is more suited for production usage with many users and more granular control over scopes.
35 +
36 +However, getting OAuth approvals takes time, so Composio provides a default developer app!
37 +</Callout>
38 +
39 +## OAuth2 Auth Configs
40 +
41 +<Steps>
42 +<Step>
43 +### Generate the OAuth Client ID and Client Secret
44 +
45 +To set up a custom OAuth config, you'll need the OAuth Client ID and Client Secret.
46 +
47 +You can generate the client ID and client secret from your provider's OAuth configuration page.
48 +
49 +Examples for Google and GitHub:
50 +
51 +<Tabs items={['Google', 'GitHub']}>
52 + <Tab value="Google">
53 +<Figure src="/images/google-oauth-config.png" alt="Google OAuth Configuration" caption="Google OAuth Configuration" size="sm" />
54 + </Tab>
55 + <Tab value="GitHub">
56 +<Figure src="/images/github-oauth-config.png" alt="GitHub OAuth Configuration" caption="GitHub OAuth Configuration" size="sm" />
57 + </Tab>
58 +</Tabs>
59 +</Step>
60 +
61 +<Step>
62 +### Set the Authorized Redirect URI
63 +
64 +When creating your OAuth app, make sure to configure the Authorized Redirect URI to point to the Composio callback URL below:
65 +
66 +```
67 +https://backend.composio.dev/api/v3/toolkits/auth/callback
68 +```
69 +</Step>
70 +
71 +<Step>
72 +### Create the auth config
73 +
74 +Once you have the OAuth credentials, you can add them to the auth config in the dashboard.
75 +
76 +1. Select the OAuth2 scheme.
77 +2. Select the scopes to request from users. Default scopes are pre-filled for most apps.
78 +3. Add the OAuth client ID and client secret for your developer app. Keep the redirect URL as is for now!
79 +4. Click Create!
80 +
81 +<Figure src="/images/integration-step-3-0.png" alt="Auth Config Settings" caption="Auth Config Settings" size="sm" />
82 +</Step>
83 +</Steps>
84 +
85 +This auth config is now ready to be used in your application!
86 +
87 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
88 + <Tab value="Python">
89 +```python
90 +# Create a new connected account
91 +connection_request = composio.connected_accounts.initiate(
92 + user_id="user_id",
93 + auth_config_id="ac_1234",
94 +)
95 +print(connection_request)
96 +
97 +# Wait for the connection to be established
98 +connected_account = connection_request.wait_for_connection()
99 +print(connected_account)
100 +```
101 + </Tab>
102 + <Tab value="TypeScript">
103 +```typescript
104 +const connReq = await composio.connectedAccounts.initiate(userId, "ac_1234");
105 +
106 +console.log(connReq.redirectUrl);
107 +
108 +const connection = await composio.connectedAccounts.waitForConnection(
109 + connReq.id
110 +);
111 +
112 +console.log(connection);
113 +```
114 + </Tab>
115 +</Tabs>
116 +
117 +### White-labeling the OAuth Consent Screen
118 +
119 +By default the users will see an OAuth screen like the one below:
120 +
121 +<Figure src="/images/oauth-branding.png" alt="Composio's Domain in OAuth Consent Screen" caption="Composio's Domain in OAuth Consent Screen" size="sm" />
122 +
123 +The OAuth redirect URL is surfaced in some OAuth providers' consent screens. This may cause confusion for some users as that URL is not of the same domain as the application.
124 +
125 +To remediate this:
126 +
127 +<Steps>
128 +<Step>
129 +### Set the Authorized Redirect URI
130 +
131 +Specify the Authorized Redirect URI to your own domain in the OAuth configuration.
132 +For example:
133 +```
134 +https://yourdomain.com/api/composio-redirect
135 +```
136 +</Step>
137 +
138 +<Step>
139 +### Create a redirect logic
140 +
141 +Create a redirect logic, either through your DNS or in your application to redirect that endpoint to `https://backend.composio.dev/api/v3/toolkits/auth/callback`
142 +
143 +**Example: API Route for OAuth Redirect**
144 +
145 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
146 + <Tab value="Python">
147 +```python
148 +from fastapi import FastAPI
149 +from fastapi.responses import RedirectResponse
150 +
151 +from composio import Composio
152 +
153 +# Create a FastAPI app
154 +app = FastAPI()
155 +
156 +# Create a Composio client
157 +composio = Composio()
158 +
159 +
160 +@app.get("/authorize/{toolkit}")
161 +def authorize_app(toolkit: str):
162 + # retrieve the user id from your app
163 + user_id = "<user_id>"
164 +
165 + # retrieve the auth config id from your app
166 + auth_config_id = "<auth_config_id>"
167 +
168 + # initiate the connection request
169 + connection_request = composio.connected_accounts.initiate(
170 + user_id=user_id,
171 + auth_config_id=auth_config_id,
172 + )
173 + return RedirectResponse(url=connection_request.redirect_url)
174 +```
175 + </Tab>
176 + <Tab value="TypeScript">
177 +```typescript
178 +import type { NextApiRequest, NextApiResponse } from 'next';
179 +
180 +export default function handler(req: NextApiRequest, res: NextApiResponse) {
181 + // The target Composio endpoint that handles OAuth callbacks
182 + const composioEndpoint = 'https://backend.composio.dev/api/v3/toolkits/auth/callback';
183 +
184 + // Extract and preserve all query parameters
185 + const queryParams = new URLSearchParams();
186 + Object.entries(req.query).forEach(([key, value]) => {
187 + if (typeof value === 'string') {
188 + queryParams.append(key, value);
189 + }
190 + });
191 +
192 + // Redirect to Composio with all query parameters intact
193 + const redirectUrl = `${composioEndpoint}?${queryParams.toString()}`;
194 + res.redirect(302, redirectUrl);
195 +}
196 +```
197 + </Tab>
198 +</Tabs>
199 +</Step>
200 +
201 +<Step>
202 +### Create the auth config
203 +
204 +Specify your custom redirect URI in the auth config settings!
205 +
206 +<Figure src="/images/custom-redirect-uri.png" alt="Auth Config Settings" caption="Auth Config Settings" size="sm" />
207 +</Step>
208 +</Steps>
209 +
210 +With this setup, you can use `https://yourdomain.com/api/composio-redirect` as your OAuth redirect URI, which will create a better user experience by keeping users on your domain during the OAuth flow.
211 +
212 +<Accordions>
213 +<Accordion title="How does this work?">
214 +
215 +The custom OAuth config allows you to use your own domain in the OAuth consent screen instead of Composio's domain. Here's the core difference:
216 +
217 +```mermaid
218 +flowchart TD
219 + A[Your App initiates OAuth] --> B[User redirected to OAuth Provider]
220 + B --> C{Redirect URI Configuration}
221 +
222 + C -->|Direct Setup| D[Provider redirects to<br/>backend.composio.dev]
223 + C -->|Custom Domain| E[Provider redirects to<br/>yourdomain.com/api/composio-redirect]
224 +
225 + E --> F[Your endpoint forwards to<br/>backend.composio.dev]
226 +
227 + D --> G[Composio exchanges code for token]
228 + F --> G
229 +
230 + G --> H[Connection established]
231 +
232 + style E fill:#e1f5fe
233 + style F fill:#e1f5fe
234 + style C fill:#fff3e0
235 +```
236 +
237 +**Key Benefits:**
238 +
239 +- **Custom Domain**: Users see your domain in OAuth consent screens, not Composio's
240 +- **Same Security**: Your domain just forwards the OAuth callback - no token handling
241 +- **Better UX**: Maintains brand consistency throughout the auth flow
242 +
243 +The custom redirect endpoint is a simple passthrough that preserves all OAuth parameters while keeping users on your domain.
244 +
245 +</Accordion>
246 +</Accordions>
fumadocs/content/docs/custom-auth-params.mdx new
+131
@@ -0,0 +1,131 @@
1 +---
2 +title: Custom Auth Parameters
3 +description: Inject custom credentials in headers or parameters
4 +---
5 +
6 +In cases where Composio is not being used for managing the auth but only for the tools, it is possible to use the `beforeExecute` hook to inject custom auth headers or parameters for a toolkit.
7 +
8 +## Setup and Initialization
9 +
10 +First, initialize the Composio SDK with your API key:
11 +
12 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
13 + <Tab value="Python">
14 +```python
15 +from composio import Composio
16 +
17 +composio = Composio()
18 +```
19 + </Tab>
20 + <Tab value="TypeScript">
21 +```typescript
22 +import { Composio } from "@composio/core";
23 +
24 +const composio = new Composio({
25 + apiKey: process.env.COMPOSIO_API_KEY,
26 +});
27 +```
28 + </Tab>
29 +</Tabs>
30 +
31 +## Creating the Auth Modifier Function
32 +
33 +Define a function that modifies authentication parameters for specific toolkits. This function checks the toolkit name and adds custom authentication headers when needed.
34 +
35 +<Card title="This is a Before Execute Modifier!" href="/docs/modify-tool-behavior/before-execution-modifiers">
36 +Before Execute Modifiers are a way to modify the parameters of a tool before it is executed. In this case, they are useful for adding custom authentication headers or parameters to a tool.
37 +</Card>
38 +
39 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
40 + <Tab value="Python">
41 +```python
42 +from composio import before_execute
43 +from composio.types import ToolExecuteParams
44 +
45 +
46 +@before_execute(toolkits=["NOTION"])
47 +def add_custom_auth(
48 + tool: str,
49 + toolkit: str,
50 + params: ToolExecuteParams,
51 +) -> ToolExecuteParams:
52 + if params["custom_auth_params"] is None:
53 + params["custom_auth_params"] = {"parameters": []}
54 +
55 + params["custom_auth_params"]["parameters"].append(
56 + {
57 + "name": "x-api-key",
58 + "value": os.getenv("NOTION_API_KEY"),
59 + "in": "header",
60 + }
61 + )
62 + return params
63 +```
64 + </Tab>
65 + <Tab value="TypeScript">
66 +```typescript
67 +const authModifier = (toolSlug: string, toolkitSlug: string, params: any) => {
68 + // Add authentication parameters for specific toolkits
69 + if (toolkitSlug === "NOTION") {
70 + if (!params.customAuthParams) {
71 + params.customAuthParams = {};
72 + }
73 +
74 + if (!params.customAuthParams.parameters) {
75 + params.customAuthParams.parameters = [];
76 + }
77 +
78 + // Add an API key to the headers
79 + params.customAuthParams.parameters.push({
80 + in: "header",
81 + name: "X-API-Key",
82 + value: process.env.CUSTOM_API_KEY,
83 + });
84 + }
85 + return params;
86 +};
87 +```
88 + </Tab>
89 +</Tabs>
90 +
91 +## Executing Tools with Custom Auth
92 +
93 +Execute the tool using the custom authentication modifier. The `beforeExecute` hook allows you to modify parameters before the tool runs.
94 +
95 +Following is an example of how to execute a tool with a custom authentication modifier for Completion Providers.
96 +
97 +For Agentic Providers, read about [Modifying tool inputs](/docs/modify-tool-behavior/before-execution-modifiers).
98 +
99 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
100 + <Tab value="Python">
101 +```python
102 +result = composio.tools.execute(
103 + slug="NOTION_GET_DATABASE_ITEMS",
104 + user_id="default",
105 + arguments={},
106 + modifiers=[
107 + add_custom_auth,
108 + ],
109 +)
110 +print(result)
111 +```
112 + </Tab>
113 + <Tab value="TypeScript">
114 +```typescript
115 +const result = await composio.tools.execute(
116 + "NOTION_GET_DATABASE_ITEMS",
117 + {
118 + userId: "sid",
119 + arguments: {
120 + database_id: "1234567890",
121 + },
122 + },
123 + {
124 + beforeExecute: authModifier,
125 + }
126 +);
127 +
128 +console.log(JSON.stringify(result, null, 2));
129 +```
130 + </Tab>
131 +</Tabs>
fumadocs/content/docs/meta.json
+7 -1
@@ -11,6 +11,12 @@
11 "using-triggers",
12 "modify-tool-behavior",
13 "custom-tools",
14 - "toolkit-versioning"
14 + "toolkit-versioning",
15 + "---Authentication---",
16 + "custom-auth-configs",
17 + "programmatic-auth-configs",
18 + "custom-auth-params",
19 + "connected-accounts",
20 + "user-management"
21 ]
22 }
fumadocs/content/docs/programmatic-auth-configs.mdx new
+239
@@ -0,0 +1,239 @@
1 +---
2 +title: Programmatic Auth Configs
3 +description: Create auth configs programmatically
4 +---
5 +
6 +Auth configs are created once and reused many times. However, when managing multiple toolkits, you may want to create auth configs programmatically.
7 +
8 +- When creating and destroying auth configs multiple times in your app's lifecycle.
9 +- When creating auth configs for your users' users.
10 +
11 +## OAuth2 based apps
12 +
13 +### Using Composio Default Auth
14 +
15 +Since OAuth2 is the most common authentication type for applications, Composio provides managed auth for most OAuth2 based applications. This is to speed up development and prototyping. This means you don't have to provide your own OAuth credentials.
16 +
17 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
18 + <Tab value="Python">
19 +```python
20 +from composio import Composio
21 +
22 +composio = Composio()
23 +
24 +# Use composio managed auth
25 +auth_config = composio.auth_configs.create(
26 + toolkit="github",
27 + options={
28 + "type": "use_composio_managed_auth",
29 + },
30 +)
31 +print(auth_config)
32 +```
33 + </Tab>
34 + <Tab value="TypeScript">
35 +```typescript
36 +import { Composio } from "@composio/core";
37 +
38 +const composio = new Composio();
39 +
40 +const authConfig = await composio.authConfigs.create("GITHUB", {
41 + name: "GitHub",
42 + type: "use_composio_managed_auth",
43 +});
44 +
45 +console.log(authConfig);
46 +```
47 + </Tab>
48 +</Tabs>
49 +
50 +The returned `auth_config_id` should be stored securely in your database for future use to be created and destroyed multiple times.
51 +
52 +You can also provide your own authentication details. The required `credentials` and `authScheme` depend on the auth type.
53 +
54 +### Using your own OAuth2 credentials
55 +
56 +Setting up and using your own OAuth2 credentials is the recommended way when going to production or expecting high usage.
57 +
58 +In this example, we're using our own OAuth2 client ID and secret to create the auth config for Notion.
59 +
60 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
61 + <Tab value="Python">
62 +```python
63 +# Use custom auth
64 +auth_config = composio.auth_configs.create(
65 + toolkit="notion",
66 + options={
67 + "name": "Notion Auth",
68 + "type": "use_custom_auth",
69 + "auth_scheme": "OAUTH2",
70 + "credentials": {
71 + "client_id": "1234567890",
72 + "client_secret": "1234567890",
73 + "oauth_redirect_uri": "https://backend.composio.dev/api/v3/toolkits/auth/callback",
74 + },
75 + },
76 +)
77 +print(auth_config)
78 +```
79 + </Tab>
80 + <Tab value="TypeScript">
81 +```typescript
82 +const authConfig = await composio.authConfigs.create("NOTION", {
83 + name: "Notion",
84 + type: "use_custom_auth",
85 + credentials: {
86 + client_id: "1234567890",
87 + client_secret: "1234567890",
88 + oauth_redirect_uri: "https://backend.composio.dev/api/v3/toolkits/auth/callback",
89 + },
90 + authScheme: "OAUTH2",
91 +});
92 +
93 +console.log(authConfig);
94 +```
95 + </Tab>
96 +</Tabs>
97 +
98 +<Callout type="info">
99 +You can specify a custom redirect URI by including the `oauth_redirect_uri` parameter in the credentials object. If not provided, Composio uses the default redirect URI.
100 +</Callout>
101 +
102 +**Specifying the authorized redirect URI**
103 +
104 +The process of setting up your own OAuth2 credentials usually involves generating a client ID and secret and specifying the **authorized redirect URI** in the OAuth configuration.
105 +
106 +<Callout type="info">
107 +The **authorized redirect URI** is the URI that captures the OAuth code that is returned to the app.
108 +</Callout>
109 +
110 +While doing so, you must ensure to set the **authorized redirect URI** in the OAuth configuration to:
111 +
112 +```
113 +https://backend.composio.dev/api/v3/toolkits/auth/callback
114 +```
115 +
116 +<Tabs items={['GitHub', 'Google']}>
117 + <Tab value="GitHub">
118 +<Figure src="/images/github-callback.png" alt="Developer settings for GitHub OAuth2 app" caption="Redirect URI for GitHub" size="sm" />
119 + </Tab>
120 + <Tab value="Google">
121 +<Figure src="/images/google-callback.png" alt="Developer settings for Google OAuth2 app" caption="Redirect URI for Google" size="sm" />
122 + </Tab>
123 +</Tabs>
124 +
125 +### Specifying scopes
126 +
127 +Composio requests a set of appropriate default OAuth2 scopes for each toolkit wherever possible. However, you can override or modify these scopes by passing a `scopes` field to the `credentials` object.
128 +
129 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
130 + <Tab value="Python">
131 +```python
132 +from composio import Composio
133 +
134 +composio = Composio()
135 +
136 +response = composio.auth_configs.create(
137 + toolkit="HUBSPOT",
138 + options={
139 + "name": "HubspotConfig",
140 + "authScheme": "OAUTH2",
141 + "type": "use_composio_managed_auth",
142 + "credentials": {
143 + "scopes": "sales-email-read,tickets"
144 + }
145 + }
146 +)
147 +
148 +print(response.id)
149 +```
150 + </Tab>
151 + <Tab value="TypeScript">
152 +```typescript
153 +import { Composio } from "@composio/core";
154 +
155 +const composio = new Composio();
156 +
157 +const authConfig = await composio.authConfigs.create("HUBSPOT", {
158 + name: "HubspotConfig",
159 + type: "use_composio_managed_auth",
160 + credentials: {
161 + scopes: "sales-email-read,tickets",
162 + },
163 +});
164 +
165 +console.log(authConfig);
166 +```
167 + </Tab>
168 +</Tabs>
169 +
170 +## Other auth types
171 +
172 +Composio supports many applications that use different authentication types like API keys, Bearer tokens, JWT and even no authentication at all.
173 +
174 +Generating the auth config for other auth types only has minor differences:
175 +- `use_custom_auth` is used instead of `use_composio_managed_auth`
176 +- The `credentials` field is used to pass the authentication details
177 +- The `authScheme` field is used to specify the auth type
178 +
179 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
180 + <Tab value="Python">
181 +```python
182 +# Use custom auth
183 +auth_config = composio.auth_configs.create(
184 + toolkit="perplexityai",
185 + options={
186 + "type": "use_custom_auth",
187 + "auth_scheme": "API_KEY",
188 + "credentials": {}
189 + },
190 +)
191 +print(auth_config)
192 +```
193 + </Tab>
194 + <Tab value="TypeScript">
195 +```typescript
196 +const authConfig = await composio.authConfigs.create('PERPLEXITYAI', {
197 + name: 'Perplexity AI',
198 + type: 'use_custom_auth',
199 + credentials: {},
200 + authScheme: 'API_KEY',
201 +});
202 +
203 +console.log(authConfig);
204 +```
205 + </Tab>
206 +</Tabs>
207 +
208 +## Programmatically inspecting fields
209 +
210 +In cases where you need to dynamically discover the exact field names and handle different auth schemes programmatically, you can inspect the auth config details first.
211 +
212 +This works for all auth types.
213 +
214 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
215 + <Tab value="Python">
216 +```python
217 +required_fields = composio.toolkits.get_auth_config_creation_fields(
218 + toolkit="NOTION",
219 + auth_scheme="OAUTH2",
220 + required_only=True,
221 +)
222 +print(required_fields)
223 +```
224 + </Tab>
225 + <Tab value="TypeScript">
226 +```typescript
227 +const toolkits = await composio.toolkits.get("NOTION");
228 +
229 +// Extract field names from authConfigDetails
230 +const authFields = await composio.toolkits.getAuthConfigCreationFields('NOTION', 'OAUTH2', {
231 + requiredOnly: true,
232 +});
233 +
234 +console.log("Required auth config fields:", authFields);
235 +```
236 + </Tab>
237 +</Tabs>
238 +
239 +Then inspect the required fields and specify them in the `credentials` object.
fumadocs/content/docs/user-management.mdx new
+324
@@ -0,0 +1,324 @@
1 +---
2 +title: User Management
3 +description: Manage users and their connected accounts
4 +---
5 +
6 +## What are User IDs?
7 +
8 +User IDs determine whose connected accounts and data you're accessing in Composio. Every tool execution, connection authorization, and account operation requires a `userId` parameter that identifies which context to use.
9 +
10 +User IDs act as containers that group connected accounts together across toolkits. Depending on your application, you can use User IDs to represent an individual user, a team, or an entire organization.
11 +
12 +## Quick Decision Guide
13 +
14 +**How do users access connected accounts in your app?**
15 +
16 +- **Each user connects their own personal accounts?**
17 + Use User IDs
18 + *Use your database UUID or primary key (e.g., `user.id`)*
19 + *Example: Users connect their personal Gmail, GitHub*
20 +
21 +- **Teams share the same connected accounts?**
22 + Use Organization IDs
23 + *Use your organization UUID or primary key (e.g., `organization.id`)*
24 + *Example: Company Slack workspace*
25 +
26 +## Patterns
27 +
28 +### User IDs (Individual Accounts)
29 +
30 +In production applications with multiple users, where each user connects and manages their own accounts.
31 +
32 +**Choosing User IDs:**
33 +
34 +- Recommended: Database UUID or primary key (`user.id`)
35 +- Acceptable: Unique username (`user.username`)
36 +- Avoid: Email addresses (emails can change)
37 +
38 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
39 + <Tab value="Python">
40 +```python
41 +# Use your database's user ID (UUID, primary key, etc.)
42 +user_id = user.id; # e.g., "550e8400-e29b-41d4-a716-446655440000"
43 +
44 +tools = composio.tools.get(
45 + user_id=user_id,
46 + toolkits=["GITHUB"],
47 +)
48 +
49 +result = composio.tools.execute(
50 + "GITHUB_GET_REPO",
51 + user_id=user_id,
52 + arguments={
53 + "owner": 'example',
54 + "repo": 'repo'
55 + }
56 +)
57 +```
58 + </Tab>
59 + <Tab value="TypeScript">
60 +```typescript
61 +// Use your database's user ID (UUID, primary key, etc.)
62 +const userId = user.id; // e.g., "550e8400-e29b-41d4-a716-446655440000"
63 +
64 +const tools = await composio.tools.get(userId, {
65 + toolkits: ['github'],
66 +});
67 +
68 +const result = await composio.tools.execute('GITHUB_GET_REPO', {
69 + userId: userId,
70 + arguments: { owner: 'example', repo: 'repo' },
71 +});
72 +```
73 + </Tab>
74 +</Tabs>
75 +
76 +<Callout type="warn">
77 +Never use 'default' as a User ID in production with users. This could expose other users' data.
78 +</Callout>
79 +
80 +### Organization IDs (Team Accounts)
81 +
82 +For applications where teams share connections - one admin connects accounts, all team members use them.
83 +
84 +**When to use:**
85 +- Team tools: Slack, Microsoft Teams, Jira
86 +- Shared accounts: support@company.com, company GitHub org
87 +- Enterprise apps: IT manages connections for all employees
88 +
89 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
90 + <Tab value="Python">
91 +```python
92 +# Use the organization ID as userId
93 +user_id = organization.id # e.g., "org_550e8400"
94 +
95 +# All users in the organization share the same connected accounts
96 +tools = composio.tools.get(
97 + user_id=user_id,
98 + toolkits=["SLACK"],
99 +)
100 +
101 +# Execute tools in the organization context
102 +result = composio.tools.execute(
103 + "SLACK_SEND_MESSAGE",
104 + user_id=user_id,
105 + arguments={
106 + "channel": '#general',
107 + "text": 'Hello from the team!'
108 + }
109 +)
110 +```
111 + </Tab>
112 + <Tab value="TypeScript">
113 +```typescript
114 +// Use the organization ID as userId
115 +const userId = organization.id; // e.g., "org_550e8400"
116 +
117 +// All users in the organization share the same connected accounts
118 +const tools = await composio.tools.get(userId, {
119 + toolkits: ['slack'],
120 +});
121 +
122 +// Execute tools in the organization context
123 +const result = await composio.tools.execute('SLACK_SEND_MESSAGE', {
124 + userId: userId,
125 + arguments: {
126 + channel: '#general',
127 + text: 'Hello from the team!',
128 + },
129 +});
130 +```
131 + </Tab>
132 +</Tabs>
133 +
134 +## Multiple Connected Accounts
135 +
136 +A single User ID can have multiple connected accounts for the same toolkit. For example, a user might connect both their personal and work Gmail accounts.
137 +
138 +**Key concepts:**
139 +- Each connected account gets a unique Connected Account ID
140 +- Multiple accounts can exist under the same User ID for any toolkit
141 +- You can specify which account to use when executing tools
142 +
143 +**Account selection:**
144 +- **Explicit:** Specify the Connected Account ID to target a specific account
145 +- **Default:** If no Connected Account ID is provided, the most recently connected account is used
146 +
147 +## Examples
148 +
149 +### Organization-Based Application
150 +
151 +In B2B applications, typically an admin connects accounts once and all team members share access. Here's a complete implementation:
152 +
153 +**Key concepts:**
154 +- Admin performs the OAuth connection using organization ID
155 +- All team members execute tools using the same organization ID
156 +- Permission checks ensure users can only access their organization's connections
157 +
158 +```typescript
159 +import { Composio } from '@composio/core';
160 +const composio = new Composio({
161 + apiKey: process.env.COMPOSIO_API_KEY,
162 +});
163 +
164 +// 1. Admin connects Slack for the entire organization
165 +async function connectOrganizationToSlack(organizationId: string, adminUserId: string) {
166 + // Use organization ID as userId in Composio
167 + const connectionRequest = await composio.toolkits.authorize(organizationId, 'slack');
168 +
169 + // Store the connection request for the admin to complete
170 + await storeConnectionRequest(organizationId, adminUserId, connectionRequest);
171 +
172 + return connectionRequest.redirectUrl;
173 +}
174 +
175 +// 2. Any user in the organization can use the connected tools
176 +async function sendSlackMessage(organizationId: string, channel: string, message: string) {
177 + return await composio.tools.execute('SLACK_SEND_MESSAGE', {
178 + userId: organizationId, // organization ID, not individual user ID
179 + arguments: {
180 + channel: channel,
181 + text: message,
182 + },
183 + });
184 +}
185 +
186 +// 3. Check if organization has required connections
187 +async function getOrganizationTools(organizationId: string) {
188 + return await composio.tools.get(organizationId, {
189 + toolkits: ['slack', 'github', 'jira'],
190 + });
191 +}
192 +
193 +// Usage in your API endpoint
194 +app.post('/api/slack/message', async (req, res) => {
195 + const { channel, message } = req.body;
196 + const organizationId = req.user.organizationId; // Get from your auth system
197 +
198 + // Verify user has permission to send messages for this organization
199 + if (!(await userCanSendMessages(req.user.id, organizationId))) {
200 + return res.status(403).json({ error: 'Insufficient permissions' });
201 + }
202 +
203 + try {
204 + const result = await sendSlackMessage(organizationId, channel, message);
205 + res.json(result.data);
206 + } catch (error) {
207 + res.status(500).json({ error: 'Failed to send message' });
208 + }
209 +});
210 +```
211 +
212 +### Multi-User Application
213 +
214 +In B2C applications, each user connects and manages their own accounts. Every user goes through their own OAuth flow and their data remains completely isolated.
215 +
216 +**Key concepts:**
217 +- Each user authorizes their own accounts using their unique user ID
218 +- Connections are isolated - users can only access their own connected accounts
219 +- No permission checks needed since users only access their own data
220 +
221 +```typescript
222 +import { Composio } from '@composio/core';
223 +const composio = new Composio({
224 + apiKey: process.env.COMPOSIO_API_KEY,
225 +});
226 +
227 +// 1. User initiates GitHub connection
228 +async function connectUserToGitHub(userId: string) {
229 + const connectionRequest = await composio.toolkits.authorize(userId, 'github');
230 + return connectionRequest.redirectUrl;
231 +}
232 +
233 +// 2. Get user's connected GitHub tools
234 +async function getUserGitHubTools(userId: string) {
235 + return await composio.tools.get(userId, {
236 + toolkits: ['github'],
237 + });
238 +}
239 +
240 +// 3. Execute tool for specific user
241 +async function getUserRepos(userId: string) {
242 + return await composio.tools.execute('GITHUB_LIST_REPOS', {
243 + userId: userId,
244 + arguments: {
245 + per_page: 10,
246 + },
247 + });
248 +}
249 +
250 +// Usage in your API endpoint
251 +app.get('/api/github/repos', async (req, res) => {
252 + const userId = req.user.id; // Get from your auth system
253 +
254 + try {
255 + const repos = await getUserRepos(userId);
256 + res.json(repos.data);
257 + } catch (error) {
258 + res.status(500).json({ error: 'Failed to fetch repos' });
259 + }
260 +});
261 +```
262 +
263 +**Data isolation**: Composio ensures each userId's connections and data are completely separate. User A can never access User B's repositories.
264 +
265 +### Hybrid Pattern
266 +
267 +Many applications need both personal and team resources. Users might connect their personal Gmail while sharing the company Slack workspace.
268 +
269 +**Common scenarios:**
270 +- Personal calendars + shared project management
271 +- Individual GitHub accounts + organization repositories
272 +
273 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
274 + <Tab value="Python">
275 +```python
276 +# Wrong: Using individual user ID for org-connected tool
277 +user_tools = composio.tools.get(
278 + user_id="user_123", # Individual user ID
279 + toolkits=["slack"] # Fails - Slack is connected at org level
280 +)
281 +
282 +# Correct: Match the ID type to how the tool was connected
283 +user_personal_tools = composio.tools.get(
284 + user_id="user_123", # Individual user ID
285 + toolkits=["gmail"] # User's personal Gmail
286 +)
287 +
288 +org_shared_tools = composio.tools.get(
289 + user_id="org_123", # Organization ID
290 + toolkits=["slack", "jira"] # Organization's shared tools
291 +)
292 +```
293 + </Tab>
294 + <Tab value="TypeScript">
295 +```typescript
296 +// Wrong: Using individual user ID for org-connected tool
297 +const userTools = await composio.tools.get(req.user.id, {
298 + toolkits: ['slack'], // Fails - Slack is connected at org level
299 +});
300 +
301 +// Correct: Match the ID type to how the tool was connected
302 +const userPersonalTools = await composio.tools.get(req.user.id, {
303 + toolkits: ['gmail'], // User's personal Gmail
304 +});
305 +
306 +const orgSharedTools = await composio.tools.get(req.user.organizationId, {
307 + toolkits: ['slack', 'jira'], // Organization's shared tools
308 +});
309 +```
310 + </Tab>
311 +</Tabs>
312 +
313 +Remember: The userId must match how the account was connected. If admin connected Slack with org ID, all members must use org ID to access it.
314 +
315 +## Best Practices
316 +
317 +**Your responsibilities:**
318 +- Pass the correct User ID for each user
319 +- Verify user permissions before executing organization tools
320 +- Never use 'default' in production with multiple users
321 +- Keep User IDs consistent across your application and Composio
322 +- Use stable identifiers that won't change over time
323 +
324 +**Data isolation:** Composio ensures complete isolation between User IDs. Users cannot access another ID's connections or data.
fumadocs/public/images/custom-auth-hubspot.png
Binary files /dev/null and b/fumadocs/public/images/custom-auth-hubspot.png differ
fumadocs/public/images/custom-auth-posthog.png
Binary files /dev/null and b/fumadocs/public/images/custom-auth-posthog.png differ
fumadocs/public/images/custom-redirect-uri.png
Binary files /dev/null and b/fumadocs/public/images/custom-redirect-uri.png differ
fumadocs/public/images/github-callback.png
Binary files /dev/null and b/fumadocs/public/images/github-callback.png differ
fumadocs/public/images/github-oauth-config.png
Binary files /dev/null and b/fumadocs/public/images/github-oauth-config.png differ
fumadocs/public/images/google-callback.png
Binary files /dev/null and b/fumadocs/public/images/google-callback.png differ
fumadocs/public/images/google-oauth-config.png
Binary files /dev/null and b/fumadocs/public/images/google-oauth-config.png differ
fumadocs/public/images/integration-step-3-0.png
Binary files /dev/null and b/fumadocs/public/images/integration-step-3-0.png differ
fumadocs/public/images/oauth-branding.png
Binary files /dev/null and b/fumadocs/public/images/oauth-branding.png differ