Petru Constantin is the founder of DeviDevs and designed the multi-agent platform the company runs on, with guardrails enforced in code. Code examples are written against the Python 3.15, FastAPI 0.163, Starlette 1.10, PyJWT 2.15 and redis-py 8.1 documentation.
AI API Security: Authentication, Authorization, and Rate Limiting
AI APIs have their own security problems. Every request costs compute, so abuse turns straight into spend and outages (OWASP LLM10:2025 Unbounded Consumption); prompts reach a model that can be manipulated (LLM01:2025 Prompt Injection); and requests and responses often carry sensitive data (LLM02:2025 Sensitive Information Disclosure). This guide covers authentication, authorization, rate limiting and request validation for an AI API.
Authentication Mechanisms
API Key Authentication with Rotation
# api_key_auth.py
import secrets
import hashlib
from datetime import datetime, timedelta, timezone
from typing import Dict, Optional, List
from dataclasses import dataclass
import jwt # PyJWT; RS256 needs the cryptography extra: pip install "pyjwt[crypto]"
@dataclass
class APIKey:
"""API key record."""
key_id: str
key_hash: str
name: str
organization_id: str
created_at: datetime
expires_at: Optional[datetime]
last_used: Optional[datetime]
scopes: List[str]
rate_limit_tier: str
status: str # active, revoked, expired
class APIKeyManager:
"""Manage API keys for AI API access."""
def __init__(self, key_store):
self.store = key_store
self.key_prefix = "sk-"
self.key_length = 48
def generate_key(
self,
name: str,
organization_id: str,
scopes: List[str],
rate_limit_tier: str = "standard",
expires_in_days: Optional[int] = 365
) -> Dict:
"""Generate new API key."""
random_part = secrets.token_urlsafe(self.key_length)
full_key = f"{self.key_prefix}{random_part}"
# Only the hash is stored; a fast hash is fine because the key is high-entropy
key_hash = self._hash_key(full_key)
key_id = f"key_{secrets.token_hex(8)}"
now = datetime.now(timezone.utc)
expires_at = now + timedelta(days=expires_in_days) if expires_in_days else None
api_key = APIKey(
key_id=key_id,
key_hash=key_hash,
name=name,
organization_id=organization_id,
created_at=now,
expires_at=expires_at,
last_used=None,
scopes=scopes,
rate_limit_tier=rate_limit_tier,
status="active"
)
self.store.save_key(api_key)
return {
"key_id": key_id,
"api_key": full_key, # Only returned once!
"expires_at": expires_at.isoformat() if expires_at else None,
"scopes": scopes,
"warning": "Save this key securely. It cannot be retrieved again."
}
def validate_key(self, api_key: str) -> Dict:
"""Validate API key and return associated metadata."""
if not api_key.startswith(self.key_prefix):
return {"valid": False, "error": "Invalid key format"}
key_record = self.store.find_by_hash(self._hash_key(api_key))
if not key_record:
return {"valid": False, "error": "Key not found"}
if key_record.status == "revoked":
return {"valid": False, "error": "Key has been revoked"}
now = datetime.now(timezone.utc)
if key_record.expires_at and now > key_record.expires_at:
return {"valid": False, "error": "Key has expired"}
key_record.last_used = now
self.store.save_key(key_record)
return {
"valid": True,
"key_id": key_record.key_id,
"organization_id": key_record.organization_id,
"scopes": key_record.scopes,
"rate_limit_tier": key_record.rate_limit_tier
}
def rotate_key(self, key_id: str, grace_hours: int = 24) -> Dict:
"""Rotate an active API key; the old one stays valid for a grace period."""
old_key = self.store.find_by_id(key_id)
if not old_key or old_key.status != "active":
raise ValueError("Active key not found")
# Keep the original lifetime for the new key
lifetime_days = (
(old_key.expires_at - old_key.created_at).days if old_key.expires_at else None
)
new_key_result = self.generate_key(
name=old_key.name,
organization_id=old_key.organization_id,
scopes=old_key.scopes,
rate_limit_tier=old_key.rate_limit_tier,
expires_in_days=lifetime_days
)
old_key.expires_at = datetime.now(timezone.utc) + timedelta(hours=grace_hours)
self.store.save_key(old_key)
return {
"new_key": new_key_result,
"old_key_expires": old_key.expires_at.isoformat(),
"message": f"Old key will remain valid for {grace_hours} hours"
}
def revoke_key(self, key_id: str, reason: str) -> bool:
"""Revoke API key immediately (use this, not rotation, for a leaked key)."""
key_record = self.store.find_by_id(key_id)
if not key_record:
return False
key_record.status = "revoked"
self.store.save_key(key_record)
self._log_revocation(key_id, reason)
return True
def _hash_key(self, key: str) -> str:
return hashlib.sha256(key.encode()).hexdigest()
def _log_revocation(self, key_id: str, reason: str):
"""Log key revocation for audit."""
pass
class JWTAuthenticator:
"""RS256 JWTs: sign with the private key, verify with the public key."""
def __init__(
self,
public_key_pem: str,
issuer: str,
audience: str,
private_key_pem: Optional[str] = None # only the token issuer needs it
):
self.public_key_pem = public_key_pem
self.private_key_pem = private_key_pem
self.issuer = issuer
self.audience = audience
self.algorithm = "RS256"
def generate_token(
self,
user_id: str,
organization_id: str,
scopes: List[str],
expires_in: int = 3600
) -> str:
"""Generate JWT access token."""
if not self.private_key_pem:
raise RuntimeError("This instance can only verify tokens")
now = datetime.now(timezone.utc)
payload = {
"sub": user_id,
"org": organization_id,
"scopes": scopes,
"iat": now,
"exp": now + timedelta(seconds=expires_in),
"iss": self.issuer,
"aud": self.audience,
"jti": secrets.token_hex(16)
}
return jwt.encode(payload, self.private_key_pem, algorithm=self.algorithm)
def validate_token(self, token: str) -> Dict:
"""Validate JWT token."""
try:
payload = jwt.decode(
token,
self.public_key_pem,
algorithms=[self.algorithm], # never take the algorithm from the token header
issuer=self.issuer,
audience=self.audience,
options={"require": ["exp", "iat", "iss", "aud", "sub"]}
)
return {
"valid": True,
"user_id": payload["sub"],
"organization_id": payload["org"],
"scopes": payload["scopes"],
"expires_at": datetime.fromtimestamp(payload["exp"], tz=timezone.utc)
}
except jwt.ExpiredSignatureError:
return {"valid": False, "error": "Token expired"}
except jwt.InvalidTokenError as e:
return {"valid": False, "error": str(e)}Authorization Framework
Scope-Based Authorization
# authorization.py
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import List, Dict, Set, Optional
from enum import Enum
import ipaddress
from fastapi import HTTPException, Request
class AIScope(Enum):
"""AI API scopes."""
# Model access
INFERENCE_READ = "inference:read"
INFERENCE_WRITE = "inference:write"
MODELS_LIST = "models:list"
MODELS_DEPLOY = "models:deploy"
# Data access
EMBEDDINGS_CREATE = "embeddings:create"
COMPLETIONS_CREATE = "completions:create"
IMAGES_CREATE = "images:create"
AUDIO_TRANSCRIBE = "audio:transcribe"
# Fine-tuning
FINETUNE_CREATE = "finetune:create"
FINETUNE_READ = "finetune:read"
FINETUNE_DELETE = "finetune:delete"
# Admin
ORGANIZATION_READ = "organization:read"
ORGANIZATION_WRITE = "organization:write"
USAGE_READ = "usage:read"
KEYS_MANAGE = "keys:manage"
@dataclass
class Permission:
"""Permission definition."""
scope: AIScope
resource_type: str
actions: List[str]
conditions: Dict
class AuthorizationManager:
"""Manage authorization for AI API requests."""
def __init__(self, resource_policies: Optional[Dict] = None):
self.scope_hierarchy = self._build_scope_hierarchy()
self.resource_policies = resource_policies or {}
def _build_scope_hierarchy(self) -> Dict[str, Set[str]]:
"""Build scope hierarchy for inheritance."""
return {
"admin": {
AIScope.ORGANIZATION_WRITE.value,
AIScope.ORGANIZATION_READ.value,
AIScope.USAGE_READ.value,
AIScope.KEYS_MANAGE.value,
AIScope.MODELS_DEPLOY.value
},
"developer": {
AIScope.INFERENCE_WRITE.value,
AIScope.INFERENCE_READ.value,
AIScope.MODELS_LIST.value,
AIScope.COMPLETIONS_CREATE.value,
AIScope.EMBEDDINGS_CREATE.value,
AIScope.IMAGES_CREATE.value,
AIScope.AUDIO_TRANSCRIBE.value,
AIScope.FINETUNE_CREATE.value,
AIScope.FINETUNE_READ.value
},
"viewer": {
AIScope.INFERENCE_READ.value,
AIScope.MODELS_LIST.value,
AIScope.USAGE_READ.value,
AIScope.FINETUNE_READ.value
}
}
def check_permission(
self,
user_scopes: List[str],
required_scope: AIScope,
resource: Optional[str] = None,
context: Optional[Dict] = None
) -> Dict:
"""Check if user has required permission."""
context = context or {}
expanded_scopes = set()
for scope in user_scopes:
expanded_scopes.add(scope)
if scope in self.scope_hierarchy:
expanded_scopes.update(self.scope_hierarchy[scope])
if required_scope.value not in expanded_scopes:
return {
"allowed": False,
"reason": f"Missing required scope: {required_scope.value}"
}
if resource and resource in self.resource_policies:
policy_result = self._evaluate_resource_policy(resource, context)
if not policy_result["allowed"]:
return policy_result
return {"allowed": True, "scope": required_scope.value}
def _evaluate_resource_policy(self, resource: str, context: Dict) -> Dict:
"""Evaluate resource-specific policy."""
policy = self.resource_policies.get(resource)
if not policy:
return {"allowed": True}
for condition in policy.get("conditions", []):
if not self._evaluate_condition(condition, context):
return {
"allowed": False,
"reason": f"Condition not met: {condition['description']}"
}
return {"allowed": True}
def _evaluate_condition(self, condition: Dict, context: Dict) -> bool:
"""Evaluate a single policy condition (unknown condition types are denied)."""
condition_type = condition.get("type")
if condition_type == "time_window":
now = datetime.now(timezone.utc).hour
start = condition.get("start_hour", 0)
end = condition.get("end_hour", 24)
return start <= now < end
if condition_type == "ip_range":
client_ip = context.get("client_ip")
if not client_ip:
return False
ip = ipaddress.ip_address(client_ip)
return any(ip in ipaddress.ip_network(r) for r in condition.get("ranges", []))
if condition_type == "model_access":
return context.get("model") in condition.get("models", [])
return False
def require_scope(scope: AIScope, resource: Optional[str] = None,
auth_manager: Optional[AuthorizationManager] = None):
"""FastAPI dependency that enforces a scope on a route.
Usage:
@app.post("/v1/chat", dependencies=[Depends(require_scope(AIScope.COMPLETIONS_CREATE))])
"""
manager = auth_manager or AuthorizationManager()
async def checker(request: Request) -> None:
model = None
if request.method == "POST":
try:
body = await request.json()
model = body.get("model") if isinstance(body, dict) else None
except ValueError:
model = None
result = manager.check_permission(
user_scopes=request.state.user_scopes,
required_scope=scope,
resource=resource,
context={
"client_ip": request.client.host if request.client else None,
"model": model
}
)
if not result["allowed"]:
raise HTTPException(status_code=403, detail=result["reason"])
return checkerRate Limiting
Multi-Tier Rate Limiter
# rate_limiting.py
from dataclasses import dataclass
from typing import Dict, Optional
from datetime import datetime, timedelta, timezone
@dataclass
class RateLimitTier:
"""Rate limit tier configuration (example numbers; size them on your model costs)."""
name: str
requests_per_minute: int
requests_per_day: Optional[int] # None = no daily cap
tokens_per_minute: int
tokens_per_day: Optional[int]
concurrent_requests: int
burst_multiplier: float
class AIRateLimiter:
"""Rate limiter for AI API requests, backed by redis.asyncio."""
TIERS = {
"starter": RateLimitTier(
name="starter",
requests_per_minute=3,
requests_per_day=100,
tokens_per_minute=10000,
tokens_per_day=100000,
concurrent_requests=1,
burst_multiplier=1.0
),
"standard": RateLimitTier(
name="standard",
requests_per_minute=60,
requests_per_day=10000,
tokens_per_minute=60000,
tokens_per_day=1000000,
concurrent_requests=5,
burst_multiplier=1.5
),
"professional": RateLimitTier(
name="professional",
requests_per_minute=300,
requests_per_day=50000,
tokens_per_minute=300000,
tokens_per_day=5000000,
concurrent_requests=20,
burst_multiplier=2.0
),
"enterprise": RateLimitTier(
name="enterprise",
requests_per_minute=1000,
requests_per_day=None,
tokens_per_minute=1000000,
tokens_per_day=None,
concurrent_requests=100,
burst_multiplier=3.0
)
}
def __init__(self, redis_client):
self.redis = redis_client # e.g. redis.asyncio.from_url("redis://...")
def _tier(self, tier_name: str) -> RateLimitTier:
return self.TIERS.get(tier_name, self.TIERS["starter"])
@staticmethod
def _keys(organization_id: str, now: datetime) -> Dict[str, str]:
minute = now.strftime('%Y%m%d%H%M')
day = now.strftime('%Y%m%d')
return {
"minute": f"ratelimit:{organization_id}:minute:{minute}",
"day": f"ratelimit:{organization_id}:day:{day}",
"tokens_minute": f"ratelimit:{organization_id}:tokens:minute:{minute}",
"tokens_day": f"ratelimit:{organization_id}:tokens:day:{day}",
}
async def check_rate_limit(
self,
organization_id: str,
tier_name: str,
estimated_tokens: int = 0
) -> Dict:
"""Check if request is within rate limits (call record_request when it is admitted)."""
tier = self._tier(tier_name)
keys = self._keys(organization_id, datetime.now(timezone.utc))
pipe = self.redis.pipeline()
pipe.get(keys["minute"])
pipe.get(keys["day"])
pipe.get(keys["tokens_minute"])
pipe.get(keys["tokens_day"])
results = await pipe.execute()
minute_count = int(results[0] or 0)
day_count = int(results[1] or 0)
token_minute_count = int(results[2] or 0)
token_day_count = int(results[3] or 0)
burst_rpm = int(tier.requests_per_minute * tier.burst_multiplier)
if minute_count >= burst_rpm:
return self._rate_limit_response("requests_per_minute", tier.requests_per_minute, 60)
if tier.requests_per_day and day_count >= tier.requests_per_day:
return self._rate_limit_response(
"requests_per_day", tier.requests_per_day, self._seconds_until_day_reset()
)
if token_minute_count + estimated_tokens > tier.tokens_per_minute:
return self._rate_limit_response("tokens_per_minute", tier.tokens_per_minute, 60)
if tier.tokens_per_day and token_day_count + estimated_tokens > tier.tokens_per_day:
return self._rate_limit_response(
"tokens_per_day", tier.tokens_per_day, self._seconds_until_day_reset()
)
return {
"allowed": True,
"tier": tier.name,
"remaining": {
"requests_minute": burst_rpm - minute_count - 1,
"requests_day": (tier.requests_per_day - day_count - 1) if tier.requests_per_day else None,
"tokens_minute": tier.tokens_per_minute - token_minute_count - estimated_tokens,
"tokens_day": (tier.tokens_per_day - token_day_count - estimated_tokens) if tier.tokens_per_day else None
}
}
async def record_request(self, organization_id: str, tokens_used: int):
"""Count a request and its tokens; INCR and EXPIRE go out in one MULTI/EXEC."""
keys = self._keys(organization_id, datetime.now(timezone.utc))
pipe = self.redis.pipeline(transaction=True)
pipe.incr(keys["minute"])
pipe.expire(keys["minute"], 120)
pipe.incr(keys["day"])
pipe.expire(keys["day"], 90000)
pipe.incrby(keys["tokens_minute"], tokens_used)
pipe.expire(keys["tokens_minute"], 120)
pipe.incrby(keys["tokens_day"], tokens_used)
pipe.expire(keys["tokens_day"], 90000)
await pipe.execute()
async def acquire_concurrent_slot(self, organization_id: str, tier_name: str) -> bool:
"""Take a concurrency slot; INCR returns the new value, so the check is atomic."""
tier = self._tier(tier_name)
key = f"ratelimit:{organization_id}:concurrent"
current = await self.redis.incr(key)
await self.redis.expire(key, 300) # safety net if a release is lost
if current > tier.concurrent_requests:
await self.redis.decr(key)
return False
return True
async def release_concurrent_slot(self, organization_id: str):
"""Release concurrent request slot."""
await self.redis.decr(f"ratelimit:{organization_id}:concurrent")
def _rate_limit_response(self, limit_type: str, limit: int, retry_after: int) -> Dict:
return {
"allowed": False,
"error": "rate_limit_exceeded",
"limit_type": limit_type,
"limit": limit,
"retry_after": retry_after,
"message": f"Rate limit exceeded for {limit_type}. Retry after {retry_after} seconds."
}
def _seconds_until_day_reset(self) -> int:
"""Seconds until midnight UTC."""
now = datetime.now(timezone.utc)
tomorrow = now.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)
return int((tomorrow - now).total_seconds())Request Validation
AI-Specific Request Validation
# request_validation.py
from typing import Any, Dict, List, Optional
import re
class ValidationError(Exception):
"""Validation error with details."""
def __init__(self, field: str, message: str, code: str):
self.field = field
self.message = message
self.code = code
super().__init__(message)
class AIRequestValidator:
"""Validate AI API requests before they reach the model.
The model allowlist, size limits and parameter bounds do the real work.
The injection patterns are a weak extra layer: they catch copy-pasted
attacks and miss paraphrases, encodings and indirect injection through
retrieved content (OWASP LLM01:2025). They also produce false positives
("act as a translator"), so log matches before you start blocking on them.
"""
BLOCKED_PATTERNS = [
r'ignore\s+previous\s+instructions',
r'you\s+are\s+now\s+',
r'act\s+as\s+(if\s+)?',
r'pretend\s+to\s+be',
r'system\s*:\s*',
]
def __init__(self, config: Dict):
# No built-in model list: model names change, so the allowlist comes from config
self.allowed_models = set(config["allowed_models"])
self.valid_roles = set(config.get("valid_roles", ["system", "user", "assistant"]))
# Parameter ranges differ per provider; copy them from your provider's API reference
self.temperature_range = config.get("temperature_range", (0.0, 1.0))
self.max_tokens_limit = config.get("max_tokens_limit", 4096)
self.max_prompt_length = config.get("max_prompt_length", 32000)
self.max_messages = config.get("max_messages", 100)
self.blocked_patterns = [re.compile(p, re.IGNORECASE) for p in self.BLOCKED_PATTERNS]
def validate_completion_request(self, request: Dict) -> Dict:
"""Validate chat/completion request."""
errors: List[ValidationError] = []
if "model" not in request:
errors.append(ValidationError("model", "Model is required", "missing_field"))
elif request["model"] not in self.allowed_models:
errors.append(ValidationError("model", f"Model '{request['model']}' is not available", "invalid_model"))
if "messages" in request:
errors.extend(self._validate_messages(request["messages"]))
elif "prompt" in request:
errors.extend(self._validate_text("prompt", request["prompt"]))
else:
errors.append(ValidationError("messages", "Either messages or prompt is required", "missing_field"))
if "temperature" in request:
low, high = self.temperature_range
value = request["temperature"]
if not isinstance(value, (int, float)) or not low <= value <= high:
errors.append(ValidationError(
"temperature", f"Temperature must be between {low} and {high}", "out_of_range"
))
if "max_tokens" in request:
value = request["max_tokens"]
if not isinstance(value, int) or not 1 <= value <= self.max_tokens_limit:
errors.append(ValidationError(
"max_tokens", f"max_tokens must be between 1 and {self.max_tokens_limit}", "out_of_range"
))
if errors:
return {
"valid": False,
"errors": [{"field": e.field, "message": e.message, "code": e.code} for e in errors]
}
return {"valid": True}
@staticmethod
def _text_of(content: Any) -> Optional[str]:
"""Text of a message: a string, or the text parts of a list of content blocks."""
if isinstance(content, str):
return content
if isinstance(content, list):
return "\n".join(
part.get("text", "") for part in content if isinstance(part, dict)
)
return None
def _validate_messages(self, messages: Any) -> List[ValidationError]:
"""Validate chat messages."""
if not isinstance(messages, list):
return [ValidationError("messages", "Messages must be an array", "invalid_type")]
errors = []
if len(messages) > self.max_messages:
errors.append(ValidationError(
"messages", f"Maximum {self.max_messages} messages allowed", "too_many_messages"
))
for i, message in enumerate(messages):
if not isinstance(message, dict):
errors.append(ValidationError(f"messages[{i}]", "Message must be an object", "invalid_type"))
continue
if message.get("role") not in self.valid_roles:
errors.append(ValidationError(
f"messages[{i}].role",
f"Invalid role. Must be one of: {sorted(self.valid_roles)}",
"invalid_role"
))
if "content" not in message:
errors.append(ValidationError(f"messages[{i}].content", "Content is required", "missing_field"))
continue
errors.extend(self._validate_text(f"messages[{i}].content", message["content"]))
return errors
def _validate_text(self, field: str, content: Any) -> List[ValidationError]:
"""Length and pattern checks on one piece of text."""
text = self._text_of(content)
if text is None:
return [ValidationError(field, "Content must be a string or a list of content blocks", "invalid_type")]
errors = []
if len(text) > self.max_prompt_length:
errors.append(ValidationError(
field, f"Content exceeds maximum length of {self.max_prompt_length}", "content_too_long"
))
if any(p.search(text) for p in self.blocked_patterns):
errors.append(ValidationError(field, "Content contains blocked patterns", "blocked_content"))
return errorsSecurity Middleware
Complete API Security Pipeline
# security_middleware.py
import logging
import time
from typing import Dict
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
logger = logging.getLogger(__name__)
class AISecurityMiddleware(BaseHTTPMiddleware):
"""Authentication, rate limiting and concurrency limits for every request.
Errors are returned as responses instead of raised as HTTPException, so they
don't depend on where exception handlers sit in the middleware stack.
Scope checks and body validation run as route dependencies (require_scope,
validate_ai_request), where FastAPI has already parsed the request.
"""
def __init__(self, app: FastAPI, config: Dict):
super().__init__(app)
self.api_key_manager = APIKeyManager(config["key_store"])
self.rate_limiter = AIRateLimiter(config["redis"])
# Placeholder estimate; record real usage from the model response where you have it
self.default_token_estimate = config.get("default_token_estimate", 1000)
async def dispatch(self, request: Request, call_next):
if request.url.path in ("/health", "/ready"):
return await call_next(request)
# 1. Authenticate
auth_result = self._authenticate(request)
if not auth_result["valid"]:
return JSONResponse({"detail": auth_result["error"]}, status_code=401)
org_id = auth_result["organization_id"]
tier = auth_result["rate_limit_tier"]
request.state.organization_id = org_id
request.state.user_scopes = auth_result["scopes"]
request.state.rate_limit_tier = tier
# 2. Rate limits
rate_result = await self.rate_limiter.check_rate_limit(
organization_id=org_id,
tier_name=tier,
estimated_tokens=self.default_token_estimate
)
if not rate_result["allowed"]:
return JSONResponse(
{"detail": rate_result["message"]},
status_code=429,
headers={
"Retry-After": str(rate_result["retry_after"]),
"X-RateLimit-Limit": str(rate_result["limit"])
}
)
# 3. Concurrency slot
if not await self.rate_limiter.acquire_concurrent_slot(org_id, tier):
return JSONResponse(
{"detail": "Too many concurrent requests"},
status_code=429,
headers={"Retry-After": "5"}
)
# 4. Count the admitted request, then process it
await self.rate_limiter.record_request(org_id, tokens_used=self.default_token_estimate)
start_time = time.monotonic()
try:
response = await call_next(request)
except Exception:
logger.exception("Unhandled error for organization %s", org_id)
return JSONResponse({"detail": "Internal server error"}, status_code=500)
finally:
await self.rate_limiter.release_concurrent_slot(org_id)
logger.info("org=%s path=%s status=%s duration=%.3fs",
org_id, request.url.path, response.status_code, time.monotonic() - start_time)
response.headers["X-RateLimit-Remaining"] = str(rate_result["remaining"]["requests_minute"])
return response
def _authenticate(self, request: Request) -> Dict:
auth_header = request.headers.get("Authorization")
if not auth_header:
return {"valid": False, "error": "Missing authorization header"}
if auth_header.startswith("Bearer "):
return self.api_key_manager.validate_key(auth_header[7:])
return {"valid": False, "error": "Invalid authorization format"}
async def validate_ai_request(request: Request) -> None:
"""Route dependency: validate the JSON body of AI requests."""
validator = request.app.state.request_validator
try:
body = await request.json()
except ValueError:
raise HTTPException(status_code=400, detail="Body must be valid JSON")
if not isinstance(body, dict):
raise HTTPException(status_code=400, detail="Body must be a JSON object")
result = validator.validate_completion_request(body)
if not result["valid"]:
raise HTTPException(status_code=400, detail={"errors": result["errors"]})
# Wiring:
# app = FastAPI()
# app.state.request_validator = AIRequestValidator(config)
# app.add_middleware(AISecurityMiddleware, config=config)
#
# @app.post("/v1/chat", dependencies=[
# Depends(require_scope(AIScope.COMPLETIONS_CREATE)),
# Depends(validate_ai_request),
# ])
# async def chat(...): ...Conclusion
Securing AI APIs requires comprehensive measures:
- Strong Authentication - API keys with rotation and RS256 JWTs verified against issuer and audience
- Fine-Grained Authorization - Scope-based access control enforced as a route dependency
- Rate Limiting - Per-minute, per-day, token and concurrency limits with burst handling
- Request Validation - Model allowlist, parameter bounds and size limits; pattern checks for prompt injection are only a weak extra layer, because OWASP notes it is unclear if there are fool-proof methods of prevention
- Complete Pipeline - Middleware for authentication and limits, route dependencies for scopes and validation
By implementing these security measures, you can protect your AI APIs from abuse while providing a reliable service to legitimate users.
From production
In JARVIS, the multi-agent platform DeviDevs runs on, a hook scans content for secrets at commit. The reason is written in the code itself: once a secret reaches git history it cannot be taken back, so the key has to be rotated. Between 7 September and 15 November 2026 that check produced 45 real blocks. This is why the key manager above treats a leaked key as a revocation, not a rotation with a grace period.
Official references
- API Reference - PyJWT
- Middleware - Starlette
- Dependencies in path operation decorators - FastAPI
- INCR - Redis documentation
- LLM01:2025 Prompt Injection - OWASP Gen AI Security Project
- LLM10:2025 Unbounded Consumption - OWASP Gen AI Security Project
Related on this site: Every AI Security Startup Got Acquired. Now What?, Your AI Agent Framework Is Probably Compromised Right Now, Securing AI Chatbots: Enterprise Implementation Guide. More articles in the AI Security category, and the engineering work behind them is on the services page.
Need an AI system built and running in production, with the scope agreed in writing and a delivery guarantee? See how a DeviDevs Sprint works →