FastAPI セキュリティ認証
FastAPIには複数のセキュリティツールが組み込まれており、OAuth2、JWTトークン、APIキーなどの一般的な認証・承認方式をサポートしています。このセクションでは、OAuth2 + JWT に基づくユーザー認証の実装方法を紹介します。
セキュリティ認証の概要
FastAPIがサポートするセキュリティ方式:
| 方式 | 適用シナリオ | 説明 |
|---|---|---|
| HTTP Basic Auth | シンプルな内部サービス | ユーザー名とパスワードをリクエストヘッダーにエンコードするため、安全性は低い |
| API Key | サービス間の呼び出し | リクエストヘッダー、クエリパラメータ、Cookieを介してAPIキーを渡す |
| OAuth2 + JWT | フロントエンドとバックエンドを分離したアプリケーション | 最も一般的な方式で、安全かつ柔軟 |
OAuth2 パスワードモード + JWT
これは、フロントエンドとバックエンドが分離されたアプリケーションで最もよく使われる認証方式です。フロー:
- クライアントはユーザー名とパスワードを
/tokenエンドポイントへ送信します。 - サーバーは資格情報を検証し、JWTアクセストークンを返します。
- クライアントは後続のリクエストでトークンを携帯します(
Authorization: Bearer <token>) - サーバーはトークンを検証してユーザーを識別します。
1. 依存関係のインストール
pip install "python-jose[cryptography]" passlib[bcrypt]
2. 完全な例
例
from datetime import datetime, timedelta
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
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: str | None = None
class User(BaseModel):
username: str
email: str | None = None
full_name: str | None = None
disabled: bool | None = None
class UserInDB(User):
hashed_password: str
# ===== 模擬データベース =====
fake_users_db = {
"alice": {
"username": "alice",
"full_name": "Alice Wonderson",
"email": "alice@example.com",
"hashed_password": pwd_context.hash("secret"), # パスワード: secret
"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: dict, username: str) -> UserInDB | None:
"""データベースからユーザーを取得する"""
if username in db:
return UserInDB(**db[username])
return None
def authenticate_user(db: dict, username: str, password: str):
"""ユーザーの資格情報を検証する"""
user = get_user(db, username)
if not user:
return False
if not verify_password(password, user.hashed_password):
return False
return user
def create_access_token(data: dict, expires_delta: timedelta | None = None):
"""JWTアクセストークンを作成する"""
to_encode = data.copy()
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=15))
to_encode.update({"exp": expire})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
トークンから現在のユーザーを取得する(依存関数)
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="資格情報を検証できません",
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
except JWTError:
raise credentials_exception
user = get_user(fake_users_db, username)
if user is None:
raise credentials_exception
return user
async def get_current_active_user(
current_user: Annotated[User, Depends(get_current_user)],
):
"""現在のアクティブユーザーを取得する"""
if current_user.disabled:
raise HTTPException(status_code=400, detail="ユーザーは無効化されています")
return current_user
# ===== ルート =====
app = FastAPI()
@app.post("/token")
async def login(form_data: Annotated[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="ユーザー名またはパスワードが間違っています",
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")
async def read_users_me(
current_user: Annotated[User, Depends(get_current_active_user)],
):
現在のユーザー情報を取得する(認証が必要)
return current_user
@app.get("/users/me/items")
async def read_own_items(
current_user: Annotated[User, Depends(get_current_active_user)],
):
現在のユーザーの項目を取得する(認証が必要)
return [{"item_id": "Foo", "owner": current_user.username}]
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
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: str | None = None
class User(BaseModel):
username: str
email: str | None = None
full_name: str | None = None
disabled: bool | None = None
class UserInDB(User):
hashed_password: str
# ===== 模擬データベース =====
fake_users_db = {
"alice": {
"username": "alice",
"full_name": "Alice Wonderson",
"email": "alice@example.com",
"hashed_password": pwd_context.hash("secret"), # パスワード: secret
"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: dict, username: str) -> UserInDB | None:
"""データベースからユーザーを取得する"""
if username in db:
return UserInDB(**db[username])
return None
def authenticate_user(db: dict, username: str, password: str):
"""ユーザーの資格情報を検証する"""
user = get_user(db, username)
if not user:
return False
if not verify_password(password, user.hashed_password):
return False
return user
def create_access_token(data: dict, expires_delta: timedelta | None = None):
"""JWTアクセストークンを作成する"""
to_encode = data.copy()
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=15))
to_encode.update({"exp": expire})
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
トークンから現在のユーザーを取得する(依存関数)
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="資格情報を検証できません",
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
except JWTError:
raise credentials_exception
user = get_user(fake_users_db, username)
if user is None:
raise credentials_exception
return user
async def get_current_active_user(
current_user: Annotated[User, Depends(get_current_user)],
):
"""現在のアクティブユーザーを取得する"""
if current_user.disabled:
raise HTTPException(status_code=400, detail="ユーザーは無効化されています")
return current_user
# ===== ルート =====
app = FastAPI()
@app.post("/token")
async def login(form_data: Annotated[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="ユーザー名またはパスワードが間違っています",
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")
async def read_users_me(
current_user: Annotated[User, Depends(get_current_active_user)],
):
現在のユーザー情報を取得する(認証が必要)
return current_user
@app.get("/users/me/items")
async def read_own_items(
current_user: Annotated[User, Depends(get_current_active_user)],
):
現在のユーザーの項目を取得する(認証が必要)
return [{"item_id": "Foo", "owner": current_user.username}]
コード解析
パスワードハッシュ
使用するpasslibbcryptアルゴリズムでパスワードをハッシュ化し、データベースに平文パスワードを保存しないようにします:
| 関数 | 説明 |
|---|---|
pwd_context.hash(password) | 平文パスワードをハッシュ値に変換する |
pwd_context.verify(plain, hashed) | 平文パスワードがハッシュ値と一致するか検証する |
JWT トークン
JWT(JSON Web Token)は、ユーザー情報と有効期限を含む安全なトークン形式です:
| 操作 | 関数 | 説明 |
|---|---|---|
| トークンの作成 | jwt.encode() | データをJWT文字列にエンコードする |
| トークンの解析 | jwt.decode() | JWT文字列を解析して検証する |
| 有効期限の設定 | "exp": expire | トークンの有効期限 |
| ユーザー識別子の保存 | "sub": username | トークンの主体(通常はユーザー名) |
OAuth2PasswordBearer
FastAPIに、リクエストヘッダーからAuthorization: Bearer <token>トークンを取得するよう指示します。
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
tokenUrl="token"クライアントがトークンを取得するエンドポイントパスを指定し、APIドキュメントに表示されます。
SECRET_KEY秘密に保ち、かつ十分に複雑でなければなりません。本番環境では環境変数に保存する必要があります。鍵が漏洩すると、攻撃者は任意のユーザーのトークンを偽造できます。
API ドキュメントを使ったテスト
OAuth2を設定すると、Swagger UIに「Authorize」ボタンが表示されます:
- クリック"Authorize"
- ユーザー名とパスワードを入力します(例:
alice/secret) - クリック"Authorize"トークンを取得
- 以降のすべてのリクエストは自動的にトークンを保持します
まとめ
- OAuth2 + JWT は、フロントエンドとバックエンドが分離されたアプリケーションで最もよく使われる認証方式です
- パスワードはハッシュ化して保存しなければならず、平文で保存してはいけません
- JWTトークンにはユーザー識別子と有効期限が含まれます
- 依存性注入を使用する(
Depends)ことで、認証ロジックを再利用できます - 本番環境ではSECRET_KEYを秘密に保つ必要があります