Xác thực bằng API Key

Triển khai AI vào môi trường sản xuất với FastAPI

Matt Eckerle

Software and Data Engineering Leader

Vì sao phải bảo mật API?

 

 

  • Chặn người dùng trái phép
  • Bảo vệ endpoint bằng xác thực API key

Một két bảo mật

Triển khai AI vào môi trường sản xuất với FastAPI

API key hoạt động thế nào

 

  • Như một mật khẩu số cho API
  • Gửi trong request headers
  • Xác minh trước khi truy cập endpoint

Sơ đồ luồng giải thích cách API key hoạt động

Triển khai AI vào môi trường sản xuất với FastAPI

Tìm hiểu APIKeyHeader

from fastapi import FastAPI
from fastapi.security import APIKeyHeader
header_scheme = APIKeyHeader(

name="X-API-Key",
auto_error=True
)
Triển khai AI vào môi trường sản xuất với FastAPI

Xác thực một endpoint

from fastapi.security import APIKeyHeader
from fastapi import Depends, HTTPException


header_scheme = APIKeyHeader(name="X-API-Key", auto_error=True) API_SECRET_KEY = "your-secret-key"
@app.get("/items/") def read_items( api_key: str = Depends(header_scheme) ):
if api_key != API_SECRET_KEY: raise HTTPException( status_code=403, detail="Invalid API key")
return {"api_key": api_key}
  • ApiKeyHeader
  • Depends thêm header scheme
  • HTTPException để ném ngoại lệ
  • Định nghĩa header API key và secret key
  • Xác thực API key với test_api_key
  • Ném 403 nếu key không khớp API_SECRET_KEY
Triển khai AI vào môi trường sản xuất với FastAPI

Xác thực toàn bộ ứng dụng

def verify_api_key(api_key: str = Depends(header_scheme)):
    if api_key != API_KEY:
        raise HTTPException(status_code=403,  detail="Invalid API key")
    return api_key

app = FastAPI( dependencies=[Depends(verify_api_key)] )
@app.post("/predict") def predict_sentiment(text: str):
return { "text": text, "sentiment": "positive", "status": "success" }
Triển khai AI vào môi trường sản xuất với FastAPI

Kiểm thử endpoint

Lệnh với API key không hợp lệ:

curl -X POST \
  http://localhost:8000/predict \
  -H "X-API-Key: wrong-key" \
  -H "Content-Type: application/json" \
  -d '{"text": "This product is amazing!"}'

Lệnh với API key hợp lệ:

curl -X POST \
  http://localhost:8000/predict \
  -H "X-API-Key: your-secret-key" \
  -H "Content-Type: application/json" \
  -d '{"text": "This product is amazing!"}'

Đầu ra khi key sai:

{"detail":"Invalid API key"}

 

 

Đầu ra khi key đúng:

{"text":"This product is amazing!",
 "sentiment":"positive",
 "status":"success"}
Triển khai AI vào môi trường sản xuất với FastAPI

Cùng luyện tập nào!

Triển khai AI vào môi trường sản xuất với FastAPI

Preparing Video For Download...