AutoGen Tutorial (Python): adding authentication for advanced developers
This tutorial shows how to add authentication to an AutoGen-based Python agent stack so only approved users can trigger tool calls and model interactions. You need this when your agent is exposed through an API, a web app, or an internal workflow where identity, authorization, and auditability matter.
What You'll Need
- •Python 3.10+
- •
autogen-agentchat - •
autogen-ext[openai] - •
fastapi - •
uvicorn - •
pydantic - •An OpenAI API key
- •A bearer token or JWT issuer you control
- •Basic familiarity with AutoGen agents and tool calling
Step-by-Step
- •Start by installing the packages and setting your model key in the environment. For production, keep secrets out of source control and use a secret manager or deployment environment variables.
pip install autogen-agentchat autogen-ext[openai] fastapi uvicorn pydantic
export OPENAI_API_KEY="your-openai-api-key"
export APP_BEARER_TOKEN="super-secret-token"
- •Build a small authentication layer first. This example uses a bearer token check because it is easy to wire into internal systems, but the same pattern works with JWT validation or mTLS-backed identity.
import os
from fastapi import FastAPI, Header, HTTPException
app = FastAPI()
EXPECTED_TOKEN = os.environ["APP_BEARER_TOKEN"]
def require_auth(authorization: str | None) -> None:
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Missing bearer token")
token = authorization.removeprefix("Bearer ").strip()
if token != EXPECTED_TOKEN:
raise HTTPException(status_code=403, detail="Invalid token")
@app.get("/health")
def health():
return {"status": "ok"}
- •Create the AutoGen agent with a real OpenAI model client. The important part here is that the agent stays behind your auth boundary; do not expose this object directly to untrusted callers.
from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient
model_client = OpenAIChatCompletionClient(
model="gpt-4o-mini",
api_key=os.environ["OPENAI_API_KEY"],
)
agent = AssistantAgent(
name="support_agent",
model_client=model_client,
system_message="You are a concise support assistant for authenticated users.",
)
- •Add a protected endpoint that forwards requests into AutoGen only after auth passes. This keeps identity checks at the edge and lets you attach user context to logs, metrics, and downstream policy checks.
from pydantic import BaseModel
class ChatRequest(BaseModel):
message: str
@app.post("/chat")
async def chat(req: ChatRequest, authorization: str | None = Header(default=None)):
require_auth(authorization)
result = await agent.run(task=req.message)
last_message = result.messages[-1]
content = getattr(last_message, "content", str(last_message))
return {
"authenticated": True,
"response": content,
}
- •If you need per-user authorization instead of just authentication, add claims-based checks before invoking the agent. In practice this is where you enforce role-based access to tools like payments lookup, claims status, or policy updates.
def authorize_user(user_role: str, action: str) -> None:
allowed = {
"viewer": {"read"},
"agent": {"read", "respond"},
"admin": {"read", "respond", "admin"},
}
if action not in allowed.get(user_role, set()):
raise HTTPException(status_code=403, detail="Not authorized for this action")
@app.post("/admin/reload")
def reload_config(authorization: str | None = Header(default=None)):
require_auth(authorization)
authorize_user("admin", "admin")
return {"reloaded": True}
- •Run the service and call it with a valid token. You should get a normal model response when authenticated and an HTTP error when the token is missing or wrong.
uvicorn app:app --reload
Testing It
First hit /health without any headers; it should return 200 OK. Then call /chat without an Authorization header and confirm you get 401 Missing bearer token. Next send Authorization: Bearer super-secret-token and verify the request reaches AutoGen and returns a model-generated response.
For quick manual testing:
curl -X POST http://127.0.0.1:8000/chat \
-H "Content-Type: application/json" \
-H "Authorization: Bearer super-secret-token" \
-d '{"message":"Summarize our authentication flow in one sentence."}'
If you want stronger assurance, add tests for three cases: missing token, invalid token, and valid token. Also log the authenticated subject or client ID before each agent run so you can trace who triggered what in production.
Next Steps
- •Replace the static bearer token with JWT validation using your identity provider’s public keys
- •Add per-tool authorization so some users can chat but not invoke sensitive tools
- •Store auth decisions and agent runs in an audit log for compliance review
Keep learning
- •The complete AI Agents Roadmap — my full 8-step breakdown
- •Free: The AI Agent Starter Kit — PDF checklist + starter code
- •Work with me — I build AI for banks and insurance companies
By Cyprian Aarons, AI Consultant at Topiax.
Want the complete 8-step roadmap?
Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.
Get the Starter Kit