Generación de Credenciales API

 

 Generación de Credenciales API

Método 1: Credenciales básicas (API Key + Secret)

php
<?php
// Generar credenciales seguras
function generarCredencialesAPI() {
    $api_key = bin2hex(random_bytes(32)); // 64 caracteres hexadecimales
    $api_secret = bin2hex(random_bytes(64)); // 128 caracteres hexadecimales
    
    return [
        'api_key' => $api_key,
        'api_secret' => password_hash($api_secret, PASSWORD_DEFAULT)
    ];
}

// Generar y guardar credenciales
$credenciales = generarCredencialesAPI();

// Guardar en base de datos (ejemplo)
// INSERT INTO api_credentials (api_key, api_secret_hash, created_at) 
// VALUES (:api_key, :api_secret, NOW())
?>

Método 2: Credenciales JWT

php
<?php
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JWTCredentials {
    private $secret_key;
    
    public function __construct() {
        $this->secret_key = bin2hex(random_bytes(64));
    }
    
    public function generarToken($payload) {
        return JWT::encode($payload, $this->secret_key, 'HS256');
    }
    
    public function verificarToken($token) {
        return JWT::decode($token, new Key($this->secret_key, 'HS256'));
    }
}
?>

2. Autenticación con API Key

Cliente PHP para consumir API

php
<?php
class APIClient {
    private $api_key;
    private $api_secret;
    private $base_url;
    
    public function __construct($api_key, $api_secret, $base_url) {
        $this->api_key = $api_key;
        $this->api_secret = $api_secret;
        $this->base_url = $base_url;
    }
    
    public function hacerRequest($endpoint, $data = [], $method = 'GET') {
        $url = $this->base_url . $endpoint;
        
        $headers = [
            'X-API-Key: ' . $this->api_key,
            'X-API-Signature: ' . $this->generarFirma($data),
            'Content-Type: application/json'
        ];
        
        $ch = curl_init();
        
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_SSL_VERIFYPEER => true
        ]);
        
        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        
        curl_close($ch);
        
        return [
            'status' => $http_code,
            'response' => json_decode($response, true)
        ];
    }
    
    private function generarFirma($data) {
        $timestamp = time();
        $string_to_sign = $timestamp . json_encode($data);
        return hash_hmac('sha256', $string_to_sign, $this->api_secret);
    }
}
?>

3. Servidor para verificar credenciales

Middleware de autenticación

php
<?php
class AuthMiddleware {
    private $db;
    
    public function __construct($db) {
        $this->db = $db;
    }
    
    public function verificarAPIKey($api_key, $firma, $datos) {
        // Buscar credencial en base de datos
        $stmt = $this->db->prepare("
            SELECT api_secret_hash, usuario_id, activo 
            FROM api_credentials 
            WHERE api_key = :api_key
        ");
        
        $stmt->execute([':api_key' => $api_key]);
        $credencial = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$credencial || !$credencial['activo']) {
            return false;
        }
        
        // Verificar firma
        $timestamp = time();
        $string_to_sign = $timestamp . json_encode($datos);
        $firma_calculada = hash_hmac('sha256', $string_to_sign, $credencial['api_secret_hash']);
        
        return hash_equals($firma_calculada, $firma);
    }
}
?>

4. Uso completo del cliente

Ejemplo de implementación

php
<?php
// Configuración
$api_key = "tu_api_key_generada";
$api_secret = "tu_api_secret_original"; // No el hash
$base_url = "https://api.tudominio.com/v1/";

// Crear cliente
$cliente = new APIClient($api_key, $api_secret, $base_url);

// Hacer petición
try {
    $response = $cliente->hacerRequest('/usuarios', [
        'filtro' => 'activos',
        'pagina' => 1
    ], 'GET');
    
    if ($response['status'] === 200) {
        echo "Éxito: ";
        print_r($response['response']);
    } else {
        echo "Error: " . $response['status'];
    }
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
?>

5. Gestión segura de credenciales

Almacenamiento seguro

php
<?php
// Configuración segura en entorno
class Config {
    const API_CREDENTIALS = [
        'key' => getenv('API_KEY'),
        'secret' => getenv('API_SECRET'),
        'url' => getenv('API_URL')
    ];
    
    public static function getCredentials() {
        return [
            'key' => self::API_CREDENTIALS['key'],
            'secret' => self::API_CREDENTIALS['secret'],
            'url' => self::API_CREDENTIALS['url']
        ];
    }
}

// Uso seguro
$credenciales = Config::getCredentials();
$cliente = new APIClient(
    $credenciales['key'],
    $credenciales['secret'],
    $credenciales['url']
);
?>

6. Archivo .env ejemplo

text
API_KEY=tu_api_key_aqui
API_SECRET=tu_api_secret_muy_largo_y_seguro_aqui
API_URL=https://api.tudominio.com/v1/

Consideraciones de seguridad:

  1. Nunca commits credenciales en el código

  2. Usa variables de entorno

  3. Implementa rate limiting

  4. Usa HTTPS siempre

  5. Rota las credenciales periódicamente

  6. Valida y sanitiza todas las entradas

Comentarios

Entradas más populares de este blog

token

¿Qué es un token y cómo se utiliza en una API?