Search code examples
phpcurlaccess-tokenphp-curl

how to fix Invalid request (Unsupported SSL request) only php?


Context of the problem I am taking a course at www.platzi.com, and in this chapter they are teaching us the logic and operation of token web authentication. So the code shown below is as shown in the course.

The flow of the code is as follows:

You have a resource server called "server.php" this server takes care of the resources you have. There is a route server called "router.php" this server is in charge of receiving the requests, give it to the resource server called "server.php" There is a server for authentication called auth_server.php, this server has two functions:

  1. Create a token when the user goes to login
  2. Validate The token that the user supplies to the resource server called server.php

Code

code server.php

<?php

header('Content-Type: application/json');
// validación de que el servidor de recursos  recibió un token
if (!array_key_exists('HTTP_X_TOKEN', $_SERVER)) {

die;
}

// $url = 'https://' . $_SERVER['HTTP_HOST'] . '/auth';

// Se debe validar el token recibido con el servidor,
// de autenticación ejecutando una llamada a tráves
//  de curl.
$url = 'https://localhost:8001';

// iniciamos la llamada de curl
$ch = curl_init($url);

// Se configura curl para enviar
// el token y  validarlo con el serrvidor
// de validación.
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
[
"X-Token: {$_SERVER['HTTP_X_TOKEN']}",
]
);

// Se configura  curl nuevamente para recibir la
// respuesta sobre el token  que enviamos
// del servidor de validación
curl_setopt(
$ch,
CURLOPT_RETURNTRANSFER,
true
);

// Se obtine la respuesta del servidor
// de validación
$ret = curl_exec($ch);

// finalmente se compara la respuesta del servidor
// de autenticación, si el resultado no es true
// entonces el usuario no ha sido autenticado
// correctamente
if ($ret !== 'true') {
http_response_code(403);

die;
}


$books = [
1 => [
'titulo' => 'Lo que el viento se llevo',
'id_autor' => 2,
'id_genero' => 2,
],
2 => [
'titulo' => 'La Iliada',
'id_autor' => 1,
'id_genero' => 1,
],
3 => [
'titulo' => 'La Odisea',
'id_autor' => 1,
'id_genero' => 1,
],
];

$allowedResourceTypes = [
'books',
'authors',
'genres',
];

$resourceType = $_GET['resource_type'];
if (!in_array($resourceType, $allowedResourceTypes)) {
header('Status-Code: 400');
echo json_encode(
[
  'error' => "Resource type '$resourceType' is un unkown",
]
);

die;
}


$resourceId = array_key_exists('resource_id', $_GET) ? $_GET['resource_id'] : '';
$method = $_SERVER['REQUEST_METHOD'];

switch (strtoupper($method)) {
case 'GET':
if ("books" !== $resourceType) {
  header('Status-Code: 404');

  echo json_encode(
    [
      'error' => $resourceType . ' not yet implemented :(',
    ]
  );

  die;
}

if (!empty($resourceId)) {
  if (array_key_exists($resourceId, $books)) {
    echo json_encode(
      $books[$resourceId]
    );
  } else {
    header('Status-Code: 404');

    echo json_encode(
      [
        'error' => 'Book ' . $resourceId . ' not found :(',
      ]
    );
  }
} else {
  echo json_encode(
    $books
  );
}

die;

break;
case 'POST':
$json = file_get_contents('php://input');

$books[] = json_decode($json);

echo array_keys($books)[count($books) - 1];
break;
case 'PUT':
if (!empty($resourceId) && array_key_exists($resourceId, $books)) {
  $json = file_get_contents('php://input');

  $books[$resourceId] = json_decode($json, true);

  echo $resourceId;
}
break;
case 'DELETE':
if (!empty($resourceId) && array_key_exists($resourceId, $books)) {
  unset($books[$resourceId]);
}
break;
default:
header('Status-Code: 404');

echo json_encode(
  [
    'error' => $method . ' not yet implemented :(',
  ]
);

break;
}

code router.php


<?php

$matches = [];

if (preg_match('/\/([^\/]+)\/([^\/]+)/', $_SERVER["REQUEST_URI"], $matches)) {
  $_GET['resource_type'] = $matches[1];
  $_GET['resource_id'] = $matches[2];

  error_log(print_r($matches, 1));
  require 'server.php';
} elseif (preg_match('/\/([^\/]+)\/?/', $_SERVER["REQUEST_URI"], $matches)) {
  $_GET['resource_type'] = $matches[1];
  error_log(print_r($matches, 1));

  require 'server.php';
} else {

  error_log('No matches');
  http_response_code(404);
}

code auth_server.php


<?php

$method = strtoupper($_SERVER['REQUEST_METHOD']);

// $token = "5d0937455b6744.68357201";
$token = sha1('Esto es secreto!!');

if ($method === 'POST') {
  if (!array_key_exists('HTTP_X_CLIENT_ID', $_SERVER) || 
      !array_key_exists('HTTP_X_SECRET', $_SERVER)) {
          http_response_code(400);

         die('Faltan parametros');
  }

  $clientId = $_SERVER['HTTP_X_CLIENT_ID'];
  $secret = $_SERVER['HTTP_X_SECRET'];

  if ($clientId !== '1' || $secret !== 'SuperSecreto!') {
    http_response_code(403);

    die("No autorizado");
  }

  echo "$token";
} elseif ($method === 'GET') {
  if (!array_key_exists('HTTP_X_TOKEN', $_SERVER)) {
    http_response_code(400);

    die('Faltan parametros');
  }

  if ($_SERVER['HTTP_X_TOKEN'] == $token) {
    echo 'true';
  } else {
    echo 'false';
  }
} else {
  echo 'false';
}

steps to replicate the problem

  1. he previously presented codes are in a single folder. Each code presented above is separated into separate files: server.php, router.php, auth_server.php

  2. In the linux terminal a tab is opened for each server and request that is shown below to. In a tab, the router server starts

$ php -S localhost:8000 router.php

ini router server

  1. In another tab, the authentication server starts
$ php -S localhost:8001 auth_server.php

ini auth server

  1. In another tab, the request is made to the authentication server to request a token, the server creates the token and I return it in the terminal. The token must be copied and sent with the GET request that is shown in the next step. Token creation
curl http://localhost:8001 -X 'POST' -H 'X-CLIENT-Id:1' -H 'X-Secret:SuperSecreto!'

get token

  1. In another tab, the GET request is made together with the token
curl http://localhost:8000/books -H 'X-Token:c4b02a1525349e7888d4140dcd524aff2d6296dd'

request list book with token

and. finally after the previous query nothing is shown.

The expected behavior: Show the list of books. Current behavior: It does not show the list of books and in the tab where the authentication server is running it shows the message of:

[Wed Jun 2 12:42:21 2021] :: 1: 48248 Invalid request (Unsupported SSL request)

error in auth server

environment specifications linux ubuntu 20.04

version php PHP 7.1.33-37

Note: sorry for my bad English. I'm using a translator


Solution

  • // Se debe validar el token recibido con el servidor,
    // de autenticación ejecutando una llamada a tráves
    //  de curl.
    $url = 'https://localhost:8001';
    

    needs to be

    // Se debe validar el token recibido con el servidor,
    // de autenticación ejecutando una llamada a tráves
    //  de curl.
    $url = 'http://localhost:8001';