
Authentication for AI Applications
Authentication for AI applications diverges from traditional human authentication. Because AI workflows inherently involve two identities—the human requesting the action and the non-human agent executing it—a robust system must issue, scope, and track credentials for both. In this first part of a two-part series, we cover the foundational shifts AI introduces to identity management, exploring user-delegated vs. autonomous machine-to-machine (M2M) patterns, token scoping strategies, and how to safely handle agent delegation to third-party APIs and databases.
Authentication for AI applications is the practice of verifying the identity of both the human user and the AI agent acting on their behalf, then issuing short-lived, scoped, auditable credentials to each. Modern AI apps are dual-principal systems: a request typically carries a user identity (sub), a client identity (azp), and an agent identity (act) — and the server must know all three to authorize safely. There are two core patterns: user-delegated agents that act inside a human's session with that user's consent, and autonomous machine-to-machine (M2M) agents that act without a user in the loop. Both are live today — Anthropic reported 97 million+ monthly Model Context Protocol SDK downloads in its December 2025 donation announcement — and both are frequently mis-scoped: 53% of organizations report their AI agents have exceeded intended permissions (CSA, April 2026).
Introduction
AI changes authentication because a single request now carries two identities — the human who asked for the action and the agent that executed it — each with different lifetimes, blast radii, and audit requirements.
What Authentication for AI Applications Means
Authentication proves identity; authorization decides what that identity may do. Both matter more for AI agents than for humans because agents operate at higher request volume, make autonomous decisions, and chain actions across multiple APIs. An AI application is any system where a language model or autonomous process invokes a backend API — in-product copilots, background workers that classify tickets overnight, and external Model Context Protocol (MCP) clients like Claude, Cursor, or ChatGPT invoking your tools. AI authentication therefore covers two identity problems at once: verifying the human user in the normal way (session, OAuth, MFA), and verifying the non-human agent with a separate credential that can be revoked, attenuated, and audited independently.
How It Differs From Traditional Web App Authentication
Traditional web auth assumes one human, one session, one cookie. Modern AI auth assumes one human plus N agents hitting M downstream APIs, with each hop producing its own token. Three shifts result: non-human actors become first-class (machine identities outnumber humans 82:1 per CyberArk 2025 and 144:1 per Entro Security 2025); token volume and lifetime pressure (an agent can issue thousands of requests per minute — short TTLs become mandatory); and delegation chains where each hop needs a verifiable link back to the original human principal. The mechanics (OAuth 2.1, JWT, OIDC) are the same — scale and audit requirements change.
What This Article Covers
This article covers, in order:
- Why AI apps have unique authentication needs
- The two core patterns: user-delegated vs. autonomous M2M
- Token scoping across time, resource, and action
- Delegation patterns
- Multi-tenant isolation
- MCP authentication
- Security and structured error responses
- Implementation with Clerk + Next.js 16
- Choosing an authentication provider
- Quick-reference checklists and an FAQ
Why AI Applications Have Unique Authentication Needs
AI introduces three structural shifts: non-human identities at scale, dual-principal requests, and architectural diversity that blurs the line between client, agent, and server.
Non-Human Identities Enter the Application
A non-human identity (NHI) is any principal that is not a person — service accounts, API keys, workload identities, SPIFFE SVIDs, and now autonomous AI agents. Gartner predicts 40% of enterprise apps will feature task-specific AI agents by the end of 2026 (up from under 5% in 2025), while 97% of NHIs possess excessive privileges and 91% of former-employee tokens remain active (Entro Security 2025). Traditional identity management was built for humans — MFA, password rotation, leavers processes — and those primitives do not map to an agent that may be created mid-request, act once, and never return. 82% of enterprises already have AI agents they did not knowingly deploy (CSA, April 2026) — you cannot authenticate what you cannot see.
Authenticating Both Human Users and AI Agents Simultaneously
Every agent request has three identities the server must track: sub (the user the action is for), azp (the client that initiated the agent — usually your web/mobile app), and act (the agent itself, RFC 8693). Dropping act breaks attribution; dropping sub breaks user-scoped access control; dropping azp means you cannot revoke a compromised client without revoking everyone. The IETF draft OBO for AI Agents v02 codifies this triple with a requested_actor parameter at the token endpoint. Design every token so middleware can answer "who asked?", "through which app?", and "via which agent?" without extra network calls.
Common AI Application Architectures
Three architectures dominate, each with a different auth shape.
- In-session copilot. A sidebar or chat UI reading the signed-in user's data. Reuse the user's session token on each tool call — the agent executes inside the browser's trust boundary. Clerk session tokens (60s TTL, auto-refresh) pass safely into AI SDK
tool()calls for low-risk reads (Vercel AI SDK). - Autonomous worker. Nightly classifier, webhook-driven triage, scheduled cleanup. No user session to inherit. Use Clerk M2M tokens, OAuth Client Credentials, cloud workload identities, or SPIFFE SVIDs; obtain per-user data on demand via on-behalf-of (OBO) token exchange (see On-Behalf-Of Token Exchange) or token vault.
- External MCP client. Your SaaS exposes tools over MCP to Claude / Cursor / ChatGPT. The external agent is an OAuth client of your app. Auth uses OAuth 2.1 + PKCE; the user consents once, tool invocations are verified server-side. The MCP Authorization Spec mandates OAuth 2.1 for HTTP transports and forbids it for stdio (which uses environment credentials).
Modern AI SaaS typically runs all three at once.
Foundational Authentication Concepts (Quick Refresher)
Skip this subsection if you already know OAuth, JWTs, and token lifetimes.
OAuth is a delegation protocol; OpenID Connect layers identity on top. Four grant types matter for AI: Authorization Code + PKCE for user-delegated agents (RFC 6749), Client Credentials for M2M, Token Exchange for on-behalf-of (RFC 8693), and Device Authorization for headless CLIs. OAuth 2.1 (draft) removes Implicit, mandates PKCE, and recommends sender-constrained tokens.
Three credential types you will issue to agents:
- Session tokens — short-lived JWTs tied to a browser session (Clerk default: 60s TTL, 50s refresh).
- API keys — long-lived, scope-bounded, no built-in expiration, server-revocable. Use for simple internal S2S (Cloudflare comparison).
- Service credentials — cloud-managed workload tokens (AWS IAM Roles, Entra Workload Identities, GCP Service Accounts, SPIFFE SVIDs) that auto-rotate and never hold static secrets.
Token lifetimes: access tokens ≤ 1 hour (≤ 15 minutes for high-privilege actions per RFC 6750 / RFC 9700); refresh tokens rotated every use with automatic reuse detection (Auth0).
Two Core Patterns for AI Agent Authentication
Every AI auth design starts with one binary question: is a human in the loop? If yes, use Pattern 1: user-delegated — the agent acts inside the user's session, with consent, bounded by the user's permissions. If no, use Pattern 2: autonomous machine-to-machine — the agent acts on its own identity with a separate credential. Most production systems run both.
Pattern 1: User-Delegated AI Agents (Human-in-the-Loop)
When to use: the agent acts synchronously during a user session with the user's consent — in-product copilots, chat UIs, prompt-triggered tool calls. The decisive test: if the action should never outlive the user's active session, use this pattern.
Flow and token shape: OAuth 2.1 Authorization Code + PKCE, producing an access token with sub = user_id, aud = your resource server (mandatory per RFC 8725), short TTL (1 hour max, 15 minutes for sensitive actions), and scopes limited to the user's current capabilities. Optionally issue a derived JWT from a Clerk JWT template embedding agent context (agent_id, tool_scopes, session_id). The consent screen should surface the agent identity explicitly (Curity).
Example — chatbot that reads a user's calendar: user signs in → chat UI asks about tomorrow's calendar → agent triggers a Google OAuth consent flow for calendar.readonly → backend exchanges the code, stores the refresh token in a server-side token vault, returns a short-lived access token to the agent → agent calls Google Calendar, never touching the refresh token. Vault pattern: Auth0 Token Vault, Anthropic Managed Agents Vaults, AWS Bedrock AgentCore Identity.
Pattern 2: Autonomous AI Agents (Machine-to-Machine)
When to use: the agent runs without a user in the loop — background workers, scheduled jobs, webhook-driven triage, batch processors. The decisive test: if the agent acts when no user is online, use this pattern.
Flow and credential shape: two industry approaches. (1) OAuth Client Credentials (RFC 6749 §4.4) with JWT Bearer Assertions (RFC 7523) replacing the static client secret — MCP's M2M extension uses this shape (MCP OAuth Client Credentials extension). (2) Clerk M2M tokens — a Clerk M2M "scope" is a communication graph (which machine may talk to which), not an OAuth capability scope. As of June 2026, Clerk does not yet support the OAuth Client Credentials flow (Clerk Machine Auth Overview). Both issue an access token whose sub is the machine identity; custom claims identify the specific agent; tokens are short-lived and revocable.
Example — background ticket classifier: worker mints a Clerk M2M token with clerkClient.m2m.createToken({ tokenFormat: 'jwt', secondsUntilExpiration: 3600 }), calls your backend; the route handler runs auth({ acceptsToken: ['m2m_token'] }) and verifies custom claims. Every update records agent_id alongside updated_by. For actions needing the ticket owner's permissions, the agent performs OBO token exchange (see On-Behalf-Of Token Exchange) instead of reusing its own M2M token.
Choosing Between the Two Patterns
Use this decision table for any new agent action.
Token Scoping for AI Agents
Scoping is the single most impactful control you can apply to AI agents. Layer three controls — time, resource, action — and you bound the blast radius of every compromised token. Skip any layer and a stolen or manipulated credential gains far more reach than the agent was ever supposed to have.
Why Scoping Matters More for AI Than for Humans
Agents make more requests per unit time and take more autonomous decisions than humans, so over-permission compounds fast — a single scope bug multiplied across 10,000 nightly runs is a different incident than one misclicked human. 53% of organizations report AI agents have exceeded their intended permissions (CSA, April 2026); 51% lack a formal revocation process and credentials remain active 47 days on average past need (Okta). Prompt injection (OWASP LLM01) turns any over-scoped token into a potential lateral-movement vector; the OWASP Top 10 for Agentic Applications 2026 lists Identity / Privilege Abuse (ASI03) and Tool Misuse (ASI02) as top-3 risks.
Time-Limited Tokens
Default to ≤ 1 hour for user-context access tokens and ≤ 15 minutes for high-privilege actions (RFC 6750, RFC 9700). Rotate refresh tokens on every exchange with automatic reuse detection — Auth0's pattern invalidates the entire token family on a stale submission (Auth0) — and pair with sender-constrained refresh tokens via DPoP (Demonstrating Proof-of-Possession) or mTLS so a stolen token cannot be replayed without the private key (WorkOS — DPoP). Refresh proactively with a 5-minute buffer (Scalekit); Clerk Core 3 does this inside the SDK (changelog). Verify exp server-side — never trust client-side time. If an agent may outlive the user session, swap to a service credential before the session ends.
Resource-Specific Permissions
OAuth scopes are coarse capability boundaries (contacts:read, contacts:write, crm.write:acme). Users can grant less than requested during consent (Auth0); Descope's progressive-scoping patterns map agent tools to scope bundles. Scopes alone are too coarse for agent safety — enforce per-endpoint and per-record decisions in middleware from the verified JWT claims. Rich Authorization Requests (RFC 9396) add an authorization_details parameter that carries structured permissions like {"type":"payment","amount":500,"merchant":"acme"} — a better fit for agent actions than a blunt payment:write scope (Stytch, Curity).
Action-Based Restrictions
Default to read-only; require explicit opt-in for write. The GitHub MCP server exposes a production example — X-MCP-Readonly: "true" disables every mutating tool without changing scopes (GitHub).
For finer control, add fine-grained authorization — relationship-based access control (ReBAC), Zanzibar-style (Google Zanzibar). Scopes answer "can this token write to the CRM?"; FGA answers "can this specific agent, acting for this specific user, update this contact record?". Clerk does not provide FGA natively; the recommended pattern is a composition: Clerk supplies identity context in the JWT (user_id, org_id, org_role, agent context from user.public_metadata), and an FGA engine — OpenFGA, Auth0 FGA, Oso, Cerbos, or Permit.io — reads those claims and answers resource-level questions. Clerk's org permissions handle most RBAC needs.
Combining All Three Scoping Strategies in Practice
Layered scoping is the norm for production agents. A single tool call might carry:
- A token valid for 15 minutes (time limit).
- Scope
crm.write:acme(resource scope bound to a specific tenant — Descope). - A middleware check that calls FGA with
(agent_id, "update", contact_123)before the update executes (per-action).
Compromise any one layer and the other two still bound the blast radius.
AI Agent Delegation Patterns
Delegation means an agent acts with another principal's authority — a user's, another agent's, or the organization's. Every production agent hits four delegation surfaces: third-party APIs (Gmail, Slack, GitHub), your internal database, in-app user data (via your backend), and other agents in a multi-agent pipeline. Each surface has a canonical pattern.
Delegation Pattern: Agent Accessing Third-Party APIs
For Gmail, Slack, GitHub, and similar, use OAuth 2.1 Authorization Code + PKCE requested in the user's name. The critical design point is that the agent never sees the refresh token — it lives server-side in a token vault, and the agent asks the vault for a short-lived access token on each call.
Canonical implementations: Auth0 Token Vault (RFC 8693 internally, pre-built Google / Slack / GitHub / Microsoft connections), Anthropic Managed Agents Vaults (mcp_oauth and static_bearer types, workspace-scoped, write-only fields), AWS Bedrock AgentCore Identity, and Descope Outbound Apps.
Storing and Refreshing Third-Party Tokens
A production token vault needs: KMS-backed encryption at rest; a write-only API (secret fields never leave the vault); per-user isolation; refresh orchestration on expiry; reuse detection that invalidates the family on replay; and revocation hooks fired on user sign-out, role change, or disconnect.
Delegation Pattern: Agent Performing Database Operations
Agent-to-database delegation enforces tenancy at two layers: the application layer (middleware checks on every request) and the database layer (row-level policies the agent cannot bypass). Agents that hit the database directly should connect as a dedicated Postgres role without BYPASSRLS. Enable Postgres Row-Level Security on every multi-tenant table with a policy keyed to a session variable the middleware sets per request (Supabase RLS, Drizzle ORM RLS).
ALTER TABLE contacts ENABLE ROW LEVEL SECURITY;
CREATE POLICY agent_tenant_scope ON contacts
USING (tenant_id = current_setting('app.current_tenant_id')::INT);Middleware sets app.current_tenant_id from the verified JWT's org_id claim at the start of each transaction. RLS becomes the last line of defense — even if a route handler forgets a tenant check, the database refuses cross-tenant reads.
For audit, include agent_id, user_id, and trace_id on every log row, and set a per-transaction application name so Postgres logs carry the agent identity on every query (SET LOCAL application_name = 'agent-' || current_setting('app.agent_id');). See LoginRadius and ISACA — Auditing Agentic AI for the full field set.
Delegation Pattern: Agent Managing User Data Inside Your App
On-Behalf-Of Token Exchange
An autonomous agent often needs to act on a specific user's data. The standards-based approach is OAuth 2.0 Token Exchange (RFC 8693): subject_token = user's token, actor_token = agent's token, response = new token with sub = user_id and act = agent_id. The most deployed reference is Microsoft Entra's jwt-bearer OBO flow, extended in Entra Agent ID specifically for agent clients.
Clerk note: Clerk does not currently implement RFC 8693 natively. The practical workaround: validate the user session at the edge, then issue a JWT from a custom template that embeds user identity (sub, org_id, org_role) and agent context (agent_id, tool_scopes). Downstream services verify that JWT against Clerk's JWKS.
Propagating User Identity to Downstream Services
Validate once at the edge, then propagate a signed identity token to each downstream service, which verifies locally against the JWKS. A service mesh or API gateway enforces that every internal call carries a valid token (GitGuardian — OAuth for MCP enterprise patterns); HashiCorp Vault for AI Agents threads an X-Correlation-ID through the stack for end-to-end tracing.
Delegation Pattern: Agent-to-Agent Handoffs
The A2A Protocol (April 2025, now Linux Foundation-governed) defines HTTP + JSON-RPC 2.0 for agent-to-agent comms with five auth schemes (Bearer, OAuth Authorization Code, OAuth Client Credentials, API Key, HTTP Basic). Each agent publishes an agent card advertising capabilities and required auth. When agent A calls agent B, A obtains a token scoped to B's resource server via a token-exchange endpoint that records A as azp and appends A to the act chain (Stytch A2A OAuth guide; IETF attenuating tokens draft for scope reduction).
Every action in a chain must remain attributable to the original user. Three mechanisms: pass sub through unchanged; append each agent to a nested act claim for the full delegation trail (IANA JWT Claims Registry); and reduce scopes at each hop so downstream agents cannot exceed the caller (OIDC-A paper, AAuth draft).
Next Steps
We have covered the foundational patterns of AI authentication: handling user-delegated vs. autonomous agents, bounding blast radius through granular time, resource, and action scoping, and safely orchestrating delegation across APIs and databases. In Part 2, we will explore the system-level challenges of AI identity: building secure multi-tenant architectures, connecting Model Context Protocol (MCP) servers safely, navigating the OWASP Top 10 for Agentic Applications, and a concrete implementation guide using Clerk and Next.js 16.
FAQ
In this series
- Authentication for AI Applications (you are here)
- Authentication for AI Applications - Part 2