Agent Identity, Authorization and Secrets
Every action should answer two questions: which agent did this, and on whose behalf?
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.
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.
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
| Word | Question | Example |
|---|---|---|
| Identity | Who or what is this? | The support agent, production instance |
| Authentication | Can it prove that? | A signed token or certificate |
| Authorization | May it do this, here, now? | Read this customer's order |
| Accounting | What happened? | A log naming user, agent, action and decision |
The identities in one request
| Pattern | The agent acts with | Good for | Watch |
|---|---|---|---|
| Shared service account | One broad account for everything | Avoid | No attribution; confused deputy |
| Agent's own identity | Narrow rights of the agent itself | Background jobs with no user | Keep the scope small |
| Delegated by a user | Overlap of user and agent rights | Interactive assistance | Expiry, consent, revocation |
| Passing the user's token on | All of the user's rights | Avoid | Any 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.
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.
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:readwas 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.
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.
Consent people can understand
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 request | Better request |
|---|---|
| "Allow access to your account" | "Read your calendar for the next two weeks to suggest times" |
| One approval for every right at first use | Ask for reading now; ask to send only when sending |
| Access that never ends | Ends with the task or on a stated date |
| No record of connected agents | A 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
| Layer | Narrow it to |
|---|---|
| Tool list | Only tools this agent's task needs |
| Operation | Read, create or change, listed separately |
| Resource | This tenant, this user, this record |
| Value | Amount, count and rate ceilings |
| Time | Minutes, ending with the task |
| Place | Only from this workload and network |
Roles, attributes and capabilities
| Model | Decision based on | Fits agents when |
|---|---|---|
| Role-based | Roles such as support or finance | Duties are stable; keep roles small |
| Attribute-based | User, resource, time, risk and context | Limits depend on values and situation |
| Relationship-based | Links such as "owner of this document" | Sharing decides access |
| Capability-based | An unforgeable grant for one operation on one object | A 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.
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
- In February 2026 NIST's cybersecurity center published a concept paper on software and AI agent identity and authorization, followed by a project. A September 2026 summary of comments names DevSecOps as the first use case.
- An IETF working group draft on agent identity management builds on existing standards. As of September 2026 it was an informational draft, so expect change.
Neither is a finished rulebook. Build on established identity standards now and keep the agent-specific parts easy to replace.
Secrets
| Never put secrets in | Do this instead |
|---|---|
| Prompts and system instructions | Let the tool service attach credentials |
| Source code and container images | Load from a secret manager at run time |
| Tool results returned to the model | Strip headers, connection strings and keys |
| Logs, traces and error messages | Redact at the source and scan for leaks |
| A sandbox that runs generated code | Broker the call from outside the sandbox |
| Chat history and memory | Detect 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
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
| Event | What must happen |
|---|---|
| New agent | Owner, purpose, rights and expiry recorded before issue |
| User leaves or changes role | Delegations end, including queued and long-running tasks |
| Suspected compromise | Disable the identity, revoke tokens, rotate secrets it could read |
| Agent retired | Remove accounts, keys, schedules and webhooks |
| Periodic review | Compare 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.
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
- Log which operations and records the shared account actually touches, and by which caller.
- Create one identity per agent and environment with only the observed, justified rights.
- Run the new rules in report-only mode and review what would have been refused.
- Switch one agent at a time, with a quick way back.
- Add user delegation for interactive paths.
- Disable the shared account, watch for failures, then remove it.
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
| Secret | Preferred lifetime handling | On suspected leak |
|---|---|---|
| Access token | Expires quickly; not stored | Revoke the delegation and issuing session |
| Refresh token | Stored encrypted, rotated on use where supported | Revoke and require sign-in again |
| Signing key | Held in a key service; overlapping rotation | Retire the key and reject its signatures |
| Provider API key | Per environment, with spend limits | Create a replacement, switch, delete the old one |
| Database password | Short-lived and issued per workload if possible | Rotate, 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
| Mistake | Better practice |
|---|---|
| One key shared by many agents | One identity per agent and environment |
| Trusting a user name written in a message | Take identity from a verified token |
| Forwarding the user's token | Exchange it for a narrower one |
| Checking scope but not the record | Check both in the service |
| Standing administrator rights "to be safe" | Time-limited elevation with approval |
| Never testing revocation | Rehearse 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
- RFC 8693: OAuth 2.0 Token Exchange
- RFC 8725: JSON Web Token Best Current Practices
- NIST concept paper on agent identity and authorization
- IETF draft: Agent Identity Management System
- OWASP authorization cheat sheet
- SPIFFE workload identity
Next steps
Network, Tenant and Multi-Agent Isolation
Limit where identities can be used.
Human Approval, Thresholds and Secure Logging
Put people on consequential steps.
Action Guardrails and Policy Engines
Decide each action by policy.