Gerar token de acesso JWT
POST /api/auth/token
POST https://api.avista.global/api/auth/tokenAutentique usando certificado de cliente X.509 + credenciais OAuth 2.0 (clientId/clientSecret) e receba um token JWT válido por 30 minutos (1800 segundos).
Headers
| Header | Tipo | Obrigatório | Descrição |
|---|---|---|---|
X-SSL-Client-Cert | string | Sim | Certificado PEM do cliente codificado em URL (header padrão do NGINX) |
Request Body
| Campo | Tipo | Obrigatório | Descrição |
|---|---|---|---|
clientId | string | Sim | OAuth 2.0 client ID obtido da criação de credencial |
clientSecret | string | Sim | OAuth 2.0 client secret (8-64 caracteres) |
{
"clientId": "account-93-550e8400",
"clientSecret": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6"
}Exemplo com 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"
}'Exemplos 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());Erro Comum — Codificação URL do Certificado
O certificado deve ser codificado usando percent-encoding (RFC 3986), não application/x-www-form-urlencoded.
| Linguagem | Função Correta | Função Incorreta |
|---|---|---|
| JavaScript | encodeURIComponent(cert) | — |
| Python | urllib.parse.quote(cert) | — |
| PHP | rawurlencode($cert) | urlencode($cert) (codifica espaços como +) |
| Java | URLEncoder.encode(cert, UTF_8).replace("+", "%20") | URLEncoder.encode(cert, UTF_8) sozinho (espaços viram +) |
Se você receber "Invalid client certificate format. Expected PEM-encoded X.509 certificate.", sua função de encoding provavelmente está usando + para espaços ao invés de %20.
Response (201)
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "Bearer",
"expires_in": 1800
}Erros
| Status | Descrição |
|---|---|
| 400 | Requisição inválida ou certificado ausente no header X-SSL-Client-Cert |
| 401 | Credenciais inválidas ou certificado inválido |
Para um guia completo de autenticação com padrões de renovação de token, veja Guia de Autenticação.
O certificado X.509 deve ser enviado URL-encoded no header X-SSL-Client-Cert. O certificado deve estar previamente vinculado a sua conta.