Autenticazione con API key

Deployment di AI in produzione con FastAPI

Matt Eckerle

Software and Data Engineering Leader

Perché proteggere le API?

 

 

  • Blocca gli utenti non autorizzati
  • Proteggi gli endpoint con l'autenticazione tramite API key

Un caveau sicuro

Deployment di AI in produzione con FastAPI

Come funzionano le API key

 

  • Come una password digitale per la nostra API
  • Inviata negli header della richiesta
  • Verificata prima di accedere agli endpoint

Diagramma di flusso che spiega come funzionano le API key

Deployment di AI in produzione con FastAPI

Capire APIKeyHeader

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

name="X-API-Key",
auto_error=True
)
Deployment di AI in produzione con FastAPI

Autenticare un 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 aggiunge lo schema header
  • HTTPException per le eccezioni
  • Definisce l'header dell'API key e la chiave segreta
  • Valida le API key con test_api_key
  • Genera 403 se la chiave non coincide con API_SECRET_KEY
Deployment di AI in produzione con FastAPI

Autenticare un'app

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" }
Deployment di AI in produzione con FastAPI

Testare l'endpoint

Comando con API key non valida:

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

Comando con API key valida:

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

Output con chiave non valida:

{"detail":"Invalid API key"}

 

 

Output con chiave valida:

{"text":"This product is amazing!",
 "sentiment":"positive",
 "status":"success"}
Deployment di AI in produzione con FastAPI

Esercitiamoci!

Deployment di AI in produzione con FastAPI

Preparing Video For Download...