← BLOG
· Arc0 team

OAuth for AI agents: per-user tokens without the pain

How OAuth for AI agents works per user: PKCE consent, encrypted token storage, refresh, OBO, MCP auth, consent screens, and reconnects, with code.

Your agent writes a good reply. Now one customer wants it sent from their own Gmail, and another wants it posted in their Slack. A third wants the deal updated in HubSpot. OAuth for AI agents is how that works without anyone handing over a password. Each user grants your app access once, and your agent acts on their behalf from then on. The first login isn't the hard part. The hard part is every user's tokens, afterwards, for as long as you're in business.

You'll get the per-user model, the four steps that keep it alive, where on-behalf-of (OBO) flows fit, and code in TypeScript and Python.

The per-user model in one picture

Authenticate the user, not the agent. The agent is a program you run. The permissions belong to the person who clicked Allow, so every token should be theirs and every call bound to them. Merge's best practices for agent authentication, read in November 2026, describe the same shape. The authorization code flow with PKCE gives the agent only that person's permissions. Each user gets one encrypted credential, refresh stays server-side, and credentials stay out of the model's context.

The whole model fits in four rules:

  1. Each user consents once, through the authorization code flow with PKCE.
  2. Your backend stores their tokens, encrypted, one credential per user per connector, keyed by user and tenant (the customer company), never in environment variables.
  3. Your backend refreshes them, outside the agent's loop.
  4. The agent gets results, never tokens. Every call it makes carries one user id, and your runtime attaches that user's token at call time.

If a token is in the prompt, the design is already wrong. Sooner or later someone writes a tool that "just needs the Gmail token for a second". Now a live credential sits in a context window, next to whatever a stranger wrote in their last email. Keep the token on your server and there's nothing in the prompt to leak.

MCP adds a second hop, and it helps to keep it separate in your head. MCP (Model Context Protocol) is the standard way agents call tools. When an interactive client such as Claude or Cursor connects to an MCP server, the client signs the person in to that server with OAuth. The server holds that person's third-party tokens separately. Two grants, two audiences, one person. This post is mostly about the server's side: the third-party tokens.

Diagram of the per-user model: an end user consents once through a Connect page showing your name and colours; the tokens go to a token vault in your backend, keyed by tenant and user; the agent sends only a user id to a backend call, which attaches that user's token, so the agent never holds one

The authorization code flow sends the user to the provider and brings a short-lived code back to your redirect URI. Your server swaps that code for tokens. PKCE (Proof Key for Code Exchange, RFC 7636) binds the code to a one-time secret, so an intercepted code is useless to whoever caught it. You make a random verifier, send its SHA-256 hash as the challenge (the S256 method), and present the verifier when you redeem the code. The verifier is 43 to 128 characters, and the plain method has no place in new code.

The security guidance agrees. RFC 9700, the current OAuth security best practice, says public clients must use PKCE and recommends it for confidential ones. It also asks for S256 and exact string matching on redirect URIs. The OAuth 2.1 draft goes the same way: PKCE required, the implicit and password grants gone, exact redirect matching. It's still an Internet-Draft, not a standard, so point to RFC 9700 when a reviewer asks why.

Use PKCE even if your server is a confidential client with a client secret. It costs a few lines and covers the day a code leaks through a log or a proxy. Add a random state value too, tie it to the user's session, and reject any callback you didn't start.

Google adds two rules you'll hit on your first integration. You need access_type=offline to refresh when the user isn't around. And Google returns the refresh token only on the first authorization; to get a new one, revoke the grant or send prompt=consent. That's the classic second-connect bug: the user reconnects, the code exchange succeeds, and the refresh token you were counting on just isn't there.

The start of the flow in TypeScript, with Node's built-in crypto:

import { createHash, randomBytes } from 'node:crypto';

export function startAuth(provider: ProviderConfig) {
  const verifier = randomBytes(32).toString('base64url');
  const challenge = createHash('sha256').update(verifier).digest('base64url');
  const state = randomBytes(32).toString('base64url');

  const url = new URL(provider.authorizeUrl);
  url.search = new URLSearchParams({
    response_type: 'code',
    client_id: provider.clientId,
    redirect_uri: provider.redirectUri, // must match the registered URI exactly
    scope: provider.scopes.join(' '),
    state,
    code_challenge: challenge,
    code_challenge_method: 'S256',
    access_type: 'offline', // Google: needed for a refresh token
  }).toString();

  // Store verifier and state in the user's server-side session, keyed by state.
  return { url: url.toString(), verifier, state };
}

Thirty-two random bytes, base64url-encoded, give a 43-character verifier, the shortest the RFC allows. Python's secrets module gets there the same way:

import base64
import hashlib
import secrets
from urllib.parse import urlencode


def b64url(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()


def start_auth(provider: dict) -> dict:
    verifier = b64url(secrets.token_bytes(32))
    challenge = b64url(hashlib.sha256(verifier.encode()).digest())
    state = b64url(secrets.token_bytes(32))
    query = urlencode({
        "response_type": "code",
        "client_id": provider["client_id"],
        "redirect_uri": provider["redirect_uri"],
        "scope": " ".join(provider["scopes"]),
        "state": state,
        "code_challenge": challenge,
        "code_challenge_method": "S256",
        "access_type": "offline",
    })
    return {"url": f"{provider['authorize_url']}?{query}", "verifier": verifier, "state": state}

If you only need Google, its official samples cover the flow in Python (Flask, with flow.authorization_url and flow.fetch_token) and in Node.js. Google's web-server guide doesn't mention PKCE at all, so add it as your own hardening, not because Google asks.

Step 2: ask for less, then step up

Request the narrowest scope that does today's job, and ask for more when the user asks the agent to do more. A scope is a named permission on the consent screen, such as reading mail or sending it. Google and MCP both let you ask for more later, and HubSpot lets you mark scopes optional at install:

  • Google: set include_granted_scopes, and the new token also covers the scopes granted earlier.
  • MCP: a server answers an under-scoped call with a 403 and insufficient_scope, and the client re-authorizes with the union of old and new scopes, retrying no more than a few times.
  • HubSpot (install time only): scope is required and optional_scope is dropped if the account lacks access; the install fails if the installing user lacks a required scope.

Gmail shows why the order matters. gmail.labels is non-sensitive, gmail.send is sensitive, and gmail.readonly, gmail.modify, and gmail.compose are restricted. Sensitive and restricted scopes can't go into a production app without Google's review, and that review can include a third-party security assessment. So "read-only" sounds like the polite ask and turns out, in Gmail, to be the expensive one.

Start with the smallest scope your first feature needs, and ask for a write scope when the user first asks for a write. A first screen that wants the whole mailbox before the agent has done anything useful is a screen people close. You'll get a better yes in context, right after the user asked the agent to send something.

Step 3: store and refresh tokens per user

Keep each user's tokens in that encrypted, per-user store and nowhere else. Not in a table the agent can query, either, and not in a cache that outlives the user's grant.

Refresh happens outside the agent loop. The agent asks for an action; your backend checks the token, refreshes it if it's about to expire, and makes the call. Merge's guidance adds two rules that keep this safe. Take a lock per credential so two workers don't refresh at once, and persist a rotated refresh token the moment you get it. RFC 9700 requires refresh tokens for public clients to be sender-constrained or rotated. Your server is a confidential client, so that rule isn't yours, but rotation can still find you: Slack rotates refresh tokens only once an app opts in, and Microsoft's replace themselves on each use.

The token that breaks is the one you refreshed twice at once. Two jobs for the same user wake up together and send the same refresh token. The provider rotates on the first, and the second gets invalid_grant. Someone gets paged in the small hours, and a user is asked to reconnect for something they didn't do.

Each provider kills refresh tokens differently (rules as of November 2026).

ProviderWhen the refresh token dies or changesWhat your code does
Google7 days in Testing status (external apps); 6 months unused; over 100 tokens per account per client ID, oldest dropped silently; a password change, with Gmail scopes; revocationPublish the app before real users arrive, and treat a dead token as reconnect
Microsoft90 days by default, 24 hours for single-page apps; each use returns a new refresh token, and the old one isn't revokedSave the new token and securely delete the old one
SlackRotation is opt-in and irreversible once on; with rotation on, access tokens last 12 hours; each refresh token works onceSave the new refresh token from every response
HubSpotAccess tokens currently expire after 30 minutes; the docs don't say whether refresh tokens expire or rotateStore whatever refresh token the response returns

Google's 7-day Testing limit skips apps that ask only for name, email and profile. Salesforce lets admins set a refresh token policy per connected app, so ask your customer's admin before you assume a token lives forever. Managed platforms run the same playbook. Nango, for one, refreshes before expiry and at least every 24 hours to avoid inactivity revocation. It retries failed refreshes and sends a webhook when one fails.

A refresh in TypeScript that takes the lock, re-reads inside it, and persists rotation at once:

// withLock is your cross-process lock (a database row or advisory lock),
// not an in-memory mutex: your workers don't share memory.
export async function accessTokenFor(tenantId: string, userId: string, provider: string) {
  const key = `${tenantId}:${userId}:${provider}`;

  return withLock(key, async () => {
    const cred = await credentials.get(key); // re-read: another worker may have refreshed
    if (!expiresSoon(cred)) return cred.accessToken;

    const res = await fetch(cred.tokenUrl, {
      method: 'POST',
      headers: { 'content-type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({
        grant_type: 'refresh_token',
        refresh_token: cred.refreshToken,
        client_id: cred.clientId,
        client_secret: cred.clientSecret,
      }),
    });
    const t = await res.json();

    if (!res.ok) {
      if (t.error === 'invalid_grant') await credentials.markReconnectRequired(key);
      throw new RefreshFailed(key, t.error); // transient failures retry later, outside the agent
    }

    await credentials.put(key, {
      ...cred,
      accessToken: t.access_token,
      refreshToken: t.refresh_token ?? cred.refreshToken, // persist rotation now
      expiresAt: Date.now() + t.expires_in * 1000,
    });
    return t.access_token;
  });
}
import json
import time
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen


def access_token_for(tenant_id: str, user_id: str, provider: str) -> str:
    key = f"{tenant_id}:{user_id}:{provider}"
    with lock(key):  # your cross-process lock, as above
        cred = credentials.get(key)
        if not expires_soon(cred):
            return cred["access_token"]

        body = urlencode({
            "grant_type": "refresh_token",
            "refresh_token": cred["refresh_token"],
            "client_id": cred["client_id"],
            "client_secret": cred["client_secret"],
        }).encode()
        try:
            with urlopen(Request(cred["token_url"], data=body)) as res:
                t = json.load(res)
        except HTTPError as err:
            error = json.load(err).get("error")
            if error == "invalid_grant":
                credentials.mark_reconnect_required(key)
            raise RefreshFailed(key, error) from err

        credentials.put(key, {
            **cred,
            "access_token": t["access_token"],
            "refresh_token": t.get("refresh_token", cred["refresh_token"]),
            "expires_at": time.time() + t["expires_in"],
        })
        return t["access_token"]

The refresh_token ?? cred.refreshToken line is the whole table in one expression. Keep the new token if the provider sent one, and the old one if it didn't.

Step 4: expired, revoked, reconnect

An expired token and a revoked grant look alike in your logs and need opposite handling. Merge's guidance draws the line well. On an expiry (a 401), refresh and retry. On a revocation or a removed scope (a 403, or a 401 that survives a refresh), stop, pause the user's jobs, and tell the user.

Three flows for one connection: an expired token is refreshed under a lock, the new token saved, and the call retried; a revoked grant or removed scope pauses the user's jobs and sends them a reconnect link; a disconnect revokes the token at the provider and ends revoked

Retrying can't fix a revoked grant, so stop retrying. Picture the customer who removed your app from their Google account on Friday. By Monday the agent has retried all weekend, and your error dashboard looks like an attack you're running on yourself. A 403 means pause, not try harder. Treat an invalid_grant as a dead grant only when it comes back from a refresh you made under the lock with the latest stored token. That rules out the lost race from Step 3. Timeouts and other transient failures are the ones to retry, with backoff.

Grants also die in ways nobody tells you about. On Microsoft, a user or admin can revoke every refresh token at once. A user's password change revokes public-client tokens but leaves confidential-client tokens alive.

When your user disconnects, revoke at the provider, then delete your copy. RFC 7009 defines the call, an HTTPS POST with the token and an optional token_type_hint. The server returns 200 even if the token was already invalid. Revoking a refresh token should also invalidate the access tokens from the same grant. Use each provider's documented endpoint; Google's samples use https://oauth2.googleapis.com/revoke.

Keep a health state per connection (active, needs reconnect, revoked) and a reconnect link the agent can hand the user wherever it failed. Arc0's connection states are one worked version: reconnect_required means fresh consent is needed, and transient refresh failures retry with backoff.

Where on-behalf-of (OBO) and token exchange fit

The documented on-behalf-of (OBO) flow is Microsoft's, and it solves a narrower problem than its name suggests. Gmail and Slack have no equivalent in the docs checked for this post. In Microsoft's identity platform docs (November 2026), OBO is server to server. It turns the user's token for your API into a token for a downstream Microsoft API.

Your middle tier posts to Microsoft's token endpoint with the jwt-bearer grant and the token it received as the assertion. It adds requested_token_use=on_behalf_of and its client secret or a certificate assertion.

POST https://login.microsoftonline.com/<tenant>/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded

grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer
&client_id=<your API's client id>
&client_secret=<your API's secret>
&assertion=<the token your API received>
&scope=<downstream delegated scopes>
&requested_token_use=on_behalf_of

The limits matter for agents. OBO works only for user principals and delegated scopes, not app roles. There's no user interaction, so consent has to be granted up front, and you get a refresh token only if you ask for offline_access. If the downstream API demands MFA under Conditional Access, the token endpoint returns interaction_required with a claims challenge. Your API passes a 401 back so the client can satisfy it.

RFC 8693 is the general version of the idea. Its token exchange grant takes a required subject_token and an optional actor_token. It also separates delegation, where the actor keeps its own identity, from impersonation. Auth0's Token Vault applies the idea to stored external tokens. It holds providers' access and refresh tokens and offers refresh token, access token, and privileged worker exchanges. You may also find an individual IETF draft for agent on-behalf-of flows; it has expired and has no formal standing.

For Gmail and Slack, the answer to "on behalf of users" is the plain one from Step 3: a stored per-user grant that your backend refreshes. OBO answers "my API to Microsoft's API", not "my agent to the user's Gmail", so the Gmail road leads back to a stored refresh token.

MCP: OAuth for interactive clients

When Claude, ChatGPT, or Cursor connects to your MCP server, the client runs the login. Authorization is optional in MCP, though HTTP transports should follow it. When a server implements it, the latest revision (2026-07-28) makes that server an OAuth 2.1 resource server that must publish RFC 9728 metadata. Clients send the RFC 8707 resource indicator on authorization and token requests. They use PKCE and must validate iss (RFC 9207) before redeeming the code.

  • Tokens go in the Authorization header on every request, never in the query string.
  • Your server rejects tokens that weren't issued for it, and never passes a client's token through to another API.
  • Clients can't assume a refresh token is issued, so plan for the person to sign in again.
  • Client ID Metadata Documents are the recommended way to identify clients, and Dynamic Client Registration is deprecated.

Never pass the client's token through to Gmail. That hop proves who the person is to your server and says nothing to Google. Your server still needs the person's own Gmail grant from Step 1. Two logins, one person, and an alphabet of RFCs between them.

Arc0 MCP is one such server: one endpoint bound to one authenticated person, with OAuth for interactive clients. Its latest supported protocol is 2025-11-25, not the newer revision.

The provider's consent screen shows whoever owns the OAuth client that asked. Register your own app and it's your name; use a vendor's app and it's theirs. As of November 2026, Composio's docs say so plainly: with Composio-managed OAuth the screen shows Composio until you use your own credentials. White-labeling its hosted Connect Link changes that page, not the provider's screen. The same holds for managed OAuth in general, Arc0 included.

Owning the app also decides your exit. A refresh token stays bound to the client it was issued to. A confidential client must authenticate to redeem it, so whoever holds the client's credentials decides where it can refresh.

The price of owning the app is calendar time, and for Gmail it can be more:

  • Google: your app name and optional logo come from the OAuth Branding page. Production brand info must be verified before users see it, and every domain must be verified, typically in Search Console. Brand verification also needs a public home page and a privacy policy on the same domain. Its automated review usually takes minutes, and its manual review 2 to 3 business days. Scope review is separate, can bring a third-party security assessment, and has no stated timeline in the docs checked for this post. Until you're verified, an app with sensitive or restricted scopes shows the unverified-app screen and is capped at 100 new users. Changing scopes later can mean verifying again.
  • Microsoft: publisher verification adds a blue verified badge at no charge. Since November 2020, with risk-based step-up consent on, users can't consent to most new unverified multitenant apps asking beyond basic sign-in.

Start verification the week you start the integration. Picture a customer's IT lead squinting at a Google screen: "who is this, and why do they want my mail?" That isn't a ticket you want in launch week.

On Arc0, the hosted Connect page your users see before the provider's screen carries your name and colours (branding). If you want your own OAuth client registrations, Arc0 takes your own OAuth apps on Launch and up.

Multi-tenant isolation and audit

Key every credential and every call by tenant and user, and make cross-user access fail closed. Merge's list says to test expired tokens, revoked grants, missing scopes, and cross-user credential access, and to fail closed. The cross-tenant test is the cheap one: as a user in tenant A, ask for tenant B's credential and expect an error, not a token. Write it before your second customer signs, because after that it's an incident review.

Record every call: which user, which agent, which app and action, which grant, and what came back. When a customer asks what the agent did last Tuesday, "we think it was fine" isn't an answer. In Arc0, the audit log is on every plan, and policies set allow, ask, or deny per scope, per agent, and per customer.

The build-it-yourself checklist

None of these is hard on its own. The work is that all of them run forever, for every provider you add.

  1. Run the authorization code flow with PKCE (S256), a checked state, and exact redirect URI matching.
  2. Ask for offline access where the provider needs it, and handle Google's first-consent-only refresh token.
  3. Store one encrypted credential per user per connector, keyed by tenant and user.
  4. Refresh outside the agent loop, under a per-credential lock, and persist rotated tokens at once.
  5. Split failures: a 401 means refresh and retry; a 403, or a 401 after a refresh, means stop and ask the user.
  6. Revoke at the provider when a user disconnects (RFC 7009 defines the call; use each provider's endpoint), then delete your copy.
  7. Track a health state per connection, with a reconnect link the agent can hand the user.
  8. Request narrow scopes and step up in context.
  9. Register your own OAuth app per provider early: Google's manual brand review takes 2 to 3 business days, and scope review comes on top.
  10. Log every call with tenant, user, agent, and result, and test that cross-tenant access fails closed.

Then plan the exit: know how you'd move every user's tokens elsewhere, and which of them would still refresh without the original client's secret.

The managed version: Arc0 Connect and Vault

Arc0 publishes this blog, so weigh this section with that in mind; each claim links to the docs where you can check it. The idea is the same per-user model with the plumbing already built, so your code shrinks to the parts that are about your product. In the diagram at the top, the green "Backend and vault" box becomes Arc0's job.

  1. Your backend creates the user from its own verified session, then asks for a short-lived Connect link.
  2. Arc0 Connect runs OAuth on a hosted page with PKCE bound to the browser. The link expires 10 minutes after creation and is claimed once.
  3. Signed webhooks confirm it. connection.connected or connection.failed is the authoritative answer; redirects and popup messages are advisory.
  4. Vault keeps the tokens, with per-secret keys bound to tenant and owner and an encryption key per customer, and tokens refresh before they expire.
  5. Calls run server-side, bound to one endUserId, so credentials never pass through the agent or the model.

In code, with the TypeScript SDK (@arc0/sdk, Node.js 22 or later), that's three calls on your server:

import { randomUUID } from 'node:crypto';
import { Arc0 } from '@arc0/sdk';

// Server-side only: keys stay on your server, never in the browser or the agent.
const management = new Arc0({ baseUrl: apiOrigin, apiKey: serverOnlyKey });

// 1. The end user comes from your verified session, not from the request body.
const user = await management.upsertUser({
  externalId: `${session.tenantId}:${session.userId}`,
  name: session.userName,
});

// 2. A short-lived Connect link for one app.
const customer = new Arc0({ baseUrl: apiOrigin, apiKey: serverOnlyKey, endUserId: user.id });
const { url } = await customer.connect({ app: 'github', authMethod: 'oauth' });

// 3. Later, the agent's action runs server-side, scoped to that user.
const receipt = await customer.execute({
  action: tool.action,
  actionVersion: tool.version,
  arguments: { owner: 'octocat', repo: 'Hello-World' },
  idempotencyKey: randomUUID(),
});

The client never retries on its own, so after a timeout you check getExecution(id) instead of sending the write again. For several apps in one go, management.createConnectSession() takes a list of apps and an expiry. The URL it returns is a secret capability (embedded sessions). The Python SDK documents connect and execute; check its docs for the end-user flow before you plan around it.

When a grant breaks, the connection moves to reconnect_required, and you send the user a reconnect link that expires after 10 minutes. Revoking through the API stops local use immediately, though the provider's own retirement of the grant may finish later. Your end users can also see and revoke grants on their connected-apps page. The audit log keeps every call from 7 days on Personal up to 365 on Scale.

You also keep the exit. Token export works any time, on every plan. One caveat: with Arc0's managed OAuth apps, an exported refresh token lacks Arc0's client secret, so refreshing it may still need Arc0. Tokens issued to your own OAuth apps keep working after export. The security page covers encryption and data handling.

Arc0 is younger than most names in this space and has no public case studies. You can start on the free plan and test with real users before you commit, and export means you can leave with your tokens.

Verdict

Build it yourself if you need one or two providers and can staff the verification queue and the refresh code for years. Getting the first token is the easy part; keeping every user's token alive is the job. Otherwise, use a managed option that passes the checklist. It keeps tokens out of the agent, handles refresh and reconnects, logs every call, and lets you export.

On those terms Arc0 is our pick, with the bias disclosed above. You can sign up free, follow the quickstart, and make your first connection with the SDK. Arc0 bills per active connected user, meaning an end user your agent actually acts for. It's free for your first 100 of them. Launch is $99 a month for 1,000, then $0.10 down to $0.03 per user. Failed calls and development mode are free, and the pricing page has the bands.

Get started

One plug. Every app. Any agent.

Your users connect their apps once, under your brand. Your agent, or Claude, ChatGPT and Cursor, acts through one MCP endpoint, with every action on the record.