How to validate access to an API for only the licensed domain?

0

I'm looking for original ideas on how to validate access to an API in php for only the domain that paid the license, since SERVER['HTTP_REFERER'] is not trustworthy.

I created an activation key in json and encrypted, generated a decryption method, but this does not guarantee that the key can be copied to multiple domains. Has anyone implemented anything like this with a workaround?

  public function GerarKeyToken($tamanho = 8, $maiusculas = true, $numeros true, $simbolos = false){
    // Caracteres de cada tipo
    $lmin = 'abcdefghijklmnopqrstuvwxyz';
    $lmai = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $num  = '1234567890';
    $simb = '!@#$%*-';
    // Variáveis internas
    $retorno     = '';
    $caracteres  = '';
    // Agrupamos todos os caracteres que poderão ser utilizados
    $caracteres .= $lmin;
    if ($maiusculas) $caracteres .= $lmai;
    if ($numeros) $caracteres .= $num;
    if ($simbolos) $caracteres .= $simb;
    // Calculamos o total de caracteres possíveis
    $len = strlen($caracteres);
    for ($n = 1; $n <= $tamanho; $n++) {
      // Criamos um número aleatório de 1 até $len para pegar um dos caracteres
      $rand = mt_rand(1, $len);
      // Concatenamos um dos caracteres na variável $retorno
      $retorno .= $caracteres[$rand-1];
    }
    return $retorno;
  }

  public function Encrypt($MegaImporterLicenca){
    $key           = hash('sha256', $MegaImporterLicenca->GetKeyToken());
    $iv            = substr(hash('sha256', $MegaImporterLicenca->GetKeyToken()), 0, 16);
    $encrypt_text  = json_encode(array('id'        => $MegaImporterLicenca->GetId(),
                                       'dominio'   => $MegaImporterLicenca->GetDominio(),
                                       'cadastro'  => $MegaImporterLicenca->GetCadastro(),
                                       'expiracao' => $MegaImporterLicenca->GetExpiracao()));
    $output        = openssl_encrypt($encrypt_text, METHOD, $key, 0, $iv);
    $output        = base64_encode($output);
    return $output;
  }

  public function Decrypt($MegaImporter,$hash){
    $key    = hash('sha256', $MegaImporter->GetKeyToken());
    $iv     = substr(hash('sha256', $MegaImporter->GetKeyToken()), 0, 16);
    $output = openssl_decrypt(base64_decode($hash), METHOD, $key, 0, $iv);
    return $output;
  }
    
asked by anonymous 31.10.2018 / 17:23

1 answer

1

You can use a Header that gives access to only a few domains ... The Header is Access-Control-Allow-Origin and you can use it according to the example below ...

<?php
$origin = $_SERVER['HTTP_ORIGIN'];
$allowed_domains = [
    'http://mysite1.com',
    'https://www.mysite2.com',
    'http://www.mysite2.com',
];

if (in_array($origin, $allowed_domains)) {
    header('Access-Control-Allow-Origin: ' . $origin);
}
    
31.10.2018 / 19:00