Navigation

FastAPIでJWT認証を実装する方法

📅 7月 9, 2025
👤
2 min read

FastAPIでJWT認証を実装する方法

概要

FastAPIはPythonの高速なWebフレームワークであり、JWT(JSON Web Token)認証を実装することで、セキュリティを向上させることができます。JWT認証は、トークンベースの認証であり、クライアントが認証情報を保持するため、セッション管理が容易であり、スケーラビリティが高い特徴があります。

環境構築


# 必要ライブラリのインストール
pip install fastapi pyjwt

実装コード


from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
import jwt
from jwt import PyJWTError
from typing import Optional

app = FastAPI()

# 任意のシークレットキーを設定
SECRET_KEY = "your_secret_key"
ALGORITHM = "HS256"

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

# ログインユーザの認証
def get_current_user(token: str = Depends(oauth2_scheme)):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise HTTPException(status_code=401, detail="Invalid authentication credentials")
    except PyJWTError:
        raise HTTPException(status_code=401, detail="Invalid authentication credentials")
    return username

# ログインエンドポイント
@app.post("/token")
async def login_for_access_token(username: str, password: str):
    # ユーザ認証のロジックを実装
    user = authenticate_user(username, password)
    if user is None:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    token = jwt.encode({"sub": username}, SECRET_KEY, algorithm=ALGORITHM)
    return {"access_token": token, "token_type": "bearer"}

# プライベートなエンドポイント
@app.get("/private_data")
async def get_private_data(current_user: str = Depends(get_current_user)):
    return {"data": "This is private data"}

使用例


# ログインしてトークンを取得
# トークンを使用してプライベートデータにアクセス

テストコード


import pytest

# テスト用のユーザ認証関数
def test_authenticate_user():
    assert authenticate_user("test_user", "password") == "test_user"
    assert authenticate_user("invalid_user", "password") is None

# テスト用のトークン生成関数
def test_generate_token():
    token = jwt.encode({"sub": "test_user"}, SECRET_KEY, algorithm=ALGORITHM)
    assert token is not None

応用・カスタマイズ

  • より複雑な認証ロジックの実装
  • JWTの有効期限管理
  • エラーハンドリングの改善

関連技術

  • Pydantic:FastAPIでのデータバリデーションに利用
  • FastAPI JWT Auth:FastAPIでJWT認証をさらに簡単に実装可能
  • FastAPI 公式ドキュメント:https://fastapi.tiangolo.com/

この記事では、FastAPIを使用してJWT認証を実装する方法について紹介しました。JWT認証を導入することで、FastAPIアプリケーションのセキュリティを向上させることができます。JWT認証は、堅牢で柔軟な認証手法であり、FastAPIとの組み合わせは効果的です。

← Back to Python