Vai al contenuto

Autenticazione

L'API SMSBAT ChatHub utilizza un sistema di autenticazione basato su token JWT a due livelli con token aziendali e token operatore.

Flusso di autenticazione

graph TD
    A[Login Credentials] --> B[Get Company Token]
    B --> C[Use Company Token]
    C --> D[Get Operator Token]
    D --> E[Use Operator Token]
    E --> F[Validate Token]

Gettone aziendale

I token aziendali forniscono l'accesso a livello di organizzazione all'API ChatHub.

Ottieni token aziendale

Endpoint: POST /api/company/get-token

Richiesta:

curl -X POST https://chatapi.smsbat.com/api/company/get-token \
  -H "Content-Type: application/json" \
  -d '{
    "login": "your-company-login",
    "password": "your-company-password"
  }'

Corpo della richiesta:

CODICE_BLOCCO_2

Risposta:

"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"

La risposta è una stringa token JWT.

Utilizza il token aziendale

Includi il token aziendale nelle richieste API utilizzando uno dei due metodi:

Metodo 1: intestazione dell'autorizzazione (consigliato)

curl -X GET https://chatapi.smsbat.com/api/company/organization \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

Metodo 2: intestazione chiave di autorizzazione X

CODICE_BLOCCO_5

Gettone operatore

I token operatore forniscono un accesso specifico per l'utente per i singoli operatori all'interno di un'organizzazione.

Ottieni il token dell'operatore

Endpoint: POST /api/operator/get-token

Richiesta:

CODICE_BLOCCO_6

Corpo della richiesta:

CODICE_BLOCCO_7

Parametri:

Parametro Digitare Obbligatorio Descrizione
id intero ID operatore
scade a stringa (ISO 8601) Data e ora di scadenza del token (massimo 24 ore da adesso)

Importante: la durata massima del token è di 24 ore. Il parametro "expiresAt" non può essere superiore a 24 ore nel futuro.

Risposta:

"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvcGVyYXRvcl9pZCI6MTIzLCJleHAiOjE3Mzc0MTI3OTl9.example_signature"

Usa il token dell'operatore

Includi il token dell'operatore nelle richieste API:

curl -X GET https://chatapi.smsbat.com/api/operator \
  -H "Authorization: Bearer {operator-token}"

Convalida del token

Verificare che un token sia ancora valido prima di utilizzarlo.

Endpoint: POST /api/operator/validate-token

Richiesta:

curl -X POST https://chatapi.smsbat.com/api/operator/validate-token \
  -H "Authorization: Bearer {company-token}" \
  -H "Content-Type: application/json" \
  -d '{
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }'

Corpo della richiesta:

{
  "token": "string"
}

Risposta (token valido):

CODICE_BLOCCO_12

Risposta (token non valido):

{
  "isValid": false,
  "error": "Invalid token"
}

Scadenza del token

Gettoni azienda

  • Nessuna scadenza esplicita nell'API
  • Contatta il tuo account manager per le politiche sul ciclo di vita dei token
  • Ruota periodicamente i token per sicurezza

Gettoni operatore

  • Scadenza impostata alla richiesta del token (parametro expiresAt)
  • Convalidare i token prima dell'uso
  • Richiedi nuovi token prima della scadenza

Esempi di implementazione

Pitone

CODICE_BLOCCO_14

JavaScript (Node.js)

CODICE_BLOCCO_15

PHP

<?php

class ChatHubAuth {
    private $baseUrl;
    private $companyToken;
    private $operatorTokens = [];

    public function __construct($baseUrl) {
        $this->baseUrl = $baseUrl;
    }

    public function getCompanyToken($login, $password) {
        $ch = curl_init($this->baseUrl . '/api/company/get-token');

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
            'login' => $login,
            'password' => $password
        ]));

        $response = curl_exec($ch);
        curl_close($ch);

        $this->companyToken = json_decode($response);
        return $this->companyToken;
    }

    public function getOperatorToken($operatorId, $expiresDays = 30) {
        $expiresAt = date(
            'Y-m-d\TH:i:s\Z',
            time() + ($expiresDays * 24 * 60 * 60)
        );

        $ch = curl_init($this->baseUrl . '/api/operator/get-token');

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->companyToken
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
            'id' => $operatorId,
            'expiresAt' => $expiresAt
        ]));

        $response = curl_exec($ch);
        curl_close($ch);

        $token = json_decode($response);
        $this->operatorTokens[$operatorId] = $token;
        return $token;
    }

    public function validateToken($token) {
        $ch = curl_init($this->baseUrl . '/api/operator/validate-token');

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->companyToken
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
            'token' => $token
        ]));

        $response = curl_exec($ch);
        curl_close($ch);

        return json_decode($response, true);
    }
}

// Usage
$auth = new ChatHubAuth('https://chatapi.smsbat.com');

// Get company token
$companyToken = $auth->getCompanyToken('login', 'password');

// Get operator token
$operatorToken = $auth->getOperatorToken(123, 30);

// Validate token
$validation = $auth->validateToken($operatorToken);
echo "Token valid: " . ($validation['isValid'] ? 'Yes' : 'No');

Migliori pratiche

Archiviazione dei token

  • ✅ Conserva i token in modo sicuro (database crittografato, gestore dei segreti)
  • ✅ Non impegnare mai i token nel controllo della versione
  • ✅ Utilizza variabili di ambiente per le credenziali
  • ❌ Non conservare i token in testo semplice
  • ❌ Non esporre i token nel codice lato client

Rotazione dei gettoni

  • Ruota periodicamente i token aziendali (ogni 3-6 mesi)
  • Imposta una scadenza ragionevole per i token dell'operatore (7-30 giorni)
  • Implementare l'aggiornamento automatico dei token prima della scadenza
  • Revocare i token quando gli operatori se ne vanno

Gestione degli errori

CODICE_BLOCCO_17

Convalida del token

Convalida sempre i token prima delle operazioni critiche:

CODICE_BLOCCO_18

Considerazioni sulla sicurezza

Solo HTTPS

Utilizza sempre HTTPS quando invii richieste di autenticazione:

CODICE_BLOCCO_19

Ambito del token

Utilizza il token appropriato per ogni operazione:

  • Token aziendale: Gestione organizzazione, creazione operatori
  • Token operatore: operazioni di chat, gestione dei messaggi

Limitazione della velocità

Implementare la limitazione della velocità per le richieste di autenticazione:

CODICE_BLOCCO_20

Risoluzione dei problemi

401 Non autorizzato

  • Verificare che le credenziali siano corrette
  • Controlla che il token non sia scaduto
  • Assicurarsi che il token sia incluso nelle intestazioni della richiesta
  • Convalida il formato del token

403 Proibito

  • Verificare che il token disponga delle autorizzazioni richieste
  • Controlla se stai utilizzando il tipo di token corretto (azienda vs operatore)
  • Assicurati che il token non sia stato revocato

Gettone scaduto

  • Richiedi un nuovo token
  • Implementare l'aggiornamento automatico dei token
  • Impostare tempi di scadenza appropriati

Passaggi successivi