Trung BìnhFastAPI iconFastAPI

OAuth2/JWT trong FastAPI thường được implement thế nào?

Pattern phổ biến: login endpoint verify credentials, cấp access token ngắn hạn; protected endpoints dùng dependency đọc Bearer token, verify signature/expiry, load user và inject current_user.

Ví dụ dependency rút gọn:

python
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")

async def current_user(token: Annotated[str, Depends(oauth2_scheme)]):
    payload = jwt.decode(token, SECRET, algorithms=["HS256"])
    return await users.get(payload["sub"])

Trong production cần refresh token, revoke/session strategy, password hashing mạnh, rotation secret/key và phân quyền theo scope/role.

Xem toàn bộ FastAPI cùng filter theo level & chủ đề con.

Mở danh sách FastAPI