Backend
FastAPI中級ガイド - 認証・ミドルウェア・依存性注入完全解説
kitahara-dev•2025/11/04•14 min read
FastAPI中級ガイド - 認証・ミドルウェア・依存性注入完全解説
FastAPIの基本を習得したら、次は認証・認可、ミドルウェア、依存性注入などの中級テクニックを学びましょう。本ガイドでは、実務で必要となる高度な機能を実践的なコード例とともに解説します。
📋 目次
- JWT認証の実装
- OAuth2とパスワードフロー
- 依存性注入(Dependency Injection)
- ミドルウェアの実装
- CORS設定
- 背景タスク(Background Tasks)
- WebSocketの実装
- ファイルアップロード
- セキュリティベストプラクティス
- カスタムエラーハンドリング
1. JWT認証の実装
JSON Web Token(JWT)を使った認証システムを構築します。
必要なライブラリのインストール
pip install "python-jose[cryptography]" "passlib[bcrypt]" python-multipart
JWT認証の完全実装
# auth.py
from datetime import datetime, timedelta
from typing import Optional
from jose import JWTError, jwt
from passlib.context import CryptContext
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel
# 設定
SECRET_KEY = "your-secret-key-keep-it-secret" # 本番では環境変数から取得
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
# パスワードハッシュ化
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# OAuth2スキーム
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# モデル
class Token(BaseModel):
access_token: str
token_type: str
class TokenData(BaseModel):
username: Optional[str] = None
class User(BaseModel):
username: str
email: Optional[str] = None
full_name: Optional[str] = None
disabled: Optional[bool] = None
class UserInDB(User):
hashed_password: str
# ダミーデータベース
fake_users_db = {
"johndoe": {
"username": "johndoe",
"full_name": "John Doe",
"email": "johndoe@example.com",
"hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW",
"disabled": False,
}
}
# ユーティリティ関数
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
def get_user(db, username: str) -> Optional[UserInDB]:
if username in db:
user_dict = db[username]
return UserInDB(**user_dict)
return None
def authenticate_user(fake_db, username: str, password: str) -> Optional[UserInDB]:
user = get_user(fake_db, username)
if not user:
return None
if not verify_password(password, user.hashed_password):
return None
return user
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
token_data = TokenData(username=username)
except JWTError:
raise credentials_exception
user = get_user(fake_users_db, username=token_data.username)
if user is None:
raise credentials_exception
return user
async def get_current_active_user(current_user: User = Depends(get_current_user)) -> User:
if current_user.disabled:
raise HTTPException(status_code=400, detail="Inactive user")
return current_user
エンドポイントの実装
# main.py
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from datetime import timedelta
from auth import (
authenticate_user, create_access_token, get_current_active_user,
fake_users_db, ACCESS_TOKEN_EXPIRE_MINUTES, Token, User
)
app = FastAPI()
@app.post("/token", response_model=Token)
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
@app.get("/users/me", response_model=User)
async def read_users_me(current_user: User = Depends(get_current_active_user)):
return current_user
@app.get("/items/")
async def read_items(current_user: User = Depends(get_current_active_user)):
return [{"item_id": 1, "owner": current_user.username}]
2. OAuth2とパスワードフロー
OAuth2のパスワードフローを実装します。
スコープ付きOAuth2
from fastapi import Security
from fastapi.security import OAuth2PasswordBearer, SecurityScopes
oauth2_scheme = OAuth2PasswordBearer(
tokenUrl="token",
scopes={
"me": "Read information about the current user",
"items": "Read items",
"items:write": "Write items"
}
)
async def get_current_user(
security_scopes: SecurityScopes,
token: str = Depends(oauth2_scheme)
) -> User:
if security_scopes.scopes:
authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
else:
authenticate_value = "Bearer"
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": authenticate_value},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
token_scopes = payload.get("scopes", [])
token_data = TokenData(scopes=token_scopes, username=username)
except JWTError:
raise credentials_exception
user = get_user(fake_users_db, username=token_data.username)
if user is None:
raise credentials_exception
for scope in security_scopes.scopes:
if scope not in token_data.scopes:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not enough permissions",
headers={"WWW-Authenticate": authenticate_value},
)
return user
@app.get("/users/me/items/")
async def read_own_items(
current_user: User = Security(get_current_active_user, scopes=["items"])
):
return [{"item_id": 1, "owner": current_user.username}]
3. 依存性注入(Dependency Injection)
FastAPIの強力な依存性注入システムを活用します。
基本的な依存性
from fastapi import Depends, HTTPException, Header
from typing import Optional
# 共通クエリパラメータ
async def common_parameters(q: Optional[str] = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
return commons
@app.get("/users/")
async def read_users(commons: dict = Depends(common_parameters)):
return commons
# クラスベースの依存性
class CommonQueryParams:
def __init__(self, q: Optional[str] = None, skip: int = 0, limit: int = 100):
self.q = q
self.skip = skip
self.limit = limit
@app.get("/items/")
async def read_items(commons: CommonQueryParams = Depends()):
response = {}
if commons.q:
response.update({"q": commons.q})
items = fake_items_db[commons.skip : commons.skip + commons.limit]
response.update({"items": items})
return response
サブ依存性
def query_extractor(q: Optional[str] = None):
return q
def query_or_cookie_extractor(
q: str = Depends(query_extractor),
last_query: Optional[str] = Cookie(None)
):
if not q:
return last_query
return q
@app.get("/items/")
async def read_query(query_or_default: str = Depends(query_or_cookie_extractor)):
return {"q_or_cookie": query_or_default}
グローバル依存性
async def verify_token(x_token: str = Header(...)):
if x_token != "fake-super-secret-token":
raise HTTPException(status_code=400, detail="X-Token header invalid")
async def verify_key(x_key: str = Header(...)):
if x_key != "fake-super-secret-key":
raise HTTPException(status_code=400, detail="X-Key header invalid")
return x_key
app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)])
@app.get("/items/")
async def read_items():
return [{"item": "Portal Gun"}, {"item": "Plumbus"}]
@app.get("/users/")
async def read_users():
return [{"username": "Rick"}, {"username": "Morty"}]
4. ミドルウェアの実装
リクエスト/レスポンスを処理するミドルウェアを作成します。
カスタムミドルウェア
import time
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import Response
class TimingMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
app.add_middleware(TimingMiddleware)
# ログミドルウェア
class LoggingMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
print(f"Request: {request.method} {request.url}")
response = await call_next(request)
print(f"Response status: {response.status_code}")
return response
app.add_middleware(LoggingMiddleware)
組み込みミドルウェア
from starlette.middleware.gzip import GZipMiddleware
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware
from starlette.middleware.trustedhost import TrustedHostMiddleware
# Gzip圧縮
app.add_middleware(GZipMiddleware, minimum_size=1000)
# HTTPS リダイレクト(本番環境のみ)
# app.add_middleware(HTTPSRedirectMiddleware)
# 信頼できるホストの設定
app.add_middleware(
TrustedHostMiddleware,
allowed_hosts=["example.com", "*.example.com"]
)
5. CORS設定
クロスオリジンリソース共有(CORS)を設定します。
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# CORS設定
origins = [
"http://localhost",
"http://localhost:3000",
"http://localhost:8080",
"https://example.com",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins, # 許可するオリジン
allow_credentials=True, # クッキーを許可
allow_methods=["*"], # 許可するHTTPメソッド
allow_headers=["*"], # 許可するHTTPヘッダー
)
# すべてのオリジンを許可(開発環境のみ)
# app.add_middleware(
# CORSMiddleware,
# allow_origins=["*"],
# allow_credentials=True,
# allow_methods=["*"],
# allow_headers=["*"],
# )
@app.get("/")
async def main():
return {"message": "Hello World"}
6. 背景タスク(Background Tasks)
時間のかかる処理を背景で実行します。
from fastapi import BackgroundTasks
import time
def write_log(message: str):
with open("log.txt", mode="a") as log:
log.write(message)
time.sleep(2) # 重い処理をシミュレート
def send_email(email: str, message: str):
print(f"Sending email to {email}: {message}")
time.sleep(5) # メール送信をシミュレート
@app.post("/send-notification/{email}")
async def send_notification(
email: str,
background_tasks: BackgroundTasks,
message: str = "Hello"
):
background_tasks.add_task(send_email, email, message)
background_tasks.add_task(write_log, f"Email sent to {email}")
return {"message": "Notification sent in the background"}
# 複数の背景タスク
@app.post("/items/{item_id}")
async def create_item(
item_id: int,
background_tasks: BackgroundTasks
):
background_tasks.add_task(write_log, f"Item {item_id} created")
background_tasks.add_task(send_email, "admin@example.com", "New item created")
return {"item_id": item_id, "status": "created"}
7. WebSocketの実装
リアルタイム通信のためのWebSocketを実装します。
from fastapi import WebSocket, WebSocketDisconnect
from typing import List
class ConnectionManager:
def __init__(self):
self.active_connections: List[WebSocket] = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
def disconnect(self, websocket: WebSocket):
self.active_connections.remove(websocket)
async def send_personal_message(self, message: str, websocket: WebSocket):
await websocket.send_text(message)
async def broadcast(self, message: str):
for connection in self.active_connections:
await connection.send_text(message)
manager = ConnectionManager()
@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: int):
await manager.connect(websocket)
try:
while True:
data = await websocket.receive_text()
await manager.send_personal_message(f"You wrote: {data}", websocket)
await manager.broadcast(f"Client #{client_id} says: {data}")
except WebSocketDisconnect:
manager.disconnect(websocket)
await manager.broadcast(f"Client #{client_id} left the chat")
# HTMLクライアント例
html = """
<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
</head>
<body>
<h1>WebSocket Chat</h1>
<form action="" onsubmit="sendMessage(event)">
<input type="text" id="messageText" autocomplete="off"/>
<button>Send</button>
</form>
<ul id='messages'>
</ul>
<script>
var ws = new WebSocket("ws://localhost:8000/ws/123");
ws.onmessage = function(event) {
var messages = document.getElementById('messages')
var message = document.createElement('li')
var content = document.createTextNode(event.data)
message.appendChild(content)
messages.appendChild(message)
};
function sendMessage(event) {
var input = document.getElementById("messageText")
ws.send(input.value)
input.value = ''
event.preventDefault()
}
</script>
</body>
</html>
"""
@app.get("/")
async def get():
return HTMLResponse(html)
8. ファイルアップロード
ファイルのアップロードとダウンロードを実装します。
from fastapi import File, UploadFile
from fastapi.responses import FileResponse
from typing import List
import shutil
from pathlib import Path
UPLOAD_DIR = Path("uploads")
UPLOAD_DIR.mkdir(exist_ok=True)
# 単一ファイルアップロード
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
file_path = UPLOAD_DIR / file.filename
with file_path.open("wb") as buffer:
shutil.copyfileobj(file.file, buffer)
return {
"filename": file.filename,
"content_type": file.content_type,
"size": file_path.stat().st_size
}
# 複数ファイルアップロード
@app.post("/uploadfiles/")
async def create_upload_files(files: List[UploadFile] = File(...)):
file_info = []
for file in files:
file_path = UPLOAD_DIR / file.filename
with file_path.open("wb") as buffer:
shutil.copyfileobj(file.file, buffer)
file_info.append({
"filename": file.filename,
"content_type": file.content_type,
"size": file_path.stat().st_size
})
return {"files": file_info}
# ファイルダウンロード
@app.get("/download/{filename}")
async def download_file(filename: str):
file_path = UPLOAD_DIR / filename
if not file_path.exists():
raise HTTPException(status_code=404, detail="File not found")
return FileResponse(
path=file_path,
filename=filename,
media_type="application/octet-stream"
)
# 画像アップロードとバリデーション
@app.post("/upload-image/")
async def upload_image(file: UploadFile = File(...)):
# 画像ファイルのみ許可
if not file.content_type.startswith("image/"):
raise HTTPException(
status_code=400,
detail="File must be an image"
)
# ファイルサイズ制限(5MB)
MAX_SIZE = 5 * 1024 * 1024
contents = await file.read()
if len(contents) > MAX_SIZE:
raise HTTPException(
status_code=400,
detail="File size must be less than 5MB"
)
file_path = UPLOAD_DIR / file.filename
with file_path.open("wb") as buffer:
buffer.write(contents)
return {
"filename": file.filename,
"size": len(contents),
"content_type": file.content_type
}
9. セキュリティベストプラクティス
セキュアなヘッダー設定
from starlette.middleware.base import BaseHTTPMiddleware
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
response = await call_next(request)
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"] = "default-src 'self'"
return response
app.add_middleware(SecurityHeadersMiddleware)
レート制限
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
@app.get("/limited")
@limiter.limit("5/minute")
async def limited_route(request: Request):
return {"message": "This route is rate limited"}
SQL インジェクション対策
# ❌ 悪い例:SQLインジェクションの脆弱性
@app.get("/users/{user_id}")
async def get_user(user_id: str):
# 危険!ユーザー入力を直接SQLに含めている
query = f"SELECT * FROM users WHERE id = {user_id}"
# result = db.execute(query)
# ✅ 良い例:パラメータ化されたクエリ
@app.get("/users/{user_id}")
async def get_user(user_id: int): # 型ヒントでバリデーション
# パラメータ化されたクエリを使用
query = "SELECT * FROM users WHERE id = ?"
# result = db.execute(query, (user_id,))
10. カスタムエラーハンドリング
独自のエラーハンドラーを実装します。
from fastapi import Request, status
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
# カスタム例外クラス
class UnicornException(Exception):
def __init__(self, name: str):
self.name = name
# カスタム例外ハンドラー
@app.exception_handler(UnicornException)
async def unicorn_exception_handler(request: Request, exc: UnicornException):
return JSONResponse(
status_code=418,
content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
)
@app.get("/unicorns/{name}")
async def read_unicorn(name: str):
if name == "yolo":
raise UnicornException(name=name)
return {"unicorn_name": name}
# バリデーションエラーのカスタマイズ
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content={
"detail": exc.errors(),
"body": exc.body,
"custom_message": "入力値が正しくありません"
},
)
# HTTPExceptionのオーバーライド
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
return JSONResponse(
status_code=exc.status_code,
content={
"message": exc.detail,
"status_code": exc.status_code,
"path": str(request.url)
},
)
# 汎用エラーハンドラー
@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
return JSONResponse(
status_code=500,
content={
"message": "Internal server error",
"error": str(exc)
},
)
📝 まとめ
FastAPI中級編で学んだ内容:
認証・認可
- ✅ JWT認証 - トークンベース認証の実装
- ✅ OAuth2 - パスワードフロー、スコープ管理
- ✅ パスワードハッシュ化 - bcryptによる安全な保存
アーキテクチャ
- ✅ 依存性注入 - 再利用可能なコンポーネント
- ✅ ミドルウェア - リクエスト/レスポンス処理
- ✅ CORS設定 - クロスオリジン対応
高度な機能
- ✅ 背景タスク - 非同期処理
- ✅ WebSocket - リアルタイム通信
- ✅ ファイルアップロード - マルチパート対応
セキュリティ
- ✅ ベストプラクティス - セキュアヘッダー、レート制限
- ✅ エラーハンドリング - カスタム例外処理
🔗 次のステップ
実践編では以下を学習します:
- FastAPI実践編 - データベース連携(SQLAlchemy、Alembic)、テスト(pytest)、デプロイ(Docker、AWS/GCP)
🔗 参考リンク
- FastAPI Security
- FastAPI WebSockets
- FastAPI Middleware
- OAuth2 with Password (and hashing), Bearer with JWT tokens
FastAPIで堅牢でセキュアなWeb APIを構築しましょう!
#Python#FastAPI#JWT#OAuth2#Security#WebSocket
著者について
kitahara-devによって執筆されました。