Trung BìnhFastAPI iconFastAPI

CORS trong FastAPI cần cấu hình ra sao?

CORS được cấu hình bằng CORSMiddleware. Không nên dùng wildcard origin cùng credentials trong production; hãy whitelist domain cụ thể theo môi trường.

Ví dụ:

python
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com"],
    allow_credentials=True,
    allow_methods=["GET", "POST", "PATCH", "DELETE"],
    allow_headers=["Authorization", "Content-Type"],
)

CORS chỉ là chính sách browser, không phải security boundary cho API.

Backend vẫn phải authenticate và authorize request.

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

Mở danh sách FastAPI