Quando devi collegare servizi diversi o API proprietarie, l’autenticazione fa la differenza tra un workflow che “va quando vuole” e uno affidabile. In questa guida pratica scoprirai come progettare l’autenticazione http request n8n in modo flessibile e sicuro: differenze tra credenziali predefinite e credenziali generiche n8n e custom auth, dove impostare header Authorization e API key in n8n, come firmare richieste con HMAC, gestire token bearer dinamici e refresh OAuth2 in automazioni, configurare querystring di autenticazione non standard e usare variabili ed espressioni n8n per headers e query. Vedrai JSON pronti all’uso del nodo HTTP Request, strategie di debug 401/403 e suggerimenti su mTLS e certificati SSL nel nodo HTTP Request. Il risultato: ricette operative, riutilizzabili e sicure, che riducono errori e tempi di integrazione.

📚 Nuovo a n8n? Parti dalla guida completa: cos'è n8n e come funziona.

[IMG: panoramica di un workflow con nodi Code → HTTP Request → controllo esito]

Predefinite vs Custom: come scegliere l’autenticazione giusta

In n8n, il nodo “n8n-nodes-base.httpRequest” supporta due strade:

  • Credenziali predefinite (salvate nel vault e referenziate dal nodo): ottime per Basic, Bearer, OAuth. Riduci l’esposizione dei segreti, faciliti riuso e rotazione.
  • Autenticazione personalizzata per il nodo HTTP Request di n8n (custom headers/query/body definiti nel nodo): perfetta per API proprietarie o schemi non standard.

Campi chiave del nodo HTTP Request:

  • parameters.url, parameters.method, parameters.responseFormat
  • parameters.jsonParameters (true per inviare il body in JSON)
  • parameters.queryParametersUi.parameter per querystring
  • parameters.headerParametersUi.parameter per headers
  • parameters.bodyParametersJson (quando jsonParameters è true)
  • options.bodyContentType, options.timeout, options.redirect, options.lowercaseHeaders, options.ignoreSSLIssues
  • credentials (blocco che referenzia credenziali predefinite, es. httpBasicAuth)

Esempio GET con query e credenziali predefinite (Basic):

{
  "name": "HTTP GET Example",
  "type": "n8n-nodes-base.httpRequest",
  "typeVersion": 1,
  "parameters": {
    "url": "https://api.example.com/data",
    "method": "GET",
    "responseFormat": "json",
    "queryParametersUi": {
      "parameter": [
        { "name": "q", "value": "newsletter" },
        { "name": "limit", "value": "10" }
      ]
    }
  },
  "credentials": {
    "httpBasicAuth": { "name": "Example API Auth" }
  }
}

Pro tip: preferisci credenziali predefinite per sicurezza dei segreti e permessi credenziali n8n granulari; usa custom auth quando l’API richiede header o payload speciali fuori dagli schemi.

[IMG: configurazione visuale del nodo con queryParametersUi e credentials]

Header e Query personalizzati: API key e token nei posti giusti

Molte API richiedono header Authorization e API key in n8n o token in query. Ecco i pattern più comuni.

Header Bearer:

{
  "name": "GraphQL Query",
  "type": "n8n-nodes-base.httpRequest",
  "typeVersion": 1,
  "parameters": {
    "url": "https://api.example.com/graphql",
    "method": "POST",
    "responseFormat": "json",
    "jsonParameters": true,
    "bodyParametersJson": {
      "query": "query { posts(limit: 3) { id title } }",
      "variables": "{}"
    },
    "headerParametersUi": {
      "parameter": [
        { "name": "Authorization", "value": "Bearer {{$env.API_TOKEN}}" }
      ]
    }
  }
}

API key in querystring:

{
  "name": "GET with API Key QS",
  "type": "n8n-nodes-base.httpRequest",
  "typeVersion": 1,
  "parameters": {
    "url": "https://api.example.com/search",
    "method": "GET",
    "responseFormat": "json",
    "queryParametersUi": {
      "parameter": [
        { "name": "api_key", "value": "{{$env.API_KEY}}" },
        { "name": "q", "value": "landingpage" }
      ]
    }
  }
}

Body‑based auth (token nel body JSON):

{
  "name": "POST with Token in Body",
  "type": "n8n-nodes-base.httpRequest",
  "typeVersion": 1,
  "parameters": {
    "url": "https://api.example.com/secure-endpoint",
    "method": "POST",
    "responseFormat": "json",
    "jsonParameters": true,
    "bodyParametersJson": {
      "token": "{{$env.INTERNAL_TOKEN}}",
      "payload": { "action": "sync" }
    },
    "options": { "bodyContentType": "JSON" }
  }
}

Consiglio: centralizza i segreti con variabili ed espressioni n8n per headers e query (es. $env) o referenzia credenziali predefinite. Evita di inserire token “in chiaro” nel bodyParametersJson.

[IMG: node editor con headerParametersUi e queryParametersUi popolati]

Firma HMAC per richieste API: costruire header deterministici

Alcune API proprietarie richiedono firma HMAC su metodo, percorso, timestamp, body. Genera la firma in un Code Node e inseriscila nell’HTTP Request.

Step 1 — Code Node: calcolo HMAC

// Inputs: secret in $env.HMAC_SECRET, path in $json.path, body in $json.body
const crypto = require('crypto');
const method = 'POST';
const timestamp = Math.floor(Date.now()/1000).toString();
const path = $json.path; // es. "/v1/orders"
const body = JSON.stringify($json.body || {});
const payload = [method, path, timestamp, body].join('\n');
const signature = crypto.createHmac('sha256', $env.HMAC_SECRET).update(payload).digest('hex');

return [{ json: { timestamp, signature, body: JSON.parse(body) } }];

Step 2 — HTTP Request con header firmati

{
  "name": "Signed Request",
  "type": "n8n-nodes-base.httpRequest",
  "typeVersion": 1,
  "parameters": {
    "url": "https://api.example.com/v1/orders",
    "method": "POST",
    "responseFormat": "json",
    "jsonParameters": true,
    "bodyParametersJson": "={{ $json[\"body\"] }}",
    "headerParametersUi": {
      "parameter": [
        { "name": "X-Auth-Timestamp", "value": "={{$json[\"timestamp\"]}}" },
        { "name": "X-Auth-Signature", "value": "={{$json[\"signature\"]}}" }
      ]
    },
    "options": { "bodyContentType": "JSON" }
  }
}

Perché funziona: sposti la complessità nel Code Node, ottieni header riproducibili e puoi loggare i soli metadati (non i segreti). Questo pattern copre firma HMAC per richieste API senza “sporcare” il resto del flusso.

[IMG: Code Node → HTTP Request con header firmati e risposta OK]

Token Bearer dinamico e refresh: orchestrazione robusta

Quando il token scade, il flusso deve rigenerarlo e riprovare. Usa un sub‑workflow di “token refresh” e cattura i 401/403.

Esempio — richiesta principale con Bearer dinamico:

{
  "name": "Main API Call",
  "type": "n8n-nodes-base.httpRequest",
  "typeVersion": 1,
  "parameters": {
    "url": "https://api.example.com/resources",
    "method": "GET",
    "responseFormat": "json",
    "headerParametersUi": {
      "parameter": [
        { "name": "Authorization", "value": "Bearer {{$json[\"access_token\"]}}" }
      ]
    },
    "options": {
      "timeout": 120000,
      "redirect": { "followRedirects": true },
      "lowercaseHeaders": true
    }
  }
}

Se ricevi 401/403:
1) Esegui un sub‑workflow “Refresh Token” che chiama l’endpoint OAuth2 del provider:

{
  "name": "OAuth2 Refresh",
  "type": "n8n-nodes-base.httpRequest",
  "typeVersion": 1,
  "parameters": {
    "url": "https://auth.example.com/oauth/token",
    "method": "POST",
    "responseFormat": "json",
    "jsonParameters": true,
    "bodyParametersJson": {
      "grant_type": "refresh_token",
      "client_id": "{{$env.CLIENT_ID}}",
      "client_secret": "{{$env.CLIENT_SECRET}}",
      "refresh_token": "={{$json[\"refresh_token\"]}}"
    },
    "options": { "bodyContentType": "JSON" }
  }
}

2) Aggiorna l’access_token nel contesto del workflow e ripeti la chiamata principale.

Questo pattern gestisce token bearer dinamico in workflow n8n senza interrompere l’esperienza utente, ed è compatibile con gestione refresh token OAuth2 in automazioni.

[IMG: flusso con IF su status 401 → Execute Workflow (Refresh) → retry]

Custom Auth nel body, query e header: ricette riutilizzabili

Molte API “legacy” usano schemi non standard. Ecco tre ricette:

  • Querystring di autenticazione non standard
{
  "name": "Legacy QS Auth",
  "type": "n8n-nodes-base.httpRequest",
  "typeVersion": 1,
  "parameters": {
    "url": "https://legacy.example.com/data",
    "method": "GET",
    "responseFormat": "json",
    "queryParametersUi": {
      "parameter": [
        { "name": "user", "value": "{{$env.API_USER}}" },
        { "name": "token", "value": "{{$env.API_TOKEN}}" }
      ]
    }
  }
}
  • Header custom multipli
{
  "name": "Custom Headers Auth",
  "type": "n8n-nodes-base.httpRequest",
  "typeVersion": 1,
  "parameters": {
    "url": "https://api.partner.com/ingest",
    "method": "POST",
    "responseFormat": "json",
    "jsonParameters": true,
    "bodyParametersJson": { "batchId": "={{$json[\"batchId\"]}}", "items": "={{$json[\"items\"]}}" },
    "headerParametersUi": {
      "parameter": [
        { "name": "X-Partner-Id", "value": "{{$env.PARTNER_ID}}" },
        { "name": "X-Partner-Token", "value": "{{$env.PARTNER_TOKEN}}" }
      ]
    },
    "options": { "bodyContentType": "JSON" }
  }
}
  • Body auth + payload
{
  "name": "Body Auth + Action",
  "type": "n8n-nodes-base.httpRequest",
  "typeVersion": 1,
  "parameters": {
    "url": "https://svc.example.com/action",
    "method": "POST",
    "responseFormat": "json",
    "jsonParameters": true,
    "bodyParametersJson": {
      "auth": { "user": "{{$env.USER}}", "key": "{{$env.KEY}}" },
      "data": "={{$json[\"payload\"]}}"
    },
    "options": { "bodyContentType": "JSON" }
  }
}

Queste ricette ti permettono di standardizzare pattern diversi con un unico approccio, mantenendo i segreti fuori dal workflow tramite $env.

[IMG: tre nodi HTTP con varianti di auth evidenziate]

mTLS, SSL e sicurezza: quando e come abilitarli

Alcune integrazioni richiedono mTLS o certificati custom:

  • Carica CA/CRT/KEY e, se richiesto, passphrase nelle credenziali predisposte al trasporto sicuro e referenzialele nel nodo HTTP Request.
  • options.ignoreSSLIssues può aiutare in ambienti di test, ma evitalo in produzione.
  • Mantieni i certificati fuori dal workflow e limita l’accesso con permessi sulle credenziali.

Suggerimento: separa ambienti (staging/prod) e usa set di credenziali differenti per CA/CRT/KEY, monitorando le scadenze. Questo riduce interruzioni impreviste e migliora la postura di sicurezza dei segreti e permessi credenziali n8n.

[IMG: credenziali con certificati caricati e scadenze annotate]

Debug 401/403 e problemi comuni: una checklist rapida

Quando l’API risponde con 401/403:

  • Verifica il formato dell’Authorization (Bearer o header custom), e attiva options.lowercaseHeaders per normalizzati in ingresso/uscita se il target è sensibile alla capitalizzazione.
  • Controlla scadenza del token; se dinamico, esegui il sub‑workflow di refresh e ripeti.
  • Esamina reindirizzamenti con options.redirect.followRedirects e prova a forzare o disattivare il follow in caso di catene strane.
  • Aumenta options.timeout per API lente; evita retry ciechi su 4xx non transitori.
  • Logga responseFormat: “json” e conserva status/headers per analisi (via nodi Set/Code).

Esempio minimale di nodo con opzioni di debug:

{
  "name": "Debuggable Call",
  "type": "n8n-nodes-base.httpRequest",
  "typeVersion": 1,
  "parameters": {
    "url": "https://api.example.com/check",
    "method": "GET",
    "responseFormat": "json",
    "headerParametersUi": {
      "parameter": [
        { "name": "Authorization", "value": "Bearer {{$json[\"access_token\"]}}" }
      ]
    },
    "options": {
      "timeout": 90000,
      "redirect": { "followRedirects": true },
      "lowercaseHeaders": true
    }
  }
}

[IMG: If branch su statusCode per gestire 401/403 con retry o alert]

Strategia di test e hardening: staging, logging controllato, riuso

Per ridurre il tempo di diagnosi:

  • Usa ambienti di staging per autenticazioni complesse; replica i flussi con dati sintetici.
  • Esporta/importa workflow JSON per versionare le configurazioni del nodo HTTP Request.
  • Minimizza il logging dei segreti: logga solo metadati (timestamp, endpoint, esito), non token.
  • Documenta i pattern ricorrenti (HMAC, query auth, bearer refresh) in sub‑workflow riutilizzabili.

Insight: crea un “catalogo” interno di ricette di autenticazione con esempi JSON e campi commentati. Nuovi membri del team accelerano l’onboarding e riduci errori in produzione.

[IMG: elenco di sub‑workflow “Auth Patterns” riutilizzabili]

Esempio end‑to‑end: validazione numeri + enrich profilo con API proprietaria

Obiettivo: validare un numero di telefono e arricchire il profilo cliente usando due servizi con autenticazioni diverse (Bearer e HMAC).

1) Preparazione input

  • Set: normalizza numero e genera correlationId

2) Validazione (Bearer in header)

{
  "name": "Phone Validation",
  "type": "n8n-nodes-base.httpRequest",
  "typeVersion": 1,
  "parameters": {
    "url": "https://api.validator.com/phones/check",
    "method": "GET",
    "responseFormat": "json",
    "queryParametersUi": {
      "parameter": [
        { "name": "phone", "value": "={{$json[\"phone\"]}}" }
      ]
    },
    "headerParametersUi": {
      "parameter": [
        { "name": "Authorization", "value": "Bearer {{$env.VALIDATOR_TOKEN}}" }
      ]
    }
  }
}

3) Firma HMAC (Code → HTTP Request)

  • Code: genera X-Auth-Signature e X-Auth-Timestamp sul payload “profile enrich”
  • HTTP Request: POST verso https://api.partner.com/enrich con header custom firmati (vedi sezione HMAC)

4) Gestione errori

  • If su status 401/403 → sub‑workflow refresh o alert
  • Log sintetico (endpoint, durata, esito) con correlationId

Risultato: un flusso stabile, sicuro e osservabile, pronto per essere schedulato o richiamato via webhook.

[IMG: canvas con Set → Phone Validation → Code (HMAC) → Enrich → If error → Notifica]

Quick Takeaways

  • Preferisci credenziali predefinite per sicurezza e riuso; usa custom auth in header/query/body per API non standard.
  • Il nodo HTTP Request espone headerParametersUi, queryParametersUi, bodyParametersJson e options: comporli bene evita 401/403.
  • HMAC: calcola la firma in un Code Node e inseriscila come header; è riproducibile e auditabile.
  • Token bearer dinamico: usa sub‑workflow di refresh e ritenta solo quando serve; logga esiti e latenza.
  • mTLS/SSL: carica certificati nelle credenziali, evita ignoreSSLIssues in produzione.
  • Debug: controlla timeout, redirect e lowercaseHeaders; conserva metadati, non segreti.
  • Versiona i pattern (HMAC, QS, Bearer) come sub‑workflow riutilizzabili per accelerare i rilasci.

Conclusione

Progettare l’autenticazione http request n8n con un approccio modulare ti permette di integrare API standard e proprietarie senza compromessi su sicurezza e affidabilità. Le credenziali predefinite semplificano la governance dei segreti; l’autenticazione personalizzata per il nodo HTTP Request di n8n ti dà la flessibilità per header, query e body fuori standard. Con ricette come HMAC via Code Node, gestione del token bearer dinamico e refresh, opzioni di robustezza (timeout, redirect, lowercaseHeaders) e buone pratiche di logging (niente segreti, sì a metadati) porti in produzione flussi che reggono ai picchi e agli imprevisti. Per i marketers che vogliono imparare ad usare n8n per migliorare la produttività, questo significa meno tempo perso su errori 401/403 e più focus su risultati: lead puliti, profili arricchiti, report aggiornati. Parti da un pattern, trasformalo in sub‑workflow riutilizzabile e scala serenamente verso integrazioni sempre più ricche.

FAQ

  • Posso combinare credenziali predefinite e header personalizzati?

  • Sì. Usa credenziali predefinite per l’autorizzazione principale e headerParametersUi per header aggiuntivi richiesti dall’API.

  • Come implemento una firma HMAC senza esporre il segreto?

  • Calcola la firma in un Code Node usando $env per il segreto e invia l’header al nodo HTTP Request. Logga solo timestamp e hash, non il segreto.

  • Come gestire un token bearer scaduto in modo automatico?

  • Cattura 401/403, invoca un sub‑workflow di refresh token (HTTP POST verso l’endpoint OAuth2), aggiorna l’access_token e ritenta la chiamata.

  • Come testare API con autenticazione complessa senza sporcare i log?

  • Usa ambienti di staging, limita il logging a metadati (status, durata, endpoint) e riferimenti anonimi. Versiona i workflow JSON per riprodurre facilmente i test.

  • Quando usare mTLS e come configurarlo?

  • Se il provider richiede mTLS, carica CA/CRT/KEY e passphrase nelle credenziali adatte e referenzialele nel nodo HTTP Request. Evita ignoreSSLIssues in produzione.

Hai uno schema di autenticazione “strano” che vuoi automatizzare? Raccontalo nei commenti e condividi questa guida con il tuo team: quale integrazione ti farebbe risparmiare più tempo questa settimana?

Vuoi automazioni AI su misura per la tua azienda?
Scopri la consulenza →