Auth

ApiKeyAuthStrategy

Autenticazione tramite API key in header HTTP. Adatta a sviluppo, test e comunicazione M2M leggera.

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)
Non usare ApiKey in applicazioni client-facing in produzione. La chiave finisce nel bundle JavaScript pubblico ed e facilmente estraibile. Preferire 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

ParametroTipoDefaultDescrizione
apiKeystringAPI key da inviare al server. Stringa non vuota
headerNamestring'x-api-key'Nome dell'header HTTP che trasporta la chiave

Comportamento

  • applyAuth(config) — aggiunge l'header {[headerName]: apiKey}. Se apiKey e vuota, ritorna config invariata
  • isAuthenticated()true se la chiave ha lunghezza > 0
  • saveCredentials(authResponse) — se un endpoint emette dinamicamente una nuova chiave, viene accettata come nuova apiKey
  • clearCredentials() — svuota la chiave (apiKey = '')
  • getToken() — ritorna la chiave o null
  • getRefreshToken() — sempre null
  • supportsRefresh() — sempre false

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