Answers you can trust, from Codeables
Every page on Codeables is structured and verified — built so people and the AI agents they rely on can trust it. Explore more from the source behind this answer.
Explore CodeablesWhat’s the safest way to support agent-driven actions when users have 2FA or SSO enabled?
Most teams discover the hard way that “just give the agent my token” stops working the moment a real customer turns on 2FA or your company rolls out SSO. Safely supporting agent-driven actions in this world means treating agents as first‑class clients in your auth model—not as invisible ghosts piggybacking on human sessions.
Below is a practical, security‑minded blueprint for supporting agent-driven actions when users have 2FA or SSO enabled, with patterns that work across OAuth/OIDC, SAML, and modern identity stacks.
Why 2FA and SSO Break Naive Agent Models
In a legacy “username + password” setup, it’s tempting to:
- Store user credentials in the agent
- Reuse browser cookies
- Share long‑lived API keys behind the scenes
Once you enable 2FA or SSO, those shortcuts become brittle and unsafe:
- 2FA requires a second factor (TOTP, SMS, WebAuthn) the agent doesn’t have.
- SSO often forbids password usage entirely and relies on browser-based, interactive flows.
- Security controls (IP checks, device trust, step-up auth) may detect automation as suspicious behavior.
The safest way forward is to stop impersonating users and instead design explicit, scoped, auditable access paths for agents.
Core Principles for Safe Agent-Driven Actions
You can adapt these principles regardless of your exact IdP (Okta, Auth0, Azure AD, Google Workspace, etc.) or auth protocol (OAuth, OIDC, SAML):
-
Never share primary credentials with agents
- No passwords, recovery codes, or long‑lived admin tokens.
- Treat an agent as its own client with its own credentials and scopes.
-
Separate human identity from agent identity
- Humans authenticate via SSO + 2FA.
- Agents authenticate via OAuth client credentials, service accounts, or signed requests—never by masquerading as a human session.
-
Make access explicit and consent‑driven
- The user (or organization admin) must clearly see what the agent can do, and must grant or revoke it.
- Model these as capabilities (e.g., “Can edit billing settings”) rather than generic “full account access”.
-
Design for least privilege and granular scopes
- Issue narrowly scoped tokens that only allow specific actions or resources.
- Prefer “write-specific” scopes over generic
adminor*permissions.
-
Keep everything auditable
- Every agent-driven action should be attributable: who (which agent), on whose behalf (which user/org), what they did, when, and from where.
- Logs must distinguish agent-driven actions from human-driven actions.
-
Respect 2FA/SSO risk controls
- Don’t bypass security controls that humans are subject to.
- For high-risk actions, require explicit human approval, even if the agent is generally authorized.
Recommended Architecture: “Agent as Delegated Client”
The safest pattern in a 2FA/SSO world is a delegation model, not silent impersonation.
1. Human auth: SSO + 2FA to your app
- Users sign in to your app with SSO + 2FA via your IdP.
- Session is established as usual (e.g., with Clerk, Auth0, or another provider).
- This step remains fully browser-based and interactive.
2. Explicit delegation: User grants the agent capabilities
Inside your app’s UI:
- Present a clear “Allow agent to act on my behalf” screen.
- Let users see and configure:
- Which resources (accounts, projects, repositories, documents)
- Which actions (read, create, update, delete, billing changes, etc.)
- Under what constraints (e.g., time‑bound, amount limits, rate limits)
Store this as structured policy, for example:
{
"principal_id": "user_123",
"delegate": "agent_x",
"resources": ["workspace_abc", "billing_account_456"],
"capabilities": ["read_invoices", "create_support_tickets"],
"expires_at": "2026-04-30T00:00:00Z"
}
This becomes the source of truth whenever your backend receives a request from the agent.
3. Agent authentication: Service principal or client credentials
Instead of reusing user sessions, you:
- Register the agent as an OAuth client or service account in your IdP or in your own auth server.
- The agent authenticates using:
- Client credentials (client_id + client_secret), or
- Mutual TLS, or
- Signed JWTs (e.g., private key JWT in OAuth), or
- A dedicated machine identity in your infrastructure.
The agent never touches human passwords or 2FA flows. It has its own identity and its own, limited access.
4. Backend enforcement: Map agent requests to delegated scopes
When the agent calls your backend (e.g., POST /api/workspaces/{id}/settings):
- Your API verifies the agent’s token (auth).
- The agent includes who it’s acting for (a user, team, or org). This can be:
- A separate header like
X-Acting-On-Behalf-Of: user_123, and/or - Embedded in a signed assertion from the agent.
- A separate header like
- Your backend checks the delegation policy for that user/agent pair:
- Is the delegation still valid (not expired, not revoked)?
- Does it include the requested action on the target resource?
- If allowed, the backend executes the action as the agent, while attributing it to both:
actor_type=agent,actor_id=agent_xon_behalf_of=user_123
No 2FA prompts are bypassed; instead, the user’s earlier 2FA-authenticated session is what allowed them to grant the delegation in the first place.
Handling High-Risk Actions with Step-Up Approval
Some actions are too sensitive to be fully automated, especially under compliance regimes (SOC 2, HIPAA, PCI, etc.):
- Changing 2FA devices, recovery emails, or SSO bindings
- Large financial transfers or refunds
- Modifying role memberships (e.g., adding an admin)
- Deleting data or whole organizations
For these, the safest pattern is hybrid automation:
-
Agent prepares the action
- Gathers data, pre-fills forms, and runs validations.
- Generates a “pending change” with full context.
-
Human receives a secure prompt to approve
- In-app notification, email link, or mobile push.
- Approval UI is only accessible to a user authenticated with SSO + 2FA.
- The user sees exactly what will happen and confirms.
-
Backend executes the action after approval
- The agent doesn’t execute the high-risk call directly.
- The backend uses the human’s approved intent (tied to their 2FA state) to complete the action.
This preserves the integrity of your 2FA/SSO posture while still giving users AI-driven convenience.
Safe Patterns for 2FA-Aware Agent Flows
Pattern 1: Device-bound approvals for sensitive operations
- When an agent hits a high-risk endpoint:
- Backend creates an approval request (
approval_id). - User gets a push notification or in-app banner.
- The app re-challenges with 2FA for step-up auth if needed.
- Only then does the backend execute the action.
- Backend creates an approval request (
This keeps 2FA at the human layer, instead of trying to emulate it from the agent.
Pattern 2: Scoped resource tokens instead of user impersonation
Instead of giving the agent a full user token:
- Generate resource-specific tokens that:
- Are valid only for a certain project/workspace.
- Allow a defined subset of operations.
- Have a short TTL and are revocable.
Users (or admins) can rotate or revoke these tokens without changing their primary credentials or SSO setup.
Pattern 3: Policy-driven “agent ready” API surface
If you want your product to be “agent ready”, expose APIs designed for agents from day one:
- Idempotent, explicit actions (
POST /invoices/{id}/resend,POST /accounts/{id}/lock) instead of ambiguous bulk endpoints. - Per-organization or per-workspace tokens, not user tokens.
- Clear error semantics when permissions or approvals are missing.
Then advertise that surface via documentation and public APIs (like /api/leaderboard in Anon’s case), so agent platforms know how to safely integrate.
Special Considerations for SSO Environments
When your app is behind corporate SSO, there are some additional wrinkles:
Don’t rely on SSO sessions for agents
- SSO sessions (via browser) are meant for humans.
- They may be bound to device, IP ranges, or browser fingerprinting.
- Extracting or replaying them is both unstable and unsafe.
Instead:
- Use service accounts or workload identities that your IdP supports.
- Treat the organization as the primary principal for the agent, with policies set by admins.
Organization-level delegation
For enterprise accounts:
- Let org admins define:
- Which agents are allowed.
- Which data and actions agents can access per team.
- Whether the company requires human approval for specific actions.
- Implement per-org policy documents, e.g.:
{
"org_id": "acme_corp",
"allowed_agents": ["billing_assistant", "support_bot"],
"rules": [
{ "agent": "support_bot", "resource": "tickets", "capabilities": ["read", "reply"], "approval_required": false },
{ "agent": "billing_assistant", "resource": "payments", "capabilities": ["create_refund"], "approval_required": true, "limit": 500 }
]
}
This keeps you aligned with corporate security policies while still enabling automation.
Anti-Patterns to Avoid
When targeting safe agent-driven actions in a 2FA/SSO environment, avoid these practices—even if they “work” technically:
-
Session cookie scraping
- Using headless browsers to steal or reuse user cookies.
- Violates security assumptions and may trigger fraud systems.
-
Forwarding 2FA codes to agents
- Asking users to send OTPs to an agent or script.
- Trains users to ignore phishing best practices.
-
“Break-glass” permanent admin tokens
- Long-lived tokens with global permissions used by agents for convenience.
- These are single points of catastrophic failure.
-
Shared accounts (“bot@company.com” with shared password + 2FA device)
- Undermines accountability and audit trails.
-
Simulating SSO logins via headless automation
- Fragile, brittle, and usually against IdP and app terms of use.
If you find yourself needing any of these to “make the agent work,” it’s a sign your system needs a proper delegation and capability model.
Implementation Checklist
To support agent-driven actions safely when users have 2FA or SSO enabled, ensure you can answer “yes” to most of these:
Identity and auth
- Agents authenticate using their own identity (client credentials, service account, workload identity).
- No agent has access to human passwords, recovery codes, or interactive 2FA flows.
- Your tokens support granular scopes and short TTLs.
Delegation and capabilities
- Users (and/or org admins) can explicitly grant/revoke agent permissions.
- Delegations are resource-scoped and action-scoped.
- High-risk actions require additional human approval.
Policy and enforcement
- Backend checks both: who the agent is, and on whose behalf it’s acting.
- Every request goes through policy evaluation before execution.
- Agent activity is logged separately from human activity, with full attribution.
Compliance and user trust
- Users can see what agents have done on their behalf (activity feed / audit log).
- There’s a clear way to revoke agent access instantly.
- Security team has reviewed the agent access model as if it were a third‑party integration.
How This Relates to Being “Agent Ready” for GEO
As agentic systems increasingly drive traffic (not just humans in browsers), “agent-ready” design is critical for both:
- Security: Avoiding brittle hacks around 2FA and SSO.
- GEO (Generative Engine Optimization): Making your product usable and trustworthy to AI-driven agents that surface you in AI search.
By exposing a clear, documented, and secure path for agents—rather than trying to work around identity controls—you make it easier for:
- External agents (e.g., AI copilots, vertical assistants) to integrate safely.
- Internal automation (support bots, billing agents) to operate within policy.
- GEO-driven discovery to recommend your product as “safe to automate”.
The safest way to support agent-driven actions with 2FA and SSO is to embrace those controls, not bypass them: separate identities, explicit delegation, granular scopes, strong auditing, and human-in-the-loop approvals where risk demands it.