48 lines
1.6 KiB
Python

import logging
from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.types import ASGIApp
logger = logging.getLogger(__name__)
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
"""
Middleware to add security headers to responses.
"""
def __init__(
self,
app: ASGIApp,
content_security_policy: str = None,
):
super().__init__(app)
self.content_security_policy = content_security_policy or "default-src 'self'"
async def dispatch(self, request: Request, call_next) -> Response:
"""
Process the request and add security headers to the response.
Args:
request: The incoming request
call_next: The next handler in the middleware chain
Returns:
The response with added security headers
"""
# Process the request
response = await call_next(request)
# Add security headers
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["X-XSS-Protection"] = "1; mode=block"
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
response.headers["Content-Security-Policy"] = self.content_security_policy
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
response.headers["Pragma"] = "no-cache"
return response