This commit is contained in:
admin
2026-05-22 23:05:25 +09:00
parent cea3016fbe
commit e8690d130b
23 changed files with 581 additions and 187 deletions

View File

@@ -2,9 +2,11 @@ from dotenv import load_dotenv
load_dotenv()
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, RedirectResponse
from fastapi.responses import JSONResponse, RedirectResponse, Response
from pydantic import ValidationError
from fastapi.middleware.cors import CORSMiddleware
from starlette.datastructures import MutableHeaders
from starlette.types import ASGIApp, Receive, Scope, Send
# FastAPI アプリケーション作成
app = FastAPI(
@@ -12,13 +14,37 @@ app = FastAPI(
)
class SecurityHeadersMiddleware:
"""キャッシュ禁止・セキュリティヘッダーを全レスポンスに付与ASGIネイティブ実装"""
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
async def send_with_headers(message):
if message["type"] == "http.response.start":
headers = MutableHeaders(scope=message)
headers["Cache-Control"] = "no-store, no-cache, must-revalidate, private"
headers["Pragma"] = "no-cache"
headers["Expires"] = "0"
headers["X-Frame-Options"] = "DENY"
headers["X-Content-Type-Options"] = "nosniff"
headers["X-XSS-Protection"] = "1; mode=block"
await send(message)
await self.app(scope, receive, send_with_headers)
app.add_middleware(SecurityHeadersMiddleware)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["Content-Type", "Authorization"],
)
# ─────────────────────────