🔄 Flujo de Autenticación
El sistema usa un flujo de autenticación server-to-server para máxima seguridad:
Request Token
Tu backend o frontend solicita un JWT usando la clave pública del portal
POST /auth/token
{
"public_key": "pk_9fcfdd91a14755cc68d0e11a14269554"
}
Receive JWT
API responde con token firmado y metadatos
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
"expires_in": 3600,
"portal": {
"id": "lefebvre-sarrut",
"name": "Portal Lefebvre Sarrut",
"public_key": "lef_pub_abcdef1234567890..."
},
"policies": {
"format_policy": {
"default_format": "webp",
"allowed_output_formats": ["webp", "jpg", "png"]
},
"presets_aspect": [],
"presets_size": [],
"allow_arbitrary": true,
"cross_access_policy": "own"
}
}
Use Token
Incluye el JWT en las peticiones del frontend
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc...
🔑 Obtener Credenciales
Antes de comenzar, necesitas obtener tus credenciales de API:
Contactar Administrador
Solicita acceso al administrador del sistema proporcionando:
- Nombre de tu aplicación/proyecto
- Dominio(s) donde estará alojada
- Tipo de integración (galería, formularios, etc.)
- Volumen estimado de uso
Recibir Credenciales
El administrador te proporcionará:
- API Key:
ak_xxxxxxxxxxxxxxxx(secreta) - Public Key:
pk_xxxxxxxxxxxxxxxx(pública) - Portal ID: Tu identificador único
Seguridad Crítica
Nunca expongas la API Key secreta en el frontend. Debe mantenerse en tu backend/servidor y usar HTTPS siempre.
🛠️ Generar Token JWT
Implementa la generación de tokens en tu backend:
curl -X POST https://limbo.lefebvre.es/auth/token \
-H "Content-Type: application/json" \
-d '{
"public_key": "pk_9fcfdd91a14755cc68d0e11a14269554"
}'
httpClient = $httpClient;
$this->publicKey = $publicKey;
$this->apiUrl = $apiUrl;
}
public function generateToken(): array
{
$response = $this->httpClient->request('POST', $this->apiUrl . '/auth/token', [
'json' => [
'public_key' => $this->publicKey
],
'headers' => [
'Content-Type' => 'application/json'
]
]);
if ($response->getStatusCode() !== 200) {
throw new \Exception('Failed to generate token: ' . $response->getContent(false));
}
return $response->toArray();
}
public function getValidToken(): string
{
// Implementar cache/storage del token con renovación automática
$tokenData = $this->generateToken();
return $tokenData['token'];
}
}
class LimboAuthService {
constructor(publicKey, apiUrl) {
this.publicKey = publicKey;
this.apiUrl = apiUrl;
this.tokenCache = null;
this.tokenExpiry = null;
}
async generateToken() {
try {
const response = await fetch(`${this.apiUrl}/auth/token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
public_key: this.publicKey
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
// Cache token con expiración
this.tokenCache = data.token;
this.tokenExpiry = Date.now() + (data.expires_in * 1000) - 30000; // 30s buffer
return data;
} catch (error) {
console.error('Failed to generate token:', error);
throw error;
}
}
async getValidToken() {
// Verificar si el token cached sigue siendo válido
if (this.tokenCache && this.tokenExpiry && Date.now() < this.tokenExpiry) {
return this.tokenCache;
}
// Generar nuevo token
const tokenData = await this.generateToken();
return tokenData.token;
}
}
// Uso
const authService = new LimboAuthService(
process.env.LIMBO_PUBLIC_KEY,
'https://limbo.lefebvre.es'
);
// En tu endpoint o frontend
async function getToken() {
const token = await authService.getValidToken();
return token;
}
🎯 Usar Token en Requests
Una vez que tengas el token, inclúyelo en todas las peticiones a la API:
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhcGktbGltYm8iLCJhdWQiOiJ...
Content-Type: application/json
Ejemplo de Petición Completa
curl -X GET https://limbo.lefebvre.es/assets \
-H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..." \
-H "Content-Type: application/json"
⏰ Gestión de Expiración
Los tokens JWT expiran en 3600 segundos (1 hora) por defecto. Esta duración es configurable por portal. Implementa renovación automática:
Auto-Renovación
Implementa lógica para renovar automáticamente tokens antes de que expiren.
Error 401 Handling
Detecta errores 401 y solicita nuevo token automáticamente.
Token Storage
Almacena tokens de forma segura en memoria o cache distribuido.
❌ Códigos de Error
Posibles errores en el proceso de autenticación:
🔑 Errores de Credenciales
400
Bad Request - Faltan credenciales
401
Unauthorized - API Key inválida
403
Forbidden - Portal deshabilitado
🚨 Errores del Servidor
500
Internal Error - Error generando token
503
Service Unavailable - Servicio temporalmente no disponible