Agent Identity, Authorization and Secrets

Every action should answer two questions: which agent did this, and on whose behalf?

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

Give each agent and workload its own identity. When it acts for a person, pass delegated rights that are narrow and short-lived, and have every service check them. Keep secrets out of prompts, code, logs and the model's reach, and make revocation fast and tested.

What you will learn: the identities involved in an agent action, authentication and authorization, token delegation, capability-based access, secret handling and revocation.
Prerequisites: Tool Permissions, Approvals and Abuse Risks. Basic familiarity with tokens and web APIs helps.

Versions used

The example runs in November 2026 with Python 3.13, PyJWT 2.15.0 and cryptography 50.0.1. It is a teaching simulation in one process, not an authorization server and not a full implementation of the token exchange standard. Use your identity provider in real systems.

Beginner Who is who

Why agents need their own identity

Imagine a record is changed overnight. If every program uses the same account, the log says only that "the service account" did it. You cannot tell which agent acted, who asked, or how to stop that one agent without stopping everything else. A separate identity answers all three.

An agent differs from a typical program in one important way: it chooses its next step while running, partly from text it reads. Its identity should therefore carry only the rights that remain acceptable even if that choice is wrong.

Four words to keep apart

WordQuestionExample
IdentityWho or what is this?The support agent, production instance
AuthenticationCan it prove that?A signed token or certificate
AuthorizationMay it do this, here, now?Read this customer's order
AccountingWhat happened?A log naming user, agent, action and decision

The identities in one request

Userasks for something
Agenta named application
Workloadthe running process
Tool servicedecides and records
PatternThe agent acts withGood forWatch
Shared service accountOne broad account for everythingAvoidNo attribution; confused deputy
Agent's own identityNarrow rights of the agent itselfBackground jobs with no userKeep the scope small
Delegated by a userOverlap of user and agent rightsInteractive assistanceExpiry, consent, revocation
Passing the user's token onAll of the user's rightsAvoidAny tool receives far more than needed

The Model Context Protocol authorization rules also forbid passing a received token through to another service; see MCP Authentication and Security.

Intermediate Delegation that stays narrow

Exchange, do not forward

In OAuth token exchange, a service presents one token to an authorization server and receives another suited to the next step. Done well, the new token names one audience (the service it is for), a small scope (the operations), the subject (the user), the actor (the agent) and a short expiry.

1. User signs intoken for the agent gateway
2. Agent requests exchangeauthenticates itself, names the target and rights wanted
3. Server grants the overlapuser rights, agent rights and request
4. Tool verifiessignature, issuer, audience, expiry, scope, actor

Run the checks

Ana may read orders and edit her profile. The agent may read orders and create refunds. The exchange asks for everything. Install with pip install "PyJWT[crypto]", save as delegation.py and run it.

"""Delegated, narrow, short-lived tokens. The agent never holds the tool's secret."""
import time

import jwt                                              # pip install "PyJWT[crypto]"
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey

ISSUER = "https://auth.lab.invalid"
ISSUER_KEY = Ed25519PrivateKey.generate()               # held by the authorization server
PUBLIC_KEY = ISSUER_KEY.public_key()                    # all that services need
AGENT_MAY = {"support-agent": {"orders:read", "refunds:create"}}
USER_MAY = {"ana": {"orders:read", "profile:write"}}


def issue(sub, audience, scopes, ttl=300, key=ISSUER_KEY, **extra):
    now = int(time.time())
    claims = {"iss": ISSUER, "sub": sub, "aud": audience, "iat": now, "exp": now + ttl,
              "scope": " ".join(sorted(scopes)), **extra}
    return jwt.encode(claims, key, algorithm="EdDSA")


def read(token, audience):
    return jwt.decode(token, PUBLIC_KEY, algorithms=["EdDSA"], audience=audience,
                      issuer=ISSUER, options={"require": ["exp", "sub", "aud", "iss"]})


def exchange(user_token, agent, audience, wanted):
    """Authorization server: grant only what user AND agent may do AND was asked for.
    A real server also authenticates the agent before it believes the agent's name."""
    user = read(user_token, "agent-gateway")
    granted = set(wanted) & USER_MAY[user["sub"]] & AGENT_MAY[agent]
    return issue(user["sub"], audience, granted, act={"sub": agent})


SECRET = {"orders-api": "sk-lab-not-a-real-key"}        # lives in the tool service only
LOG = []


def orders_tool(token, scope="orders:read"):
    try:
        claims = read(token, "orders-api")
    except jwt.InvalidTokenError as error:
        return f"rejected: {type(error).__name__}"
    if scope not in claims["scope"].split() or "act" not in claims:
        return f"rejected: needs delegated {scope}"
    LOG.append(f"user={claims['sub']} agent={claims['act']['sub']} scope={scope}")
    # call_backend(SECRET["orders-api"]) would happen here; the key is never returned
    return "ok: order A-1 is shipped"


if __name__ == "__main__":
    user_token = issue("ana", "agent-gateway", USER_MAY["ana"])
    good = exchange(user_token, "support-agent", "orders-api",
                    ["orders:read", "refunds:create", "profile:write"])
    print("granted scope:", read(good, "orders-api")["scope"])
    other = exchange(user_token, "support-agent", "billing-api", ["orders:read"])
    cases = [
        ("delegated token", good, "orders:read"),
        ("refund Ana cannot make", good, "refunds:create"),
        ("user token passed straight on", user_token, "orders:read"),
        ("token for another service", other, "orders:read"),
        ("expired", issue("ana", "orders-api", {"orders:read"}, ttl=-60,
                          act={"sub": "support-agent"}), "orders:read"),
        ("signed by the agent itself",
         issue("ana", "orders-api", {"orders:read"}, key=Ed25519PrivateKey.generate(),
               act={"sub": "support-agent"}), "orders:read"),
    ]
    for name, token, scope in cases:
        print(f"{name:<31}{orders_tool(token, scope)}")
    print("log:", LOG)
    print("secret appears in log:", SECRET["orders-api"] in " ".join(LOG))

Output:

granted scope: orders:read
delegated token                ok: order A-1 is shipped
refund Ana cannot make         rejected: needs delegated refunds:create
user token passed straight on  rejected: InvalidAudienceError
token for another service      rejected: InvalidAudienceError
expired                        rejected: ExpiredSignatureError
signed by the agent itself     rejected: InvalidSignatureError
log: ['user=ana agent=support-agent scope=orders:read']
secret appears in log: False

What to notice

  • Only orders:read was granted: the one right in all three sets.
  • The user's own token was refused by the tool because it was addressed to a different service.
  • A token the agent signed itself failed, because only the issuer holds the signing key.
  • The backend key stays in the tool service. The agent receives results, never the key.
What is simplified

Everything shares one process, the agent's name is taken on trust, keys are generated at start-up and tokens are plain bearer tokens, usable by whoever holds them. Real systems authenticate the agent, rotate published keys, and can bind tokens to a key or certificate so a copied token is useless elsewhere.

Verification checklist for services

  • Fix the accepted algorithms in code; never take them from the token
  • Check signature with the issuer's current key
  • Require and check issuer, audience, subject and expiry
  • Check the scope for this operation, then rights on this specific record
  • Reject anything unclear and log why, without logging the token

The JWT best current practices explain common verification mistakes. Scope alone is rarely enough: orders:read must still be limited to orders this user may see.

A user who delegates should know what they are handing over. Describe rights in everyday words, ask at the moment of need and keep a place to review and withdraw them.

Weak requestBetter request
"Allow access to your account""Read your calendar for the next two weeks to suggest times"
One approval for every right at first useAsk for reading now; ask to send only when sending
Access that never endsEnds with the task or on a stated date
No record of connected agentsA list with last use and a remove button

Consent does not enlarge rights. A user can pass on only what they hold, and an organization may forbid delegating some operations at all.

Chains of agents

When an agent calls another agent, repeat the exchange at each step. The user stays the subject, the current agent becomes the actor and the scope can only shrink. The token exchange standard allows earlier actors to be recorded inside the actor claim for audit; services should make decisions on the verified subject and current actor, not on text describing the chain. Limit chain length, so that a loop between agents cannot continue renewing its own access.

Least privilege in layers

LayerNarrow it to
Tool listOnly tools this agent's task needs
OperationRead, create or change, listed separately
ResourceThis tenant, this user, this record
ValueAmount, count and rate ceilings
TimeMinutes, ending with the task
PlaceOnly from this workload and network

Roles, attributes and capabilities

ModelDecision based onFits agents when
Role-basedRoles such as support or financeDuties are stable; keep roles small
Attribute-basedUser, resource, time, risk and contextLimits depend on values and situation
Relationship-basedLinks such as "owner of this document"Sharing decides access
Capability-basedAn unforgeable grant for one operation on one objectA task should carry only what it needs

A capability handed to a task, for example "attach a file to ticket 42 until 15:00", avoids giving the agent standing access to every ticket.

Expert Workloads, secrets and revocation

Workload identity instead of stored keys

A long-lived key copied into configuration can be stolen and used from anywhere. Workload identity lets the platform prove which process is running and issue short-lived credentials to it. Cloud providers offer this, and SPIFFE is an open specification for it.

It mattered in a July 2026 incident: Hugging Face's published timeline of an intrusion by AI agents lists replacing static credentials with workload identity, scoping credentials per cluster and blocking access to the pod metadata service among its follow-up work.

Standards in motion

Neither is a finished rulebook. Build on established identity standards now and keep the agent-specific parts easy to replace.

Secrets

Never put secrets inDo this instead
Prompts and system instructionsLet the tool service attach credentials
Source code and container imagesLoad from a secret manager at run time
Tool results returned to the modelStrip headers, connection strings and keys
Logs, traces and error messagesRedact at the source and scan for leaks
A sandbox that runs generated codeBroker the call from outside the sandbox
Chat history and memoryDetect and refuse to store them

Assume anything placed in the model's context can be repeated. Environment variables are visible to any code running in the same process, so they do not protect a secret from an agent that executes code there.

The broker pattern

Agentasks for an operation
Brokerchecks policy, adds credential
Target servicereturns a filtered result

The broker must offer narrow operations. A broker that forwards any request with a powerful key attached has simply moved the problem.

Revocation and lifecycle

EventWhat must happen
New agentOwner, purpose, rights and expiry recorded before issue
User leaves or changes roleDelegations end, including queued and long-running tasks
Suspected compromiseDisable the identity, revoke tokens, rotate secrets it could read
Agent retiredRemove accounts, keys, schedules and webhooks
Periodic reviewCompare granted with used; remove the difference

Short expiry limits how long a stolen token works, but a task that runs for days needs fresh authorization along the way. Check rights again at the time of action, not only when the task was created.

Long-running and scheduled work

A task that waits for days should not hold a live token the whole time. Store a reference to the approved delegation, and when the task wakes, ask the authorization server for a fresh short token. That request is where a disabled user, a withdrawn consent or a changed policy takes effect.

Startrecord the delegation
Waitno live token held
Resumere-check user and policy
Actfresh narrow token

See Stateful and Long-Running Agent Architecture.

What to record

{"time": "2026-11-28T14:02:11Z", "user": "u-204", "agent": "support-agent",
 "agent_version": "3.4.0", "task": "t-9912", "operation": "orders.read",
 "resource": "order/A-1", "decision": "allow", "policy": "p-17",
 "token_id": "tk-5521"}

This record is illustrative. It identifies the token without containing it.

Moving off a shared account

  1. Log which operations and records the shared account actually touches, and by which caller.
  2. Create one identity per agent and environment with only the observed, justified rights.
  3. Run the new rules in report-only mode and review what would have been refused.
  4. Switch one agent at a time, with a quick way back.
  5. Add user delegation for interactive paths.
  6. Disable the shared account, watch for failures, then remove it.
Illustrative example

A travel assistant used one key with full access to bookings. After the change, searching uses the agent's own read-only identity, viewing a traveler's trips uses delegation from that traveler, and buying a ticket needs a separate short-lived right issued only after approval. A prompt that asks about someone else's trip now fails in the booking service itself.

Tests to automate

  • A token for one service is refused by every other.
  • Expired, unsigned and wrongly signed tokens are refused.
  • One user cannot reach another user's records by changing an identifier.
  • Revoking a user stops that user's queued tasks.
  • Planted marker secrets never appear in prompts, replies or logs.

Rotation by secret type

SecretPreferred lifetime handlingOn suspected leak
Access tokenExpires quickly; not storedRevoke the delegation and issuing session
Refresh tokenStored encrypted, rotated on use where supportedRevoke and require sign-in again
Signing keyHeld in a key service; overlapping rotationRetire the key and reject its signatures
Provider API keyPer environment, with spend limitsCreate a replacement, switch, delete the old one
Database passwordShort-lived and issued per workload if possibleRotate, end sessions, review access

Rotation that requires a night of manual edits will be postponed. Practice it until it is routine, and scan repositories, logs and build output for secrets so that you learn about leaks early.

Common mistakes

MistakeBetter practice
One key shared by many agentsOne identity per agent and environment
Trusting a user name written in a messageTake identity from a verified token
Forwarding the user's tokenExchange it for a narrower one
Checking scope but not the recordCheck both in the service
Standing administrator rights "to be safe"Time-limited elevation with approval
Never testing revocationRehearse it and time it

Checklist

  • Each agent has an owner and its own identity
  • Delegated access is exchanged, narrow and short-lived
  • Services verify tokens and record-level rights
  • No secret reaches the model, code sandbox or logs
  • Revocation is tested, including long-running tasks

Frequently asked questions

Does every agent need a separate identity?

Give separate identities to anything with different rights, owners or environments, so you can attribute and revoke them independently.

Can the model decide who the user is?

No. Identity must come from authentication, and the model should have no way to change it.

Are API keys acceptable?

Sometimes there is no alternative. Keep them in a secret manager, scope them tightly, rotate them and broker their use.

How short should a token lifetime be?

As short as the work and your renewal process allow. Minutes are common for tool calls; measure before choosing.

References and further reading

Next steps