ApiKeyAuthStrategy
Cosa fa
ApiKeyAuthStrategy inserisce un header HTTP (default x-api-key) con il valore della chiave su ogni request. La chiave e un segreto a lungo termine: la libreria non persiste nulla autonomamente, la chiave e tenuta in memoria nell'istanza della strategy.
Non supporta refresh — supportsRefresh() ritorna false. Il client HTTP non tentera il refresh dopo un 401: l'errore va gestito dall'applicazione.
Quando usarla
- Sviluppo e test — chiave letta da
process.env - Comunicazione M2M leggera tra microservizi interni (BFF → service)
- SDK e CLI admin con chiave provisioned out-of-band (admin panel)
JwtAuthStrategy o CookieAuthStrategy per traffico utente. Per servizi backend, abbinare la chiave a IP allowlist, rate limit e rotazione periodica.Costruttore
class ApiKeyAuthStrategy implements IAuthStrategy {
constructor(config: ApiKeyAuthConfig)
}
ApiKeyAuthConfig
| Parametro | Tipo | Default | Descrizione |
|---|---|---|---|
apiKey | string | — | API key da inviare al server. Stringa non vuota |
headerName | string | 'x-api-key' | Nome dell'header HTTP che trasporta la chiave |
Comportamento
applyAuth(config)— aggiunge l'header{[headerName]: apiKey}. SeapiKeye vuota, ritornaconfiginvariataisAuthenticated()—truese la chiave ha lunghezza> 0saveCredentials(authResponse)— se un endpoint emette dinamicamente una nuova chiave, viene accettata come nuovaapiKeyclearCredentials()— svuota la chiave (apiKey = '')getToken()— ritorna la chiave onullgetRefreshToken()— semprenullsupportsRefresh()— semprefalse
Esempio
Da variabile d'ambiente
import {
ApiKeyAuthStrategy,
HttpClientFactory,
} from '@pzeta/postgrest'
const strategy = new ApiKeyAuthStrategy({
apiKey: process.env.SERVICE_API_KEY ?? '',
headerName: 'x-api-key',
})
const httpClient = HttpClientFactory.createFetchClient({ baseURL: '/api' })
httpClient.setAuthStrategy(strategy)
const response = await httpClient.get('/anagrafica')
// Header: x-api-key: <SERVICE_API_KEY>
Via factory
import { AuthStrategyFactory } from '@pzeta/postgrest'
const strategy = AuthStrategyFactory.createApiKeyStrategy({
apiKey: process.env.API_KEY ?? '',
})
Header custom
const strategy = new ApiKeyAuthStrategy({
apiKey: 'sk_live_...',
headerName: 'Authorization', // es. backend che si aspetta Authorization: <key>
})
Vedi anche
AuthStrategyFactory—createApiKeyStrategy(config)JwtAuthStrategy— alternativa con refresh tokenPostgRESTClient
Auth
Autenticazione multi-strategia per @pzeta/postgrest. Supporta JWT Bearer, Cookie HTTP-only, API Key e NoAuth con interfaccia comune IAuthStrategy.
AuthService
Servizio di autenticazione completo. Login, logout, register, activate, forgotPassword, resetPassword, refresh con locking concorrente. Implementa anche IAuthHandler per retry automatico su 401.