Let an AI agent authenticate with third-party APIs securely

An agent that posts to Slack, reads a calendar, or merges a pull request needs authority from a real user. The unsafe pattern is to paste that user's API key or password into agent config, a `.env` file, or the model context.

Secure third-party API auth means the owner approves once on a hosted consent screen. The agent then uses short-lived, scoped bearer tokens. Refresh happens out of band. Revoke ends the whole session when trust breaks.

The sections below are a build sequence for developers shipping unattended agents. They assume you already chose OAuth over shared secrets. For why agents stress OAuth at all, read the identity essay on autonomous software first.

What you are building (and what the agent is not)

The agent is software acting on behalf of a user or organisation. It is not the user. Your data model must record both the human owner and the agent identity with its scopes and grant time.

Third-party APIs expect a bearer token or OAuth access token tied to that delegation. They do not expect your agent to impersonate a browser session with a saved password.

Unattended use is the default for agents on a schedule. Consent is a single moment. Exercise of authority can run for weeks. That gap is why rotation and fail-closed revoke are not optional extras.

Step 1: Separate human login from agent credentials

Before you wire Gmail or GitHub, decide which client receives which token:

Human browser client

Interactive login for your dashboard. Narrow scopes. Short sessions are fine.

Agent client

Public or confidential client registered for headless refresh. PKCE on every authorisation. No password grant.

Distinct agent subject

Store agent id, owner id, and granted scopes. Auditing and per-agent revoke depend on this row.

Step 2: Run hosted consent once, then unattended refresh

The owner must approve on a page you control, not inside the chat UI:

Authorisation URL

Send the owner to the upstream IdP or your broker with `response_type=code`, client id, redirect URI, scopes, and PKCE challenge.

S256 PKCE

Treat every agent client as public. Proof Key for Code Exchange blocks a stolen code from being redeemed elsewhere.

One-time code exchange

Redeem the code exactly once server-side. Never hand the code or refresh token to the model.

Token storage

Keep refresh families in your secret store or token service. The agent runtime receives only access tokens with minutes of life.

Step 3: Scope access tokens to the job

Least privilege is the main control when nobody is watching:

Per integration

Calendar read should not imply send-mail. Split tools into separate OAuth scopes where the vendor allows it.

Per tenant

Multi-tenant products must not share one founder API key across customers. Each end user grants their own token family.

Per agent

When one company runs several agents, map each tool call to the agent id that is allowed to use that scope.

Step 4: Rotate refresh tokens and revoke families on replay

Long-running agents need refresh. Refresh must be safe under theft:

Rotation

Each refresh issues a new refresh token and invalidates the previous one. Stolen refresh credentials have a short window.

Family revocation

If a spent refresh token appears again, revoke the entire family. That pattern means capture, not a benign retry.

Fail-closed introspect and revoke

When the token service is unreachable, deny the API call. Failing open turns an outage into a bypass.

Relay-style OAuth broker vs Vault-style signing

ProblemFitWhat the agent never holds
Call third-party HTTP APIs as the user (Gmail, GitHub, X)OAuth broker such as Empyre Relay or your own token serviceUpstream password, root API key, or long-lived refresh in prompts
Sign payloads or decrypt with material that must not leave storageSigning relay such as Empyre VaultPrivate key bytes; only signatures or ciphertext exit the enclave
Route traffic with rate limits but static service credentialsHTTP gateway (see API relay article)Does not replace user delegation when the API requires OAuth

When to buy Relay vs build on Auth0, Clerk, or Okta

If you already run a mature IdP for human login, extending it for machine clients is often correct. Turn on PKCE, rotation, and narrow scopes explicitly. Agent-shaped products argue those should be defaults because silent misconfiguration is common.

Empyre Relay at relay.empyre.dev is OAuth for AI agents with hosted consent, mandatory S256 PKCE, one-time codes, refresh rotation with family revocation, and fail-closed revoke and introspect. The npm package is @empyre/relay-sdk 1.0.0 on registry.npmjs.org, read 2026-09-26. Relay returned HTTP 200 the same day. Relay has been feature-frozen since 2026-07-10. Scoped GET /relay/oauth/userinfo (2026-08-06) returns consented profile claims.

Empyre Vault at vault.empyre.dev is the sibling when the risk is key exfiltration, not login-as-user. @empyre/vault-sdk 1.0.0 on registry.npmjs.org, read 2026-09-26. Keys never leave; signatures come out.

For the buyer checklist on choosing a provider, use OAuth for AI agents. For SDK and MCP install intent, use Relay plugin. For auth-broker vs HTTP gateway wording, use API relay. Product CTAs live on OAuth for AI agents — Relay product page.

What not to do

These patterns fail audits and leak in production:

Password or root API key in agent config

Grants full account access with no per-tool limit and no audit trail.

Shared tenant secret for all customers

One rotation locks out every user. One leak exposes every account.

Secrets in prompts, logs, or commits

Models echo context. See how agents leak API keys for the mechanism list.

Treating the agent as the user

You cannot revoke one automation without locking the founder.

Fail-open token checks

If verification times out, the answer must be deny, not allow.

Minimal agent token exchange (Relay SDK)

The agent proves its own identity to your app, then receives a short-lived scoped token. Owner approval may be pending on first connect:

import { RelayClient } from "@empyre/relay-sdk";

const relay = new RelayClient({ audience: "your-api.example" });

const result = await relay.authenticateAgent(
  process.env.RELAY_AGENT_ID,
  process.env.RELAY_AGENT_SECRET,
);

if ("status" in result && result.status === "pending_approval") {
  // Owner approves on hosted consent; retry after approval.
} else {
  await callThirdPartyApi(result.access_token);
}

Wire third-party APIs without giving the model the secret

Your server or a dedicated broker holds refresh tokens. Tool handlers receive only an access token or a broker session id.

When the agent calls a tool, validate agent id and scope server-side before forwarding to Gmail, Stripe, or GitHub.

Log client id, agent id, scope, and upstream route. Do not log bearer tokens or refresh material.

Generated companies on Empyre still need the same discipline for founder integrations. Relay solves identity for apps you build. It does not remove per-vendor OAuth inside a company operator.

Common questions

Can I use a long-lived API key if the agent runs internally?

For a single-tenant tool you fully control, sometimes. The pattern breaks for multi-tenant products or any agent that reads user mail or repos. OAuth delegation scales revoke per user.

Is PKCE only for mobile apps?

No. Public agent clients should use S256 PKCE on every authorisation, regardless of whether you also store a client secret.

How is this different from Giving AI agents an identity?

That article explains why unattended software inverts OAuth's human-present assumption. This page is the how-to sequence for wiring third-party APIs today.

How is this different from OAuth for AI agents (the checklist article)?

The checklist compares providers and requirements. This page walks implementation order: consent, PKCE, scope, rotation, revoke, and broker choice.

When do I need Vault instead of Relay?

When the agent must sign or decrypt with private key material that must never enter the runtime. OAuth solves delegated login to third-party APIs.

What npm package implements Empyre Relay?

`@empyre/relay-sdk`, version **1.0.0** on registry.npmjs.org on 2026-09-26. Scope is `@empyre`, not a fictional `@empyre/relay` name.

Try Empyre free for 3 days

Describe a business in plain words and watch eight AI agents build and deploy it. Starter is free for the first 3 days.

Start your free trial

Related

Last updated 2026-09-26. Competitor descriptions reflect each product's publicly documented capabilities at that date; they change often, so check the source before relying on a detail.