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

next
mdx 193 lines 8.56 KB
Raw
1 ---
2 title: Restrict Gmail connections to an email domain
3 description: Check the connected Gmail address before giving an agent access, and disable connections outside your allowed domain.
4 keywords: [gmail, email domain, allowlist, account identity, authentication, python, typescript]
5 gallery:
6 categories: [General agents]
7 logos: [gmail]
8 ---
9
10 Accept a Gmail connection only when its mailbox address belongs to your allowed domain. This example connects an account, checks its address on the server, and prepares agent tools only after approval.
11
12 The check runs **after Google authentication**. It doesn't restrict Google's account picker or prove Google Workspace membership. For an organization-membership policy, follow [Google's guidance on the validated `hd` claim](https://developers.google.com/identity/gsi/web/guides/verify-google-id-token).
13
14 ## Set up the project
15
16 Use Python 3.12 or Node.js 24.17 or newer. Install in a new project, using a virtual environment for Python:
17
18 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
19 <Tab value="Python">
20 <PackageInstall packages="composio" ecosystem="python" />
21 </Tab>
22 <Tab value="TypeScript">
23 <PackageInstall packages="@composio/core zod" />
24 </Tab>
25 </Tabs>
26
27 Set a [Composio project key](https://dashboard.composio.dev/~/project/settings/api-keys?utm_source=docs&utm_medium=content&utm_campaign=examples-restrict-gmail-domain) and a fresh application user ID for this demo:
28
29 ```bash
30 export COMPOSIO_API_KEY="your-composio-api-key"
31 export COMPOSIO_USER_ID="domain-check-demo"
32 ```
33
34 In your application, derive the user ID from your authenticated session. Keep the API key and this code on the server. If you use a scoped project key, enable [Proxy execute (Legacy) → Write only](/reference/authenticating-to-composio/project-api-key-permissions#proxy-execute-legacy). These scripts call the direct proxy route, which Session tool execution does not grant.
35
36 The script calls Gmail's [`users.getProfile`](https://developers.google.com/workspace/gmail/api/reference/rest/v1/users/getProfile) endpoint with `me`, which selects the authenticated mailbox. It reads the returned `emailAddress`. The endpoint requires a Gmail scope such as `https://www.googleapis.com/auth/gmail.readonly`; `openid` and `email` alone don't grant this access. Ensure your Gmail auth config requests `gmail.readonly` if the agent will also read messages. See [Controlling scopes](/docs/authentication/controlling-scopes) to configure scopes and reconnect after changing them.
37
38 ## Connect and check the account
39
40 Replace `example.com` in the script with your allowed domain. Run the script, open the printed Connect Link, and complete authentication within five minutes. The script polls its own connection request, so it doesn't need an HTTP callback handler.
41
42 {/* code-example: no-api reason="Runnable onboarding script: SDK connection polling, local domain validation, and conditional disable" */}
43 <Tabs groupId="language" items={['Python', 'TypeScript']} persist>
44 <Tab value="Python">
45
46 Save as `restrict_gmail.py`:
47
48 ```python title="restrict_gmail.py"
49 import os
50 from email.headerregistry import Address
51
52 from composio import Composio
53
54 ALLOWED_DOMAIN = "example.com"
55
56
57 def approved_email(data):
58 email = data["emailAddress"]
59 address = Address(addr_spec=email)
60 if (
61 not address.username
62 or address.addr_spec != email
63 or address.domain.lower() != ALLOWED_DOMAIN.lower()
64 ):
65 raise ValueError("Mailbox address is not allowed")
66 return email
67
68
69 composio = Composio()
70 user_id = os.environ["COMPOSIO_USER_ID"]
71 onboarding = composio.create(
72 user_id=user_id,
73 toolkits=["gmail"],
74 manage_connections=False,
75 sandbox={"enable": False},
76 )
77 request = onboarding.authorize("gmail")
78 print(f"Connect Gmail: {request.redirect_url}", flush=True)
79
80 try:
81 account = request.wait_for_connection(timeout=300) # Python uses seconds.
82 response = composio.tools.proxy(
83 endpoint="https://gmail.googleapis.com/gmail/v1/users/me/profile",
84 method="GET",
85 connected_account_id=account.id,
86 )
87 if response.status != 200:
88 raise RuntimeError("Gmail profile request failed")
89 email = approved_email(response.data)
90 except Exception:
91 # Also reject missing identity, insufficient scopes, and timeouts.
92 composio.connected_accounts.disable(request.id)
93 raise SystemExit(
94 f"Connection disabled. Rerun and connect a Gmail account at {ALLOWED_DOMAIN}. "
95 "If you used that domain, check the Gmail scopes and try again."
96 ) from None
97
98 session = composio.create(
99 user_id=user_id,
100 toolkits=["gmail"],
101 connected_accounts={"gmail": [account.id]},
102 manage_connections=False,
103 sandbox={"enable": False},
104 )
105 tools = session.tools()
106 print(f"Connected as {email}. Agent tools are ready for this account.")
107 ```
108
109 ```bash
110 python restrict_gmail.py
111 ```
112
113 </Tab>
114 <Tab value="TypeScript">
115
116 Save as `restrict-gmail.ts`:
117
118 ```typescript title="restrict-gmail.ts"
119 import { Composio } from '@composio/core';
120 import { z } from 'zod';
121
122 const ALLOWED_DOMAIN = 'example.com';
123 const gmailProfile = z.object({ emailAddress: z.string().email() });
124
125 function approvedEmail(data: unknown) {
126 const { emailAddress } = gmailProfile.parse(data);
127 const domain = emailAddress.split('@')[1].toLowerCase();
128 if (domain !== ALLOWED_DOMAIN.toLowerCase()) {
129 throw new Error('Mailbox address is not allowed');
130 }
131 return emailAddress;
132 }
133
134 const userId = process.env.COMPOSIO_USER_ID;
135 if (!userId) throw new Error('Set COMPOSIO_USER_ID');
136 const composio = new Composio();
137 const onboarding = await composio.create(userId, {
138 toolkits: ['gmail'],
139 manageConnections: false,
140 sandbox: { enable: false },
141 });
142 const request = await onboarding.authorize('gmail');
143 console.log(`Connect Gmail: ${request.redirectUrl}`);
144
145 let email: string;
146 try {
147 const account = await request.waitForConnection(300_000); // TypeScript uses milliseconds.
148 const response = await composio.tools.proxyExecute({
149 endpoint: 'https://gmail.googleapis.com/gmail/v1/users/me/profile',
150 method: 'GET',
151 connectedAccountId: account.id,
152 });
153 if (response.status !== 200) {
154 throw new Error('Gmail profile request failed');
155 }
156 email = approvedEmail(response.data);
157 } catch {
158 // Also reject missing identity, insufficient scopes, and timeouts.
159 await composio.connectedAccounts.disable(request.id);
160 throw new Error(
161 `Connection disabled. Rerun and connect a Gmail account at ${ALLOWED_DOMAIN}. ` +
162 'If you used that domain, check the Gmail scopes and try again.',
163 );
164 }
165
166 const session = await composio.create(userId, {
167 toolkits: ['gmail'],
168 connectedAccounts: { gmail: [request.id] },
169 manageConnections: false,
170 sandbox: { enable: false },
171 });
172 const tools = await session.tools();
173 console.log(`Connected as ${email}. Agent tools are ready for this account.`);
174 ```
175
176 ```bash
177 node restrict-gmail.ts
178 ```
179
180 </Tab>
181 </Tabs>
182
183 For an approved account, the script prints `Connected as alice@example.com. Agent tools are ready for this account.` Pass the returned `tools` to your [agent framework](/docs/providers) using this approved session. The default SDK provider returns OpenAI-compatible tools; configure your framework's provider when constructing `Composio` if needed.
184
185 For a rejected account, the script disables the connection and exits before creating the agent session. If disabling fails, the script stops with that error and still doesn't create the agent session. Resolve the failure before retrying. Disabling a connection blocks Composio tool execution; it doesn't revoke Google's OAuth grant.
186
187 ## Keep the check in the execution path
188
189 The onboarding session never supplies tools to an agent. The second session selects the approved account explicitly and disables in-chat connection management, so the agent can't connect another account through that session. Don't expose the onboarding session to clients or reuse other sessions that can select unchecked accounts. Apply the same validation whenever you accept a new or replacement connection.
190
191 The domain comparison ignores case and requires an exact match. `alice@EXAMPLE.COM` passes; `alice@gmail.com`, `alice@sub.example.com`, and `alice@notexample.com` don't. Missing or malformed profile data and failed profile requests also prevent approval. An alias such as `work-gmail` or the account's `displayName` isn't the input to this decision.
192
193 To display identity without a domain policy, see [Identify the connected account](/docs/authentication/manually-authenticating#identify-the-connected-account). For session account selection, see [Managing multiple connected accounts](/docs/authentication/managing-multiple-connected-accounts#selecting-a-specific-account-for-a-session).