Avistadocs

Generar token de acceso JWT

POST /api/auth/token

POST https://api.avista.global/api/auth/token

Autenticarse utilizando un certificado de cliente X.509 + credenciales OAuth 2.0 (clientId/clientSecret) y recibir un token JWT válido por 30 minutos (1800 segundos).

Headers

HeaderTipoRequeridoDescripción
X-SSL-Client-CertstringCertificado PEM del cliente codificado en URL (header estándar de NGINX)

Cuerpo de la solicitud

CampoTipoRequeridoDescripción
clientIdstringClient ID de OAuth 2.0 obtenido en la creación de credenciales
clientSecretstringClient secret de OAuth 2.0 (8-64 caracteres)
{
  "clientId": "account-93-550e8400",
  "clientSecret": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6"
}

Ejemplo con Curl

curl -X POST https://api.avista.global/api/auth/token \
  -H "Content-Type: application/json" \
  -H "X-SSL-Client-Cert: $(cat ./client-cert.pem | python3 -c 'import sys,urllib.parse; print(urllib.parse.quote(sys.stdin.read()))')" \
  -d '{
    "clientId": "YOUR_CLIENT_ID",
    "clientSecret": "YOUR_CLIENT_SECRET"
  }'

Ejemplos de Código

const axios = require('axios');
const fs = require('fs');

const certificate = fs.readFileSync('./client-cert.pem', 'utf8');
const encodedCert = encodeURIComponent(certificate);

const response = await axios.post('https://api.avista.global/api/auth/token', {
  clientId: process.env.AVISTA_CLIENT_ID,
  clientSecret: process.env.AVISTA_CLIENT_SECRET,
}, {
  headers: {
    'Content-Type': 'application/json',
    'X-SSL-Client-Cert': encodedCert,
  },
});

console.log('Token:', response.data.access_token);
console.log('Expires in:', response.data.expires_in, 'seconds');
import os
import requests
import urllib.parse

with open('client-cert.pem', 'r') as f:
    certificate = f.read()
    encoded_cert = urllib.parse.quote(certificate)

response = requests.post(
    'https://api.avista.global/api/auth/token',
    json={
        'clientId': os.environ['AVISTA_CLIENT_ID'],
        'clientSecret': os.environ['AVISTA_CLIENT_SECRET'],
    },
    headers={
        'Content-Type': 'application/json',
        'X-SSL-Client-Cert': encoded_cert,
    },
)

data = response.json()
print(f"Token: {data['access_token']}")
print(f"Expires in: {data['expires_in']} seconds")
<?php
$certificate = file_get_contents('./client-cert.pem');
$encodedCert = rawurlencode($certificate);

$ch = curl_init('https://api.avista.global/api/auth/token');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'X-SSL-Client-Cert: ' . $encodedCert,
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'clientId' => getenv('AVISTA_CLIENT_ID'),
        'clientSecret' => getenv('AVISTA_CLIENT_SECRET'),
    ]),
]);

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

$data = json_decode($response, true);
echo "Token: " . $data['access_token'] . "\n";
echo "Expires in: " . $data['expires_in'] . " seconds\n";
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

String certificate = Files.readString(Path.of("client-cert.pem"));
// IMPORTANT: Use URLEncoder.encode + replace "+" with "%20"
// Java's URLEncoder uses application/x-www-form-urlencoded (spaces as +)
// The API expects RFC 3986 percent-encoding (spaces as %20)
String encodedCert = URLEncoder.encode(certificate, StandardCharsets.UTF_8)
    .replace("+", "%20");

String body = String.format(
    "{\"clientId\":\"%s\",\"clientSecret\":\"%s\"}",
    System.getenv("AVISTA_CLIENT_ID"),
    System.getenv("AVISTA_CLIENT_SECRET")
);

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.avista.global/api/auth/token"))
    .header("Content-Type", "application/json")
    .header("X-SSL-Client-Cert", encodedCert)
    .POST(HttpRequest.BodyPublishers.ofString(body))
    .build();

HttpResponse<String> response = HttpClient.newHttpClient()
    .send(request, HttpResponse.BodyHandlers.ofString());

System.out.println("Response: " + response.body());

Error Común — Codificación URL del Certificado

El certificado debe codificarse usando percent-encoding (RFC 3986), no application/x-www-form-urlencoded.

LenguajeFunción CorrectaFunción Incorrecta
JavaScriptencodeURIComponent(cert)
Pythonurllib.parse.quote(cert)
PHPrawurlencode($cert)urlencode($cert) (codifica espacios como +)
JavaURLEncoder.encode(cert, UTF_8).replace("+", "%20")URLEncoder.encode(cert, UTF_8) solo (espacios se vuelven +)

Si recibe "Invalid client certificate format. Expected PEM-encoded X.509 certificate.", su función de encoding probablemente esté usando + para espacios en vez de %20.

Respuesta (201)

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 1800
}

Errores

EstadoDescripción
400Solicitud inválida o certificado faltante en el header X-SSL-Client-Cert
401Credenciales inválidas o certificado inválido

Para una guía completa de autenticación con patrones de renovación de token, vea Guía de Autenticación.

El certificado X.509 debe enviarse codificado en URL en el header X-SSL-Client-Cert. El certificado debe estar previamente vinculado a su cuenta.

En esta página