OAuth Field Guide
Researched guide · 2026-10-28

Gmail (Google)

mail.google.com · Email · for: AI agent reads, drafts and sends email from the user's Gmail account.

High frictionScope-based verificationwhy this rating →
Do this next

Write down which features truly need to read mail. If any do, start the privacy policy, Limited Use statement and Search Console domain verification today, because restricted verification and CASA can't start without them.

Your path at a glance

Prepare
Register
Configure OAuth
Test
Review
Launch
Customer
Agent
You
Provider
wait 2 wk – 13 wk
Customer admin
Milestones
◆ Works for you
30 min – 1 h work
no wait
◆ Any customer
25 h – 80 h work
2 wk – 13 wk wait
agent can do you agent prepares, you finish assumedClick a step to jump to it.

Watch out for

Before you start

Steps

Prepare

  1. 1Decide scopes and data flowYouopen ↗details →
  2. 2Publish homepage and privacy policy, and verify the domainYouopen ↗details →

Register the app

  1. 3Create the Cloud project and enable the Gmail APIAgent prepares, you finishopen ↗details →

Configure OAuth

  1. 4Configure Google Auth Platform: Branding, Audience, Data AccessYouopen ↗details →
  2. 5Create a Web application OAuth clientYouopen ↗details →
  3. 6Implement the authorization-code flowAgent can doopen ↗details →

Test with your account

  1. 7Connect your own Gmail as a test userAgent prepares, you finishopen ↗details →

Review & verification

  1. 8Record the demo video and submit for verificationYouopen ↗details →
  2. 9Complete the CASA security assessmentYouopen ↗details →

Launch to customers

  1. 10Publish to production and calendar recertificationYouopen ↗details →

Customer-side setup

  1. 11Workspace customers: admin trusts your client IDCustomer adminopen ↗details →

Copy & paste

Scopes to request
https://www.googleapis.com/auth/gmail.readonlyhttps://www.googleapis.com/auth/gmail.composehttps://www.googleapis.com/auth/gmail.modifyhttps://www.googleapis.com/auth/gmail.sendopenid email
Developer console
https://console.cloud.google.com/auth/overview
OAuth docs
https://developers.google.com/identity/protocols/oauth2/web-server
Authorize URL
https://accounts.google.com/o/oauth2/v2/auth
Token URL
https://oauth2.googleapis.com/token
Discovery
https://accounts.google.com/.well-known/openid-configuration
Prompt for your coding agent
Show prompt
You are implementing Google OAuth so our AI agent can read, draft and send Gmail on behalf of users.
Facts: authorize https://accounts.google.com/o/oauth2/v2/auth, token https://oauth2.googleapis.com/token, revoke https://oauth2.googleapis.com/revoke; PKCE S256 is supported. Scopes: openid email https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/gmail.compose (both Gmail scopes are restricted).
Tasks:
1. Load GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET and GOOGLE_REDIRECT_URI from env (see the .env template). Never commit secrets.
2. /auth/google/start: build the authorize URL with response_type=code, access_type=offline, include_granted_scopes=true, prompt=consent (on reconnect), a signed state, and a PKCE S256 code_challenge.
3. /auth/google/callback: verify state, exchange the code with the code_verifier, parse the granted 'scope' string, and mark missing features if the user unchecked a scope. Store the refresh_token encrypted, plus sub, email and granted scopes.
4. Write a Gmail client wrapper: refresh access tokens using expires_in, and on invalid_grant set needs_reconnect. Handle admin_policy_enforced by showing our Workspace-admin guide. Back off exponentially on 429 and on 403 rateLimitExceeded/userRateLimitExceeded.
5. Disconnect: call the revoke endpoint and delete stored tokens.
6. Never log message bodies. Keep Gmail data out of analytics, eval and training datasets (Limited Use).
7. Add a CI test asserting that the scope list in code equals config/google-approved-scopes.json.
8. Draft the per-scope justification and Limited Use statement from the templates, filling in our real features.
Don't touch the Google Cloud console; a human creates the project, consent screen and client and gives you the client ID and secret.
.env template
Show dotenv
# Google Auth Platform → Clients → Web application
GOOGLE_CLIENT_ID=000000000000-xxxxxxxxxxxxxxxx.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=replace-me-from-secret-manager
GOOGLE_REDIRECT_URI=https://app.example.com/auth/google/callback
GOOGLE_SCOPES=openid email https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/gmail.compose
# Encrypt refresh tokens at rest
TOKEN_ENCRYPTION_KEY=generate-a-random-32-byte-value
Scope justification template (restricted-scope verification)
Show markdown
## https://www.googleapis.com/auth/gmail.readonly
Feature: <AppName>'s assistant reads the user's recent inbox threads to summarize them and suggest replies inside <AppName> (screen: <Inbox Summary>, shown at <mm:ss> in the demo video).
Why narrower scopes don't work: gmail.metadata exposes only headers and labels, and the summaries need message bodies. gmail.send cannot read mail.
Data handling: message content is processed only to produce the summary the user requested. It's stored encrypted for <N days>, not shared except with <LLM provider> under zero-retention, no-training terms, and never used to train models.

## https://www.googleapis.com/auth/gmail.compose
Feature: the assistant creates draft replies that the user reviews and sends, or sends a message the user explicitly approves (demo <mm:ss>).
Why narrower scopes don't work: gmail.send can send but cannot create or update drafts, and the user's review-before-send flow depends on drafts.

## Limited Use statement (homepage/privacy policy)
<AppName>'s use and transfer to any other app of information received from Google APIs will adhere to the Google API Services User Data Policy (https://developers.google.com/terms/api-services-user-data-policy), including the Limited Use requirements.
Customer Workspace admin guide
Show markdown
If your users see "<AppName> is blocked" or "admin_policy_enforced":
1. Admin console → Security → Access and data control → API controls → Manage Third-Party App Access.
2. Add app → OAuth App Name or Client ID → enter <GOOGLE_CLIENT_ID>.
3. Choose the org units, then set access to "Trusted" (or "Specific Google data" limited to gmail.readonly and gmail.compose).
Scopes requested: openid, email, gmail.readonly, gmail.compose. Security assessment: CASA Letter of Validation dated <date>.

Why & details

The reasoning, evidence and sources behind everything above. Hover a badge to see its sources.

The full picture

Scope-based verification

Hard: you can test in an hour, but every Gmail scope that reads mail or manages drafts is restricted. Before arbitrary users can connect without warnings, you need brand verification, restricted-scope review (Google estimates about 6 weeks) and an annual third-party CASA security assessment paid by you. Until then, you're limited to 100 test users whose refresh tokens expire after 7 days, or a lifetime cap of 100 users who click through an 'unverified app' warning.

Project and client setup is self-serve, but the scopes decide the review. gmail.send alone is sensitive. gmail.readonly, gmail.compose and gmail.modify are restricted, and an agent that stores or transmits that data through a server must pass a security assessment. Workspace customers' admins can also block or must trust the app.

Rating: Audits, partner approval or multi-week reviews that you can't speed up.

Working with your own account
30 min – 1 h hands-on · no wait

Cloud project with the Gmail API enabled, Google Auth Platform configured as External + Testing, your account added as a test user, and a Web OAuth client. You click through the 'Google hasn't verified this app' screen, and the refresh token dies after 7 days.

Any customer can connect
25 h – 80 h hands-on · 2 wk – 13 wk

Brand verification, restricted-scope verification and a CASA Letter of Validation are approved, the app is In production, and Workspace customers' admins have trusted the client ID if they restrict Gmail. Active time covers the privacy policy, domain verification, demo video, justifications and CASA remediation.

What affects your setup

Before you start — why each matters

How well this guide is backed

5 tested44 source-backed1 community-reported1 uncertain· Well evidenced (97% backed)

Step details

  1. 1Decide scopes and data flow↑ back to step

    Map each agent feature to the narrowest scope. Reading or drafting forces restricted scopes. Because an AI agent sends message content through your servers and an LLM, plan for CASA. Write down why narrower scopes (gmail.send, gmail.metadata) wouldn't work.

    👤 Why you: A product/business judgement only you can make

    🤖 What an agent can do: Inventory Gmail API calls in the codebase, map them to scopes, and draft the per-scope justification text (template below).

    https://developers.google.com/workspace/gmail/api/auth/scopes ↗
  2. 2Publish homepage and privacy policy, and verify the domain↑ back to step

    Host the homepage and privacy policy on your domain, with the Limited Use disclosure. Add the domain as a property in Google Search Console and verify it (usually a DNS TXT record) with a project Owner or Editor account.

    👤 Why you: DNS or domain ownership change

    🤖 What an agent can do: Draft the privacy-policy section on Google user data and the Limited Use statement, and add both pages to the site. The human adds the DNS TXT record.

    https://search.google.com/search-console ↗
  3. 3Create the Cloud project and enable the Gmail API↑ back to step

    Create (or pick) a project, then enable gmail.googleapis.com.

    👤 Why you: Needs your logged-in console session (2FA/CAPTCHA)

    🤖 What an agent can do: If the developer is logged in to gcloud, run `gcloud projects create` and `gcloud services enable gmail.googleapis.com --project <id>`.

    https://console.cloud.google.com/apis/library/gmail.googleapis.com ↗
  4. 4Configure Google Auth Platform: Branding, Audience, Data Access↑ back to step

    Branding: app name, support email, logo, homepage, privacy policy, terms and authorized domains. Audience: External, leave in Testing, add test users. Data Access: add exactly the scopes you'll submit, since a mismatch with the submission is a common rejection.

    👤 Why you: Needs your logged-in console session (2FA/CAPTCHA)

    🤖 What an agent can do: Produce a checklist of exact field values and the scope list, copied from the code's scope constants.

    https://console.cloud.google.com/auth/branding ↗
  5. 5Create a Web application OAuth client↑ back to step

    Google Auth Platform → Clients → Create client → Web application. Add exact HTTPS redirect URIs per environment (localhost is allowed for dev). Store the client ID and secret in your secret manager.

    👤 Why you: Needs your logged-in console session (2FA/CAPTCHA)

    🤖 What an agent can do: List every redirect URI the app uses per environment and generate the .env template.

    https://console.cloud.google.com/auth/clients ↗
  6. 6Implement the authorization-code flow↑ back to step

    Redirect with scope, access_type=offline, prompt=consent (on reconnect), state, PKCE S256 and include_granted_scopes=true. Exchange the code at oauth2.googleapis.com/token. Check which scopes were actually granted. Store refresh tokens encrypted, and handle invalid_grant as 'reconnect needed'.

    🤖 What an agent can do: Implement it with google-auth-library or openid-client, including a granted-scope check, encrypted token storage, refresh and revoke on disconnect, and quota-aware backoff on 429/403 rateLimitExceeded.

    https://developers.google.com/identity/protocols/oauth2/web-server ↗
  7. 7Connect your own Gmail as a test user↑ back to step

    Sign in as a listed test user, accept the unverified-app warning, and test read, draft and send. Expect the refresh token to stop working 7 days after consent while in Testing.

    👤 Why you: Needs your logged-in console session (2FA/CAPTCHA)

    🤖 What an agent can do: Write an end-to-end smoke test: list 5 messages, create a draft, and send it to a test address.

    https://console.cloud.google.com/auth/audience ↗
  8. 8Record the demo video and submit for verification↑ back to step

    Record the full flow: Google consent screen showing the exact scopes, then each feature that uses each scope. In Verification Center, submit brand and restricted-scope verification with justifications, then reply to Trust & Safety emails promptly.

    👤 Why you: Record a demo video

    🤖 What an agent can do: Write the video shot list and narration script, and finalize the justification text and Limited Use answers.

    https://console.cloud.google.com/auth/verification ↗
  9. 9Complete the CASA security assessment↑ back to step

    When Google's team prompts you (the final step of restricted review), engage an authorized lab, complete the assessment at the assigned level (AL1 or AL2), fix the findings, and submit the Letter of Validation.

    👤 Why you: Legal attestation, payment, or contract

    🤖 What an agent can do: Run SAST and dependency scans, map controls to the CASA/OWASP ASVS requirements, fix findings, and assemble evidence such as encryption at rest, access controls and logging.

    https://support.google.com/cloud/answer/13465431 ↗
  10. 10Publish to production and calendar recertification↑ back to step

    Move the Audience to In production after approval. Recertification is due 12 months from the LOV date and is a full reassessment even without code changes.

    👤 Why you: A product/business judgement only you can make

    🤖 What an agent can do: Add a monitored reminder about 90 days before LOV expiry, and a CI check that the requested scopes in code match the approved set.

    https://support.google.com/cloud/answer/13463816 ↗
  11. 11Workspace customers: admin trusts your client ID↑ back to step

    If the customer restricts Gmail or blocks unconfigured apps, their admin must add your app by OAuth client ID in Admin console → Security → Access and data control → API controls and set it to Trusted or Specific Google data.

    👤 Why you: Your customer's admin must act

    🤖 What an agent can do: Generate a customer admin guide that includes your client ID and requested scopes, and detect admin_policy_enforced errors in the callback to show it.

    https://knowledge.workspace.google.com/admin/apps/control-which-apps-access-google-workspace-data ↗

Gotchas explained

  • BlockerNo Gmail read or draft scope avoids restricted verification

    gmail.readonly, gmail.compose, gmail.modify and gmail.metadata are all restricted; only gmail.send (sensitive) and gmail.labels are lower tier. If restricted data is stored on or transmitted through your servers, which is the norm for an AI agent, CASA is required every year.

    Fix: Budget for CASA from day one, or ship a send-only first version on gmail.send while restricted verification runs.

  • BlockerThe 100-user cap is lifetime and can't be reset

    An unverified production app can onboard 100 new users in total over the project's whole life. Going 'In production' before verification can burn the cap.

    Fix: Stay in Testing with named test users until verification is approved, and use a separate project for experiments.

  • Warning7-day refresh tokens in Testing

    Test users' authorizations, including refresh tokens, expire 7 days after consent, so beta users get logged out every week.

    Fix: Show a clear 'reconnect Gmail' prompt on invalid_grant. Don't treat Testing as a beta channel for real customers.

  • WarningWorkspace admins can silently block or revoke you

    Admins can disallow unconfigured third-party apps or mark Gmail as Restricted. Turning on Restricted revokes tokens of untrusted apps that already connected.

    Fix: Ship an admin allowlisting guide with your OAuth client ID. Detect the authorization error (commonly reported as admin_policy_enforced; the code isn't confirmed in the cited doc) and invalid_grant, and route the user to the guide.

  • WarningRefresh tokens disappear in surprising ways

    They're returned only on first consent, revoked on password change (Gmail scopes), and silently dropped beyond 100 per account per client. Test harnesses that reconnect repeatedly hit the 100 limit.

    Fix: Use prompt=consent on reconnect, keep one refresh token per user, revoke old ones on disconnect, and alert on refresh failures.

  • WarningCommon rejection reasons

    Scopes on the consent screen or Data Access page that don't match the submission, a homepage that's only a login page, a privacy policy on another domain or missing the Limited Use statement, vague justifications, a demo that doesn't show the real consent screen, and misuse of Google product names.

    Fix: Use the justification template, record every scope's feature, and match the submitted scope list to code exactly.

  • WarningLimited Use bans model training on Gmail data

    Workspace API data may not be used to create, train or improve AI/ML models beyond that user's personalized model. Transfers are allowed only to provide user-facing features. Humans may not read the data without the user's affirmative agreement, except for security, legal or aggregated internal operations.

    Fix: Use LLM providers with zero-retention, no-training terms, disclose them in the privacy policy, and exclude Gmail data from logs, evals and fine-tuning sets.

  • InfoNew quota model for projects created after 2026-05-01

    New projects get the standardized agent-tool quotas: 6,000 units/min per user, with messages.send costing 100 units, so about 60 sends/min per user. A daily billing threshold of 80M units per project applies, and charges above it are planned for later in 2026. Quota increases will require billing to be enabled.

    Fix: Batch reads, prefer messages.list + metadata over full fetches, and enable billing early on the production project.

Why each scope

ScopeWhy you need itTierEvidence
https://www.googleapis.com/auth/gmail.readonlyRead messages, threads and settings so the agent can triage and summarize mail.restricted
https://www.googleapis.com/auth/gmail.composeCreate, update and send drafts, and send messages. Covers both drafting and sending.restricted
https://www.googleapis.com/auth/gmail.modifyAlternative to readonly+compose if the agent also labels, archives or marks messages read (read, compose, send; no permanent delete).restricted
https://www.googleapis.com/auth/gmail.sendSend only. Sensitive, not restricted, so no CASA, but it can't read mail or manage drafts. Enough only for a send-only agent.sensitive
openid emailIdentify which Google account was connected (store the sub and email).basic

Reference facts

  • Endpoints & PKCEDiscovery lists PKCE methods plain and S256. Revoke tokens at https://oauth2.googleapis.com/revoke.
  • Getting a refresh tokenSend access_type=offline. The refresh_token comes back only on the first authorization, so add prompt=consent to force a new one when re-connecting.
  • Testing-mode expiryIn Testing status (External), authorizations and refresh tokens expire 7 days after consent, unless the only scopes are openid/email/profile.
  • Refresh-token killers6 months unused, password change (when the token has Gmail scopes), user revocation, time-based access expiry, org session control (1-24h), and over 100 tokens per account per client (the oldest is dropped silently).
  • Access-token lifetimeShort-lived; use expires_in from the token response. Google's overview page only says tokens have 'limited lifetimes' (typically 3600s).
  • Gmail API quotas6,000 quota units/min per user per project and 1,200,000/min per project. messages.send = 100 units, messages.get = 20 (60 for full/raw), drafts.create = 10. New quotas apply to projects created on or after 2026-05-01, with a daily billing threshold of 80M units per project. Charges for usage above it are planned for later in 2026, with 90 days' notice.
  • Granular consentUsers can uncheck individual scopes on the consent screen. Check the scope field in the token response and degrade gracefully, or re-prompt with include_granted_scopes=true.
  • Invalid-client behaviorAn unknown client_id at /o/oauth2/v2/auth sends the user to accounts.google.com/signin/oauth/error. At the token endpoint it returns 401 invalid_client 'The OAuth client was not found.'
  • PKCE (from discovery document)Advertised methods: plain, S256
  • Scopes advertised in discoveryopenid, email, profile
  • Endpoints observed liveAuthorize: HTTP 302; redirects to accounts.google.com/signin/oauth/error; → endpoint is live (client validation may happen after login) · Token: HTTP 401; error "invalid_client: The OAuth client was not found."; → token endpoint is live and rejects a bogus code

What we verified — and what we couldn't

Live probes (no credentials)

  • ✓discovery https://accounts.google.com/.well-known/openid-configurationHTTP 200; issuer https://accounts.google.com; authorize https://accounts.google.com/o/oauth2/v2/auth; PKCE methods: plain, S256[P1]
  • ✓authorize https://accounts.google.com/o/oauth2/v2/authHTTP 302; redirects to accounts.google.com/signin/oauth/error; → endpoint is live (client validation may happen after login)[P2]
  • ✓token https://oauth2.googleapis.com/tokenHTTP 401; error "invalid_client: The OAuth client was not found."; → token endpoint is live and rejects a bogus code[P3]
  • ✓page https://console.cloud.google.com/auth/overviewHTTP 302; redirects to accounts.google.com/ServiceLogin[P4]
  • ✓page https://developers.google.com/identity/protocols/oauth2/web-serverHTTP 302; redirects to developers.google.com/identity/protocols/oauth2/web-server[P5]

Open questions

  • Which CASA assurance level (AL1 or AL2) will Google assign, and what will it really cost?
    Google assigns the level from user count, scopes and other signals and publishes no prices. Vendor prices (about $540 to $3,000+) are community-reported, and much third-party material still uses the old 'Tier 2/Tier 3' labels with no official mapping to AL1/AL2.
    To resolve: Wait for the Trust & Safety email after restricted review starts, then get quotes from two or three labs on the App Defense Alliance authorized list.
  • How do reviewers treat sending Gmail content to a third-party LLM API?
    Limited Use allows transfers only to provide user-facing features and bans training generalized models. The policy doesn't explicitly address LLM inference providers as subprocessors.
    To resolve: Disclose the LLM provider and its no-training terms in the privacy policy and justification, and ask in the verification email thread if challenged.
  • What will usage above the daily billing threshold cost, and when?
    Google says billing details will come 'later in 2026' with at least 90 days' notice. As of 2026-10-28 we found no published price.
    To resolve: Watch developers.google.com/workspace/tools-safety and the Workspace Developers blog.
  • Does Google's Workspace MCP server (public developer preview since 2026-05-01) change verification for third-party agents?
    The announcement describes Gmail MCP tools but not how third-party OAuth clients get verified or capped when using it.
    To resolve: Read the 'Configure the Google Workspace MCP servers' guide and check whether it reuses your own OAuth client and scopes.
  • How long will verification really take for this app?
    Google's estimates aren't guaranteed, and community reports range from about 2 weeks to over 2 months depending on resubmissions and CASA remediation.
    To resolve: Submit early with a complete package, answer reviewer emails within 24h, and start lab scoping as soon as restricted review begins.

Ask the provider

A ready-to-send message built from the open questions above.

Send to
No contact channel found — check https://developers.google.com/identity/protocols/oauth2/web-server for developer support
Subject
OAuth integration questions — Gmail (Google)
Hi Gmail (Google) developer support team,

We're building an integration where AI agent reads, drafts and sends email from the user's Gmail account. Before we register an OAuth app and launch to customers, we couldn't find answers to the following in your documentation:

1. Which CASA assurance level (AL1 or AL2) will Google assign, and what will it really cost?
   (What we found: Google assigns the level from user count, scopes and other signals and publishes no prices. Vendor prices (about $540 to $3,000+) are community-reported, and much third-party material still uses the old 'Tier 2/Tier 3' labels with no official mapping to AL1/AL2.)
2. How do reviewers treat sending Gmail content to a third-party LLM API?
   (What we found: Limited Use allows transfers only to provide user-facing features and bans training generalized models. The policy doesn't explicitly address LLM inference providers as subprocessors.)
3. What will usage above the daily billing threshold cost, and when?
   (What we found: Google says billing details will come 'later in 2026' with at least 90 days' notice. As of 2026-10-28 we found no published price.)
4. Does Google's Workspace MCP server (public developer preview since 2026-05-01) change verification for third-party agents?
   (What we found: The announcement describes Gmail MCP tools but not how third-party OAuth clients get verified or capped when using it.)
5. How long will verification really take for this app?
   (What we found: Google's estimates aren't guaranteed, and community reports range from about 2 weeks to over 2 months depending on resubmissions and CASA remediation.)

Could you point us to the right documentation or process — including whether any review or approval is needed before customers outside our own account can connect, and the typical timeline?

Thanks,
[Your name]
[Company · website]

Sources

  1. S1Gmail API – Choose Gmail API scopesofficial
  2. S2Google Identity – Using OAuth 2.0 to Access Google APIs (refresh token expiration)official
  3. S3Google Cloud Help – Manage App Audienceofficial
  4. S4Google Cloud Help – Verification requirementsofficial
  5. S5Google Cloud Help – Security Assessmentofficial
  6. S6Google Cloud Help – OAuth verification FAQofficial
  7. S7Google Cloud Help – Annual Recertificationofficial
  8. S8App Defense Alliance – CASA Assurance Levelsofficial
  9. S9App Defense Alliance – Authorized labsofficial
  10. S10Google API Services User Data Policyofficial
  11. S11Google Workspace API user data and developer policyofficial
  12. S12Google Workspace Admin – Control which apps access Google Workspace dataofficial
  13. S13Google Workspace – Configure the OAuth consent screen and choose scopesofficial
  14. S14Google Identity – OAuth 2.0 for Web Server Applicationsofficial
  15. S15Gmail API – Usage limitsofficial
  16. S16Google Workspace – Standardized model for agent tools and APIsofficial
  17. S17Workspace Updates – Agent tools and security updates for Workspace developers (2026-05-01)official
  18. S18Google Cloud Help – When is verification not neededofficial
  19. S19Nango – Google security review guidecommunity
  20. T1Probe: Google OIDC discovery document (2026-10-28)probe
  21. T2Probe: authorize with client_id=probe-invalid (2026-10-28)probe
  22. T3Probe: token endpoint with bogus client/code (2026-10-28)probe
  23. P1Our probe: discovery check on accounts.google.comprobe
  24. P2Our probe: authorize check on accounts.google.comprobe
  25. P3Our probe: token check on oauth2.googleapis.comprobe
  26. P4Our probe: page check on console.cloud.google.comprobe
  27. P5Our probe: page check on developers.google.comprobe