How to authenticate AI agents in Go: delegated, scoped, key-bound tokens
An agent holding your API key can do everything you can, from anywhere, for as long as the key lives. Here is how to give it less, in Go.
On this page
- Why a shared API key fails for agents
- 1. Delegate: a token that names the person and the agent
- 2. Scope: check every route against the token
- 3. Keep it short: one token per task
- 4. Bind the token to the agent’s key with DPoP
- 5. Ask a person before risky actions
- 6. Revoke and log who did what
- AI agent authentication best practices at a glance
- FAQ
- Key takeaways
Why a shared API key fails for agents
The quickest way to let a coding agent call your API is to paste your personal API key into its configuration. It works, and it fails in four ways at once:
- Your log can’t tell the agent from you. Every request looks like yours, so “who deleted this?” has no answer.
- The agent can do everything you can. A key with your full rights turns one prompt injection into anything your account allows.
- You can’t stop one agent. Revoking the key stops every tool that shares it, including you.
- A copy works anywhere. A bearer key leaked in a log or a repository works on any computer until someone notices.
OWASP lists this pattern as Excessive Agency, the sixth risk of its 2025 Top 10 for LLM applications. Its mitigations are the ones this post builds: give extensions the minimum permissions, run actions “in the context of that specific user”, require a person to approve high-impact actions, and enforce authorization in the downstream system instead of trusting the model to decide (OWASP).
This post walks through six practices for authenticating AI agents in a Go server, each with code that compiles against tensile-auth:
- Delegate: give each agent its own token, issued by a person.
- Scope: check each route against what the token holds.
- Keep it short: let the token live for one task.
- Bind it to a key: make a copied token useless.
- Ask a person: put a human approval in front of risky actions.
- Revoke and log: stop one agent at once, and record who did what.
If you want the concepts first, read what an AI agent identity is.
1. Delegate: a token that names the person and the agent
OAuth’s token exchange specification draws the line this post depends on. With impersonation, the actor gets all of the subject’s rights and becomes indistinguishable from them. With delegation, the actor “still has its own identity” and acts as an agent for the subject (RFC 8693, section 1.1). A shared key is impersonation. You want delegation: every request says both who is responsible and which agent made it.
In tensile-auth, a person registers an agent once with svc.CreateAgent, which sets the agent’s ceiling: the most scopes any of its sessions can ever hold. Then svc.Delegate issues a session for one task. Both calls refuse scopes the person doesn’t hold with auth.ErrScopeExceeded, and an agent can’t create an agent.
This handler runs when the person, signed in to your app, approves a token for their agent. The agent sends its public key’s thumbprint, which section 4 explains:
type agentRequest struct {
Name string `json:"name"`
Scopes []string `json:"scopes"`
Thumbprint string `json:"jkt"` // from dpop.Thumbprint on the agent's machine
}
func createAgentToken(svc *auth.Service) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
person, _ := auth.FromContext(r.Context())
var req agentRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
// The agent's ceiling: never more than the person holds.
agent, err := svc.CreateAgent(r.Context(), person, auth.AgentSpec{
Name: req.Name, Scopes: req.Scopes,
})
if err != nil {
authhttp.Error(w, r, err)
return
}
// The token for one task: narrower, shorter, and bound to a key.
tok, _, err := svc.Delegate(r.Context(), person, auth.DelegateSpec{
Agent: agent.ID,
Name: req.Name + ", issue triage",
Scopes: req.Scopes,
TTL: time.Hour,
KeyThumbprint: req.Thumbprint,
})
if err != nil {
authhttp.Error(w, r, err)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{
"agent": string(agent.ID),
"token": tok.Reveal(), // shown once; the store keeps only a hash
})
}
}
Every request the agent makes then authenticates as an auth.Principal with User set to the person, Agent set to the agent, Depth 1, and Parent set to the browser session that issued it. User is never empty for a claimed agent, however deep the chain goes, so you always know whom to ask.
2. Scope: check every route against the token
A delegated token is only as narrow as the checks your routes make. The OAuth security best current practice says the privileges of an access token “SHOULD be restricted to the minimum required” for the use case, down to certain resources and actions (RFC 9700, section 2.3).
In tensile-auth, each route declares an auth.Need, and authhttp.Mux enforces it before your handler runs. These are the example server’s routes. Section 4 covers WithDPoP, and section 5 covers the delete route:
var deleteNeed = auth.Need{
Action: "repo.delete",
Assurance: auth.AssuranceMulti,
Within: 10 * time.Minute,
Human: true,
}
func newMux(svc *auth.Service, origin string) (*authhttp.Mux, error) {
verifier, err := dpop.New(dpop.WithOrigin(origin))
if err != nil {
return nil, err
}
mux := authhttp.NewMux(svc,
authhttp.WithClientIP(),
authhttp.WithOrigins(origin),
authhttp.WithDPoP(verifier),
authhttp.WithApprovalURL("/approve/"),
)
// A person, signed in with a passkey in the last 10 minutes, hands out agent tokens.
mux.HandleFunc("POST /agents", authhttp.Need(auth.Need{
Assurance: auth.AssuranceMulti, Within: 10 * time.Minute, Human: true,
}), createAgentToken(svc))
// Agents and people both pass, if they hold the scope.
mux.HandleFunc("GET /repos/{id}/issues", authhttp.Need(auth.Need{
Scopes: []string{"issues:read"},
}), listIssues)
mux.HandleFunc("POST /repos/{id}/issues/{n}/labels", authhttp.Need(auth.Need{
Scopes: []string{"issues:write"},
}), labelIssue)
// Only a person can delete. An agent gets an approval its person can grant.
mux.Handle("DELETE /repos/{id}", authhttp.Public, authhttp.Approvable(deleteNeed,
func(r *http.Request) auth.Action {
id := r.PathValue("id")
return auth.Action{Kind: "repo.delete", Resource: id, Summary: "Delete the repository " + id}
})(http.HandlerFunc(deleteRepo)))
return mux, mux.Check()
}
Three details matter here:
- Scopes narrow at every step. A session’s scopes must be held by its parent and by the agent’s ceiling. A token for
issues:readandissues:writecan’t call a route that needsrepo:admin, and it gets a403with the codescope_missingand the missing scope in the challenge. - The
POST /agentsroute refuses agents.Human: truemeans an agent can’t mint tokens for itself, andWithinmeans the person confirmed it’s them in the last 10 minutes. mux.Checkrefuses to start a server with a gap. A route registered with an empty rule, neitherauthhttp.Neednorauthhttp.Public, is an error, so a forgotten check fails at startup instead of in production.
The decision runs in your server, from the token’s recorded scopes. The model never decides whether it’s allowed, which is the “complete mediation” that OWASP asks for.
3. Keep it short: one token per task
A token that lives for an hour can leak for an hour. A token that lives for a year can leak for a year. tensile-auth’s default auth.Policy ends an agent session after 15 minutes without use and 8 hours after it starts, and a delegated session never outlives the session it came from. A request for longer fails: in the example, TTL: 9 * time.Hour returns auth.ErrExpiryExceeded.
Short lifetimes work because issuing a token is one call. Delegate per task, label the session with DelegateSpec.Name so the person can recognize it, and let it expire.
Revocation doesn’t wait for expiry. svc.Authenticate reads the store on every request, so a revoked token fails on its next use. When the person signs out, authhttp.SignOut revokes their browser session and every agent session delegated from it.
4. Bind the token to the agent’s key with DPoP
Scopes and lifetimes limit what a stolen token can do. Binding it to a key stops a stolen copy from working at all. RFC 9700 says authorization and resource servers “SHOULD use mechanisms for sender-constraining access tokens”, and names DPoP as one (RFC 9700, section 2.2.1).
DPoP, Demonstrating Proof of Possession, is RFC 9449. The client keeps a private key. With each request, it sends the token and a short JWT signed by that key, the proof, in the DPoP header. The proof carries the HTTP method (htm), the URL without its query (htu), the time it was made (iat), a unique ID (jti), and the SHA-256 hash of the access token (ath). The token records the key’s thumbprint as its jkt confirmation, so the server can check that the signer is the key the token was issued to (RFC 9449, section 4.2).
On the agent’s machine, make the key once and send only its thumbprint to the server:
// On the agent's machine: make a key once, keep the private half,
// and give the server only its thumbprint.
func newAgentKey() (*ecdsa.PrivateKey, string, error) {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, "", err
}
jkt, err := dpop.Thumbprint(&key.PublicKey)
return key, jkt, err
}
Then sign a fresh proof for every request:
// Every request carries the token and a fresh proof signed by the key.
func call(key *ecdsa.PrivateKey, token, method, url string) (*http.Response, error) {
proof, err := dpop.Sign(key, method, url, token, time.Now())
if err != nil {
return nil, err
}
req, err := http.NewRequest(method, url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "DPoP "+token)
req.Header.Set("DPoP", proof)
return http.DefaultClient.Do(req)
}
On the server, authhttp.WithDPoP checks the proof, and auth.RequireAgentKeys makes the binding mandatory: svc.Delegate without a KeyThumbprint fails with auth.ErrKeyRequired.
func newService() (*auth.Service, error) {
limiter, err := ratelimit.New(ratelimit.NewMemory(), ratelimit.DefaultRules())
if err != nil {
return nil, err
}
return auth.New(memstore.New(),
auth.WithLimiter(limiter),
auth.RequireAgentKeys(), // refuse agent tokens that aren't bound to a key
)
}
To see what binding buys you, try each way an attacker could use the agent’s token. Every result is from running this post’s example server:
- Request
- GET /repos/acme/issues
- Authorization
- DPoP tsa_…
- DPoP proof
- signed by the agent's key, for GET /repos/acme/issues
200The proof's key matches the token's thumbprint, its ath matches the token, and its ID is fresh.
Audit logNothing. The request runs as alice's agent.
- Request
- GET /repos/acme/issues
- Authorization
- Bearer tsa_…
- DPoP proof
- none
401A token bound to a key never works without a proof.
Audit logtoken_rejected, reason key_required
- Request
- GET /repos/acme/issues
- Authorization
- DPoP tsa_…
- DPoP proof
- signed by another key
401The proof is valid, but its key isn't the one the token is bound to.
Audit logtoken_rejected, reason key_mismatch
- Request
- GET /repos/acme/issues
- Authorization
- DPoP tsa_…
- DPoP proof
- copied from a request the agent already made
401The first use worked. The second has the same proof ID, which the replay cache already spent.
Audit logtoken_rejected, reason proof_replayed
- Request
- GET /repos/acme/issues
- Authorization
- DPoP tsa_…
- DPoP proof
- signed by the agent's key, for GET /repos/other/issues
401The proof's htu names a different URL, so it can't be moved to this request.
Audit logtoken_rejected, reason proof_url
- Request
- GET /repos/acme/issues
- Authorization
- DPoP tsa_…
- DPoP proof
- signed by the agent's key, for GET /repos/acme/issues
401alice stopped the agent. Every request reads the store, so the next one fails.
Audit logtoken_rejected, reason revoked
Know the limits before you rely on it:
- The key must stay on the agent’s machine. RFC 9700 notes that binding helps less when an attacker gets the key too, for example from compromised client software (section 4.10.1). Malware running as the agent can sign proofs.
- No server nonces. tensile-auth’s
dpoppackage doesn’t support the optional server-provided nonce of RFC 9449, section 8. The 60-secondiatwindow and the replay cache limit how long a captured proof works. - Share the replay cache across servers. The default
dpop.Memorycache lives in one process. With several servers, passdpop.WithReplays(pgstore.NewProofReplays(db))so a proof spent on one server is spent on all of them. - Two algorithms. Proofs must use
ES256(P-256) orEdDSA(Ed25519).
If an agent can’t keep a private key, for example a hosted tool that only accepts a bearer token, leave RequireAgentKeys off for it, and make up for it with narrower scopes and a shorter TTL.
5. Ask a person before risky actions
Some actions shouldn’t depend on any token: deleting a repository, sending money, changing who has access. For these, the person must confirm, and the confirmation must cover the exact action.
In the routes above, deleteNeed says Human: true, so no agent passes it on its own. authhttp.Approvable turns that refusal into a request its person can grant. The agent’s DELETE /repos/acme gets this answer, trimmed:
{"status": 403, "code": "human_required", "title": "A person must do this",
"challenge": {"action": "repo.delete", "assurance": "multi", "within_seconds": 600, "human": true,
"approval": {"id": "apr_xOBxo6oCgMgcr68Jhm-NyA", "url": "/approve/apr_xOBxo6oCgMgcr68Jhm-NyA",
"summary": "Delete the repository acme", "expires_in": 300}}}
The agent shows its person the URL. The person reads “Delete the repository acme” and approves it with a passkey, whose signature covers the action’s digest. The agent retries the same request with the approval’s ID in the Tensile-Approval header, and the route runs once. A second retry gets approval_invalid, and so does a retry for a different repository.
Three rules keep approvals from becoming a bypass:
- An approval covers one action. It is bound to the digest of the action’s kind, resource, parameters, and summary, and to the agent that asked.
- It expires. A request waits 5 minutes for its person, and an approval waits 5 minutes to be used (
auth.ApprovalTTL). - It doesn’t add scopes. If the need lists scopes, the agent must hold them itself. An approval stands in only for what a person adds.
The same need protects people too. A person whose last passkey check is older than 10 minutes gets step_up_required with the factors that would pass, confirms, and retries. For how the passkey signature becomes a receipt that you can check later, read how to prove a human approved an agent action.
6. Revoke and log who did what
When an agent misbehaves, the person needs one button that stops it, and you need a record of what it did.
// "Stop this agent": disables it and ends every session it holds.
func stopAgent(ctx context.Context, svc *auth.Service, person auth.Principal, id auth.AgentID) error {
return svc.RevokeOwnAgent(ctx, person, id)
}
// What did this agent do with its credentials?
func agentHistory(ctx context.Context, svc *auth.Service, person auth.Principal, id auth.AgentID) ([]auth.Event, error) {
return svc.Events(ctx, auth.EventFilter{User: person.User, Agent: id, Descending: true, Limit: 50})
}
RevokeOwnAgent disables the agent, so no session can be delegated to it again, and revokes all its sessions in one transaction. Revoking any session with svc.Revoke also revokes every session delegated from it. For a “Where you’re signed in” page, svc.SessionTree lists each device with the agents under it.
The library records its own events, and writes each change’s event in the same transaction as the change. In the example run, the agent’s history read, oldest first: agent_created, session_delegated, four token_rejected events for the attacks in section 4, access_denied with the reason not_human for the delete, approval_requested, approval_granted with the person as the actor, approval_redeemed, agent_revoked, and one more token_rejected with the reason revoked. svc.SealAudit chains the events by hash, and svc.VerifyAudit reports any event that changed afterward. The security page covers the chain and its signed checkpoints.
The library logs authentication, not your app’s actions. Log those yourself, with both identities from the principal:
func labelIssueLogged(w http.ResponseWriter, r *http.Request) {
p, _ := auth.FromContext(r.Context())
// ... label the issue ...
slog.InfoContext(r.Context(), "issue labelled",
"repo", r.PathValue("id"), "issue", r.PathValue("n"),
"user", p.User, // the person responsible
"agent", p.Agent, // empty when the person did it
"session", p.Session, // this task's token
"parent", p.Parent, // the session it was delegated from
)
w.WriteHeader(http.StatusNoContent)
}
AI agent authentication best practices at a glance
| Practice | What it stops | In tensile-auth |
|---|---|---|
| Delegate per agent | Agent actions logged as the person’s | svc.CreateAgent, svc.Delegate |
| Scope every route | An agent doing more than its task | auth.Need{Scopes}, authhttp.Mux |
| Short lifetimes | A leaked token working for months | 15 minutes idle, 8 hours at most by default |
| Bind to a key | A copied token working anywhere | DPoP with authhttp.WithDPoP, auth.RequireAgentKeys |
| Ask a person | A prompt injection deleting data | authhttp.Approvable, Human: true |
| Revoke and log | Not knowing what an agent did, or not stopping it | svc.RevokeOwnAgent, svc.Events, the hash chain |
FAQ
Should agents use OAuth instead?
When a third-party agent connects to your API through a consent screen, yes. tensile-auth’s oauth package serves the device authorization grant and token exchange (RFC 8693), and an exchanged token is an agent session like the ones in this post. When the person and the agent both use your own app, svc.Delegate is the shorter path.
Can an agent create another agent?
No. svc.CreateAgent refuses agent sessions. An agent can delegate a narrower session to itself for a subtask, up to a depth of 4 by default, and every level still names the same person.
Does an approval let an agent skip its scopes?
No. The agent must meet every part of the need that isn’t about a person, such as its scopes, before it can ask.
What about MCP servers?
The MCP authorization specification of 25 November 2025 forbids token passthrough: a server must accept only tokens issued for it and must not forward them to other APIs (MCP). Each hop gets its own token, which is the same rule as delegation.
What if the agent’s machine is compromised?
Then it can use its token until you revoke it, as the person can on their own device. Short lifetimes, narrow scopes, and approvals limit what it can do in that time.
Key takeaways
- Never give an agent your own key. Issue it a delegated token that names you and the agent.
- Check every route against the token’s scopes in your server, and refuse to start with a route that has no rule.
- Issue one token per task, measured in hours, and revoke the whole tree with one call.
- Bind agent tokens to a key with DPoP, so a copied token fails without the key.
- Put a person in front of irreversible actions, with an approval for one exact action that works once.
- Log the person and the agent on every action, and keep the audit trail where tampering shows.
Try it
Give your coding agent this line to add tensile-auth to your Go app, then give each agent a delegated token with Delegate:
Add sign-in with tensile-auth. Read https://auth.tensile.tools/llms.txt and follow it.