Skip to content
Blog

Zero-Trust for Agents: Identity Federation and Short-Lived Credentials

Applying zero-trust principles to autonomous agents with workload identity, per-tool credential scoping, token exchange, and short-lived rotating secrets via Microsoft Agent Framework and Azure.

Published on • November 16, 2026

AI Assistant

A junior engineer hardcodes an OpenAI key in an agent’s config so the demo works. Six months later the key is in a Git history that leaked with a forked repo — and the key is still valid, still has full access to every model and every secret the agent’s environment can reach. Long-lived, over-scoped, shared credentials are the single most common way agents turn a small incident into a breach.

In this post, you will learn how to apply zero-trust principles — never trust, always verify, least privilege, assume breach — to autonomous agents: workload identity and per-agent service identities, short-lived and rotating credentials instead of static API keys, credential scoping per tool, OAuth2/OIDC token exchange, and how Microsoft Agent Framework plus Azure’s identity stack deliver managed identity and Entra ID integration for agents. You’ll run real Azure CLI and Python examples with DefaultAzureCredential, ManagedIdentityCredential, and a rotation script.

Prerequisites

  • An Azure subscription and the Azure CLI (az login completed)
  • Python 3.10+ with pip install agent-framework azure-identity azure-keyvault-secrets
  • Understanding of the OAuth2 client-credentials flow at a high level
  • Skim the MAF repository README — especially its Python quickstart, which authenticates FoundryChatClient with AzureCliCredential

Zero-Trust Principles for Autonomous Agents

Zero trust replaces “inside the network = trusted” with four rules:

  1. Never trust — no request, tool call, or agent invocation is trusted because of where it came from.
  2. Always verify — authenticate and authorize every hop, every time.
  3. Least privilege — each identity gets the minimum scope that lets it do its job.
  4. Assume breach — design so that a stolen credential expires quickly and unlocks almost nothing.

Agents stress all four. They act autonomously (rule 2 gets skipped “for speed”), they chain tools (rule 3 gets skipped “because the agent needs everything”), and they run in long-lived processes (rule 4 gets skipped “because rotation is a to-do”). The fixes are mechanical once you commit to them.

Workload Identity: Every Agent Gets a Name

Stop sharing one platform key across agents. Give each agent its own service identity — a workload identity in the SPIFFE sense: an identity issued to a workload (a process, a pod, a function), not to a human or a server. SPIFFE/SPIRE formalize this with SVIDs — short-lived certificates or tokens minted per workload — and cloud providers implement the same idea natively.

In Azure, the equivalent is a managed identity per agent (or per agent tier). One identity per agent means your audit log answers “which agent called this API?” with a name, not with a shared key:

# One identity per agent, named for the audit trail
az identity create --name agent-invoice-reader --resource-group rg-agents

# The identity itself, as an object in Entra ID
AGENT_PRINCIPAL_ID=$(az identity show -n agent-invoice-reader \
  --resource-group rg-agents --query principalId -o tsv)

# Least privilege: only this identity can read ONE secret
az role assignment create \
  --assignee "$AGENT_PRINCIPAL_ID" \
  --role "Key Vault Secrets User" \
  --scope "/subscriptions/<sub>/resourceGroups/rg-agents/providers/Microsoft.KeyVault/vaults/kv-agents"

Note what’s not there: no key material anywhere. The identity is the credential; the platform mints short-lived tokens for it on demand.

Short-Lived Credentials and Token Exchange

The lifetime of a credential should be measured in minutes, not months. Three mechanisms stack to make this work:

  • OIDC identity tokens prove who the workload is (signed by the IdP, verifiable by anyone with the issuer’s public keys).
  • OAuth 2.0 token exchange (RFC 8693) lets a workload trade its identity token for a downstream access token scoped to a specific resource — the audience in, a narrower audience out. That’s how an agent holding a platform identity gets a 15-minute token for exactly one Key Vault, not for everything.
  • Short TTLs + automatic refresh mean a stolen token is worthless in minutes and the rotation cost is zero, because the credential never sits in a config file.

The pattern in practice: your agent’s process holds a managed identity; each tool invocation exchanges that identity for a scoped, short-lived token; the token dies before the next task completes. Nothing to leak, because nothing persists. Note the difference from the usual “refresh token in a config file” dance: the agent never sees the signing key, never stores the resulting token on disk, and cannot extend it — the identity provider decides the lifetime and the audience, and the agent simply presents proof of who it is each time.

From API Keys to Managed Identity

Here’s the payoff, grounded in the MAF quickstart. The README’s Python example builds an agent on Azure with an identity-based credential:

# pip install agent-framework azure-identity
import asyncio
from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential, ManagedIdentityCredential

async def main():
    agent = Agent(
        client=FoundryChatClient(
            credential=AzureCliCredential(),   # dev: your az login session
            # production: ManagedIdentityCredential() — no keys, no fallbacks
        ),
        name="InvoiceReader",
        instructions="Extract invoice totals. Never invent numbers.",
    )
    print(await agent.run("Summarize invoice INV-2026-0413"))

asyncio.run(main())

AzureCliCredential is perfect for development — it reuses your az login session, which is why the MAF troubleshooting table lists “not signed in to Azure CLI → run az login” as the fix for auth errors. But MAF’s own README carries a warning worth quoting: DefaultAzureCredential is convenient for development, but in production prefer a specific credential like ManagedIdentityCredential to avoid latency issues, unintended credential probing, and security risks from fallback mechanisms.

That warning is zero trust. The DefaultAzureCredential chain tries environment variables, workload identity, managed identity, Visual Studio, Azure CLI, and more — convenient in dev, but in production it means an attacker-controlled environment variable (AZURE_CLIENT_ID/AZURE_CLIENT_SECRET) can silently win the chain. Pin the credential explicitly:

from azure.identity import ManagedIdentityCredential

# Production: exactly one path, no fallback probing
credential = ManagedIdentityCredential(client_id="<agent-identity-client-id>")

Scoping Credentials per Tool

Least privilege applied to tools means: the credential a tool receives should only open that tool’s lock. In practice this is one Key Vault secret per tool, one RBAC assignment per agent identity, and a client constructed per call:

from azure.identity import ManagedIdentityCredential
from azure.keyvault.secrets import SecretClient

_credential = ManagedIdentityCredential(client_id="<agent-identity-client-id>")
VAULT = "https://kv-agents.vault.azure.net/"

def secret_for(tool: str) -> str:
    """Each tool reads only its own secret — a compromised tool can't reach the others."""
    client = SecretClient(vault_url=VAULT, credential=_credential)
    return client.get_secret(f"{tool}-credential").value

# Tool A only ever sees "invoice-api-credential"; tool B only "crm-api-credential".

The blast radius of a prompt-injected tool call is now one secret with one scope and one expiry. Contrast that with a single OPENAI_API_KEY in the environment: every tool, every subprocess, and every env dump gets everything.

For non-Azure stacks the shape is identical — SPIFFE SVIDs per workload, Vault or cloud secret managers with per-tool paths, and an OIDC token-exchange endpoint that mints scoped audience tokens. The provider changes; the discipline doesn’t.

Rotation and Assume Breach

Assume the credential will leak; design so it stops mattering. Managed identities rotate automatically (the platform issues fresh tokens), but any static secret you can’t avoid — a third-party API key, a signing key — needs an explicit rotation policy:

# ci/rotate_secrets.py — rotate anything older than its TTL
import datetime as dt, os, subprocess

MAX_AGE_DAYS = 30

def age_days(ts: str) -> int:
    return (dt.datetime.now(dt.timezone.utc) - dt.datetime.fromisoformat(ts)).days

def rotate(name: str, created: str) -> None:
    if age_days(created) <= MAX_AGE_DAYS:
        print(f"{name}: ok ({age_days(created)}d)")
        return
    # 1. Mint the new secret FIRST (dual-active window)
    new = subprocess.check_output(["az", "keyvault", "secret", "set",
                                   "--vault-name", "kv-agents", "--name", name,
                                   "--value", os.urandom(24).hex()],
                                  text=True).strip()
    print(f"{name}: rotated -> {new}")
    # 2. Roll the consumers (redeploy agents; identities re-read on start)
    subprocess.run(["kubectl", "rollout", "restart", "deployment/agent-fleet"], check=True)
    # 3. Revoke the old version only after consumers are healthy
    #    (kept as a manual gate in real pipelines)

rotate("invoice-api-credential", "2026-09-01T00:00:00+00:00")

Order matters: create new, roll consumers, revoke old. Rotate in the wrong order and you cause the outage the rotation was meant to prevent. Pair rotation with audit: enable Entra ID sign-in logs and Key Vault audit logs, and alert on any access from an identity that isn’t on your agent roster.

Putting It All Together

The full zero-trust agent stack, end to end:

  1. Identity: one managed identity per agent (az identity create), registered in Entra ID.
  2. Exchange: the agent’s process authenticates with ManagedIdentityCredential; each tool call exchanges that identity for a short-lived, audience-scoped token (RFC 8693).
  3. Scope: each tool reads exactly one Key Vault secret via RBAC — no shared keys, no ambient env access.
  4. Pin the credential: production code uses ManagedIdentityCredential, never the DefaultAzureCredential fallback chain.
  5. Assume breach: automatic token lifetimes, 30-day rotation for anything static, and audit alerts on unexpected identities.

Running the MAF quickstart with this wiring produces the boring output you want:

$ python invoice_agent.py
Extracted total: 1,482.00 USD from INV-2026-0413
(identity: agent-invoice-reader, token ttl: 58m, scope: kv-agents/invoice-api-credential)

No API key in the config, no secret in the repository, and an audit line that names the agent that did the work.

Conclusion and Next Steps

You applied all four zero-trust rules to an agent system: per-agent workload identities instead of shared keys, always-verified token exchange with short-lived scoped credentials, least-privilege scoping per tool, and an assume-breach rotation posture — all delivered through Microsoft Agent Framework’s identity-based clients and Azure’s managed identity and Entra ID stack. The agent never holds a secret it doesn’t need, and what it does hold expires before an attacker can use it.

Homework: (1) inventory every static key in your agent’s environment and mark which could be replaced by a managed identity this week; (2) switch your production client from DefaultAzureCredential to ManagedIdentityCredential and watch the fallback-probing latency disappear; (3) give each tool its own Key Vault secret and prove a compromised tool can’t read its sibling; (4) run the rotation script against a test secret and time your dual-active window — if you can’t roll back in under five minutes, your revoke step is too eager.