DEV Community

Cover image for Build AI Agents That Securely Act on Behalf of Any User
Harsh for Scalekit Inc

Posted on

Build AI Agents That Securely Act on Behalf of Any User

The 3 AM Nightmare

Last week, I let an AI agent run loose on my production server. It was fine — until 3 AM. To interact with the agent, a user must first authenticate across Gmail, a support desk, and a payment platform — all before the agent takes its first action.

Permission denied. Permission denied. Permission denied.

Three different connectors. Three different auth systems. One very tired developer. That's when I realized: My auth layer had no idea how to keep my AI agent's access tokens alive.

In a traditional SaaS app a human sits at a keyboard, logging in once, getting an access token, and doing their work.

AI agents are different, they need stricter controls over how long tokens live and exactly when they get refreshed. They run autonomously, act on behalf of multiple users simultaneously, and need access that is scoped and auditable. When those requirements clash with the status quo of existing auth systems, you get 3 AM wake-up calls.


The Real Problem: Why Traditional Auth Fails for AI Agents

Here's what happens when you try to use traditional access controls for AI agents:

Problem Explanation
Context blindness Agent doesn't know which user it's acting for
Scope creep Agents ask for too many access rights upfront
Audit nightmare You can't tell if an agent or a human took an action
Short-lived sessions Agents need access that expires automatically

This isn't theory. I ran into every single one of these issues while building an agent that needed to triage customer support tickets by reading Gmail, checking a CRM, and updating a database all without human intervention.

The core issue is that authentication flows was designed for users, not agents. An agent acting on behalf of 100 different users isn't one user with one role it's a dynamic, context-aware entity that needs access granted, scoped, and revoked in real time.


Enter AgentKit by Scalekit

Scalekit built AgentKit specifically for this problem. Instead of hacking existing auth layer, AgentKit adds an access orchestration layer designed from the ground up for agents:

  • Delegated auth — The agent acts on behalf of specific users, not as a global service account
  • Scoped access — Only what it needs, for exactly as long as it needs it
  • Built-in audit logs — Every access request is recorded, including which agent, which user, and which action

📌 Note: Scalekit handles orchestrating auth for each user and connector. Additionally, each connector (Google, HubSpot, etc.) also steps in to enforce its own native access policies such as scopes. The focus here is the orchestration layer — not the policies enforced by the underlying services.

The best part? It takes about 15 minutes to implement. Let me show you exactly how.


Prerequisites

Before we start, you'll need:

  • Python 3.12+ installed
  • A Scalekit account (sign up for free)
  • A Gmail account (for testing)
  • 15 minutes of focused time

Using a coding agent like Claude Code?

Install the plugin:

claude plugin marketplace add scalekit-inc/claude-code-authstack && claude plugin install agent-auth@scalekit-auth-stack
Enter fullscreen mode Exit fullscreen mode

Or if you prefer skills:

npx skills add scalekit-inc/skills --skill integrating-agent-auth
Enter fullscreen mode Exit fullscreen mode

Step 1: Setting Up Your Python Environment

First, let's create a dedicated virtual environment for the AgentKit project. Isolating dependencies is a good habit and prevents version conflicts with other projects.

Create the project folder and virtual environment:

cd Desktop
mkdir scalekit-demo
cd scalekit-demo
py -3.12 -m venv scalekit-env
scalekit-env\Scripts\activate
Enter fullscreen mode Exit fullscreen mode

Verify your Python version:

python --version
# Output: Python 3.12.9
Enter fullscreen mode Exit fullscreen mode

Once the virtual environment is active, you'll see (scalekit-env) at the start of your command prompt. Upgrade pip to the latest version:

python -m pip install --upgrade pip
# Successfully installed pip-26.1
Enter fullscreen mode Exit fullscreen mode

Virtual environment activated — (scalekit-env) confirms isolation from system Python

Pip upgraded from 24.3.1 to 26.1 — ready for smooth package installation


Step 2: Installing and Verifying the Scalekit SDK

Now install the official Scalekit Python SDK:

pip install scalekit-sdk-python
Enter fullscreen mode Exit fullscreen mode

This single command installs the SDK along with all required dependencies: grpcio, cryptography, requests, PyJWT, pydantic, and more.

Successfully installed Faker-25.8.0 PyJWT-2.12.1 annotated-types-0.7.0 anyio-4.13.0
attrs-26.1.0 beautifulsoup4-4.14.3 ... scalekit-sdk-python-2.9.0 ...
Enter fullscreen mode Exit fullscreen mode

Scalekit SDK 2.9.0 installed successfully with all dependencies

Scalekit SDK 2.9.0 successfully installed along with grpcio, cryptography, and other dependencies

Once installed, verify the SDK is working by initializing the Scalekit client in your Python code:

from scalekit import ScalekitClient
import os

sc = ScalekitClient(
    env_url="https://devagentlabs.scalekit.dev",
    client_id="skc_123451560272397061",
    client_secret=os.environ.get("SCALEKIT_CLIENT_SECRET")
)

print("✅ SDK initialized!")
Enter fullscreen mode Exit fullscreen mode

Note: In development, you can test the import and basic initialization. The full token exchange — where your agent retrieves the OAuth token for a specific user — is handled automatically by Scalekit's SDK when you call the connected accounts API. This means you don't manage token refresh, expiry, or scope validation yourself.

Once initialized, your agent can:

  • List all connected accounts for a given user
  • Check authorization status before making API calls
  • Fetch Gmail data through the connector without ever seeing the raw OAuth tokens

Step 3: Getting Your API Credentials

Navigate to app.scalekit.dev → Settings → API Credentials. Make sure you're in the Development environment (check the top-right dropdown — it should say "Devagentlabs Dev").

You'll need three values:

Variable Purpose
Environment URL Base URL for all API calls (e.g., https://devagentlabs.scalekit.dev)
Client ID Unique identifier for your application
Client Secret Secret key used to authenticate your requests

⚠️ Security note: Never hardcode your Client Secret in source code or commit it to GitHub. Use environment variables in production:

export SCALEKIT_CLIENT_SECRET="your_secret_here"

API Credentials — Environment URL, Client ID, and masked Client Secret

Settings → API Credentials page showing Environment URL, Client ID, and masked Client Secret


Step 4: Creating a Gmail Connector

With credentials ready, let's connect Gmail. Navigate to Connections → + Create Connection → Select Gmail.

Configure the connector with these settings:

  • Connection Name: my-gmail (acts as a unique identifier/primary key for this integration)
  • Authentication Type: OAuth
  • OAuth Credentials: Use Scalekit credentials (for development — uses Scalekit's managed OAuth app)
  • Scopes: https://www.googleapis.com/auth/gmail.readonly

💡 Best practice: Always request the minimum access needed. Read-only access (gmail.readonly) is sufficient for most agent use cases like email triage, summarization, or monitoring. Never request write access unless your agent actually needs to send or modify emails.

Gmail connector configured with gmail.readonly scope — least-privilege principle

Configuring the Gmail connector — note the read-only scope following the least-privilege principle


Step 5: Authorizing a Connected Account

Now we'll create a connected account — this is the link between a specific user and the Gmail connector. This is where multi-service user access orchestration comes to life: once a user authorizes here, any agent acting on their behalf can request their credentials programmatically.

  1. Go to Connected Accounts → + Add Account
  2. Set a User ID (e.g., test-user-123) and select the my-gmail connection
  3. Click Create
  4. Generate an authorization link and open it in your browser
  5. Sign in with your Google account and click Allow to grant read-only access

After the OAuth flow completes, the account status changes from "Pending" to "Connected".

💡 Development tip: Google may show an "unverified app" warning during the OAuth flow. This is expected — click "Advanced" → "Go to scalekit.dev (unsafe)" → "Allow". The app will be properly verified for production use.

Connected account test-user-123 — Status: Connected

Connected account successfully authorized — the agent can now access Gmail on behalf of test-user-123


Step 6: Going to Production

Before shipping to production, it's a best practice to set up user verification to ensure only authenticated users can trigger agent actions on their behalf.

🔐 Best practice: Review the AgentKit User Verification guide to understand how to validate user identity before your agent performs any actions in production.

This ensures your agent always acts on behalf of a verified user — not an anonymous or unauthorized request.


What's Next?

With the connected account active, your AI agent now has a proper access orchestration layer. It can:

  • Read user emails via the Gmail connector with scoped, auditable access
  • Check authorization status programmatically before each operation
  • Let Scalekit handle token refresh, expiry, and scope validation automatically

Beyond Gmail, AgentKit supports 40+ connectors including Slack, GitHub, Google Calendar, Google Drive, and more. The same pattern connect once, delegate safely, audit everything applies across all of them.

Check out the AgentKit documentation to explore the full connector catalog and advanced use cases like multi-user delegation and access policies.


Conclusion

Traditional authorization wasn't built for AI agents. When your agent needs to act on behalf of multiple users across multiple services, legacy access controls become a liability not a safeguard.

Scalekit AgentKit provides a purpose-built access orchestration solution with:

  • Just-in-time access requests — agents get access only when needed
  • Automatic token management — no manual refresh logic
  • Complete audit trails — every access request is logged
  • 15-minute implementation — as proven in this tutorial

Imagine a user authenticates once. The AI agent then fetches the last 5 unread emails from a teammate, drafts a summary, and posts it to a Slack channel all without re-prompting for credentials. That's the power of Scalekit's delegated auth.

The 3 AM access crashes? Gone.


This article is sponsored by Scalekit. All code, opinions, and 3 AM debugging stories are my own.

Top comments (2)

Collapse
 
urmila_sharma_78a50338efb profile image
urmila sharma

This is the problem that doesn't get enough attention Everyone talks about building smart agents. Nobody talks about how to let them safely touch user data.

The act on behalf of pattern is where most agent demos stop working in production. OAuth flows, token exchange, fine-grained permissions none of that is magic. It's just hard.

Curious about your approach: are you using OAuth 2.0 token exchange, or something custom? And how do you handle the delegation vs impersonation distinction does the agent act as the user, or as itself with user permissions?

Thanks for writing about this. The security side of AI agents is under-discussed and over important. 🙌

Collapse
 
harsh2644 profile image
Harsh Scalekit Inc

Urmia you've asked exactly the questions that the article should have answered.

The 'act on behalf of' pattern is where most agent demos stop working in production.

Yes. The demo works. The pilot works. Then you try to connect it to real user data, and suddenly you're in OAuth redirect hell, token refresh purgatory, and permission boundary confusion.

OAuth flows, token exchange, fine-grained permissions none of that is magic. It's just hard.

This is the sentence that needs to be on a plaque in every AI security meeting. The hard parts aren't interesting. That's why everyone skips them. That's also why most agents never ship.

Delegation vs impersonation does the agent act as the user, or as itself with user permissions?

This is the question. Impersonation is powerful and terrifying. Delegation is cleaner but requires infrastructure most teams don't have. The answer shapes your entire auth architecture.

Thank you for bringing the hard questions. The security side of AI agents isn't glamorous. It's also what separates demos from production. 🙌