Khi API của bạn có nhiều endpoint cần đăng nhập, đừng viết lại đoạn kiểm tra token ở từng hàm. Hãy gom logic xác thực JWT vào một dependency dùng chung — mỗi route cần bảo vệ chỉ thêm Depends(get_current_user) là xong. Cách này áp dụng cho mọi dự án FastAPI dùng OAuth2 password flow với JWT.

Vấn đề

Cách phổ biến khi mới làm FastAPI là kiểm tra token ngay trong từng endpoint:

from fastapi import FastAPI, Header, HTTPException
app = FastAPI()
@app.get("/users/me")
async def read_users_me(authorization: str | None = Header(default=None)):
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(status_code=401, detail="Thiếu token")
token = authorization.split(" ", 1)[1]
# ... decode token, kiểm tra hạn, lấy user ...
return {"username": "..."}

Với 10 endpoint, đoạn này lặp lại 10 lần: ai cũng sợ, sửa một chỗ quên chín chỗ. Còn nếu sau này đổi cách lưu session, đổi thuật toán ký token, bạn phải lần mò từng file.

Giải pháp

FastAPI có sẵn hệ thống dependency injection: viết một hàm get_current_user duy nhất trích và xác thực token, rồi mọi route chỉ việc khai báo Depends().

from datetime import datetime, timedelta, timezone
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
# Cài đặt: pip install fastapi "python-jose[cryptography]" "passlib[bcrypt]" "python-multipart"
SECRET_KEY = "thay-bang-chuoi-ngau-nhien-secrets.token_hex(32)"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# Ví dụ dùng dict giả; dự án thật thay bằng truy vấn database
fake_users_db = {
"linh": {
"username": "linh",
"full_name": "Linh Fish",
"hashed_password": pwd_context.hash("matkhau123"),
"disabled": False,
}
}
class Token(BaseModel):
access_token: str
token_type: str
def verify_password(plain: str, hashed: str) -> bool:
return pwd_context.verify(plain, hashed)
def get_user(username: str):
return fake_users_db.get(username)
def authenticate_user(username: str, password: str):
user = get_user(username)
if not user or not verify_password(password, user["hashed_password"]):
return None
return user
def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
to_encode = data.copy()
expire = datetime.now(timezone.utc) + (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: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Không xác thực được token",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str | None = payload.get("sub")
if username is None:
raise credentials_exception
except JWTError:
raise credentials_exception
user = get_user(username)
if user is None:
raise credentials_exception
return user
app = FastAPI()
@app.post("/token", response_model=Token)
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(form_data.username, form_data.password)
if not user:
raise HTTPException(status_code=400, detail="Sai username hoặc mật khẩu")
access_token = create_access_token(
data={"sub": user["username"]},
expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES),
)
return {"access_token": access_token, "token_type": "bearer"}
@app.get("/users/me")
async def read_users_me(current_user: dict = Depends(get_current_user)):
return {"username": current_user["username"], "full_name": current_user["full_name"]}

Vì sao tốt hơn: oauth2_scheme tự trích token từ header Authorization: Bearer …; dependency get_current_user chạy trước endpoint và ném lỗi 401 tập trung một chỗ. Endpoint mới cần bảo vệ chỉ thêm một tham số Depends(get_current_user) — không động vào logic xác thực. Bonus: nút “Authorize” trên Swagger UI (/docs) tự động hoạt động nhờ khai báo OAuth2PasswordBearer.

Áp dụng vào dự án của bạn

Đừng hardcode SECRET_KEY trong code — đọc từ biến môi trường (os.environ[“SECRET_KEY”]) và sinh bằng secrets.token_hex(32). Trong dự án thật, thay fake_users_db bằng hàm truy vấn database và tách get_current_user ra file dependencies.py để mọi router đều import được. Cần phân quyền admin? Viết thêm dependency get_current_active_user hoặc kiểm tra user[“role”] ngay trong get_current_user, không bao giờ kiểm tra role rải rác trong từng endpoint.

Bài viết liên quan

Câu hỏi thường gặp

OAuth2PasswordBearer có tự kiểm tra token thật hay giả không?

Không. Nó chỉ trích chuỗi token từ header Authorization. Việc decode, kiểm tra chữ ký và hạn dùng là trách nhiệm của bạn trong get_current_user (đoạn jwt.decode ở trên).

Nên lưu SECRET_KEY ở đâu cho an toàn?

Trong biến môi trường hoặc file .env (dùng python-dotenv), tuyệt đối không commit vào git. Key bị lộ thì ai cũng tự ký được token hợp lệ.

Token hết hạn thì client phải làm gì?

Đăng nhập lại qua /token để lấy token mới. Nếu muốn trải nghiệm mượt hơn, triển khai thêm refresh token (token dài hạn chỉ dùng để đổi access token mới) — đó là bước nâng cao tiếp theo.

Muốn route chỉ admin mới vào được thì làm thế nào?

Tạo dependency con, ví dụ get_current_admin_user, gọi get_current_user bên trong rồi kiểm tra user[“role”] == “admin”. Giữ mọi logic phân quyền trong dependencies, endpoint chỉ khai báo.

Code này có chạy được trên Python 3.10+ không?

Có. Cú pháp str | None yêu cầu Python 3.10 trở lên; nếu dùng 3.8/3.9, thay bằng Optional[str] từ typing.

Nguồn tham khảo