Authentication for ADK Agent Endpoints #3549
Replies: 1 comment 1 reply
-
|
Response from ADK Answering Agent (experimental, answer may be inaccurate) TLDR: The Hello! You can add authentication to your ADK agent's endpoints by leveraging FastAPI's standard authentication mechanisms. The The most common way to handle this in FastAPI is to use a dependency injection. Here is a simplified example of how you can protect your endpoints: from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import APIKeyHeader
from google.adk.cli.fast_api import get_fast_api_app
# Define your API key name and the expected value
API_KEY_NAME = "X-API-Key"
API_KEY = "your_secret_api_key" # Replace with your actual key
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
async def get_api_key(api_key: str = Depends(api_key_header)):
if not api_key or api_key != API_KEY:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Could not validate credentials",
)
return api_key
# Get the base ADK FastAPI app
app: FastAPI = get_fast_api_app(agents_dir="./agents")
# Now, you can add your protected endpoints like this:
@app.get("/my-protected-endpoint", dependencies=[Depends(get_api_key)])
async def protected_route():
return {"message": "You have access!"}
# Note: This example shows how to protect a new, custom endpoint.
# To protect the built-in ADK endpoints, you would need to add the
# dependency to the router itself, like so:
#
# from fastapi import APIRouter
#
# protected_router = APIRouter(dependencies=[Depends(get_api_key)])
# # Then include the ADK router into this protected_router
# # This is a more advanced use case and might require a deeper
# # understanding of how the ADK router is constructed.
#
# A simpler approach for protecting all endpoints is to use Middleware:
#
# from starlette.middleware.base import BaseHTTPMiddleware
#
# class AuthMiddleware(BaseHTTPMiddleware):
# async def dispatch(self, request, call_next):
# api_key = request.headers.get(API_KEY_NAME)
# if request.url.path not in ["/docs", "/openapi.json"]: # Exclude docs
# if not api_key or api_key != API_KEY:
# return JSONResponse(
# status_code=status.HTTP_403_FORBIDDEN,
# content={"detail": "Not authenticated"},
# )
# response = await call_next(request)
# return response
#
# app.add_middleware(AuthMiddleware)This approach allows you to implement your own authentication logic without modifying the core ADK source code. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I’m using get_fast_api_app to serve an agent, and I want to authenticate access to the agent endpoints (like /app/:app_name/user/:user_id/session/:session_id, /run, /run_sse).
What is the recommended way to enforce authentication or validate tokens for these ADK-managed endpoints without overriding the internal ADK logic?
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions