API Key 驗證

使用 FastAPI 將 AI 佈署到生產環境

Matt Eckerle

Software and Data Engineering Leader

為什麼要保護 API?

 

 

  • 阻擋未授權使用者
  • 以 API key 驗證保護 API 端點

安全保險庫

使用 FastAPI 將 AI 佈署到生產環境

API key 的運作方式

 

  • 就像 API 的數位密碼
  • 透過請求標頭傳送
  • 存取端點前先驗證

說明 API key 如何運作的流程圖

使用 FastAPI 將 AI 佈署到生產環境

理解 APIKeyHeader

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

name="X-API-Key",
auto_error=True
)
使用 FastAPI 將 AI 佈署到生產環境

端點驗證

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 加入標頭方案
  • 使用 HTTPException 拋出例外
  • 定義 API key 標頭與金鑰
  • test_api_key 驗證 API key
  • 若與 API_SECRET_KEY 不符則拋出 403
使用 FastAPI 將 AI 佈署到生產環境

整個應用程式驗證

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" }
使用 FastAPI 將 AI 佈署到生產環境

測試端點

無效 API key 的指令:

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

有效 API key 的指令:

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!"}'

無效金鑰輸出:

{"detail":"Invalid API key"}

 

 

有效金鑰輸出:

{"text":"This product is amazing!",
 "sentiment":"positive",
 "status":"success"}
使用 FastAPI 將 AI 佈署到生產環境

一起來練習吧!

使用 FastAPI 將 AI 佈署到生產環境

Preparing Video For Download...