Implement token's in web services with php and json

0

I have created several web services to consult data from my database from an android application, the web services are already working, they return the information to me and it is already shown in the application, but I want to implement token's as security in my queries, but not I understand how I can implement the token's, this is a web services that I use:

<?PHP
$hostname_localhost = "localhost";
$database_localhost = "mgrex";
$username_localhost = "root";
$password_localhost = "";

$json = array();

if(isset($_GET["empresa"]) && isset($_GET["rol"])){
    $empresa = $_GET["empresa"];
    $rol = $_GET["rol"];

    $conexion = mysqli_connect($hostname_localhost,$username_localhost,$password_localhost,$database_localhost);
    mysqli_set_charset($conexion, "utf8");
    $consulta = "select * from inicio WHERE empresa = '{$empresa}' AND rol = '{$rol}'";
    $resultado = mysqli_query($conexion, $consulta);

    while($registro=mysqli_fetch_array($resultado)){
        $json['inicio'][]=$registro;    
    }

}else{
            $resultar["tituloNoticia"]='No registrado';
            $resultar["subtituloNoticia"]='No registrado';
            $resultar["imagenNoticia"]='No registrado';
            $resultar["descripcionNoticia"]='No registrado';
            $resultar["empresa"]='No registrado';
            $resultar["rol"]='No registrado';
            $json['inicio'][]=$resultar;

}
    mysqli_close($conexion);
    echo json_encode($json);

?> 

I have been reviewing examples on the internet like the following:

require_once 'vendor/autoload.php';

use Firebase\JWT\JWT;

$time = time();
$key = 'my_secret_key';

$token = array(
    'iat' => $time, // Tiempo que inició el token
    'exp' => $time + (60*60), // Tiempo que expirará el token (+1 hora)
    'data' => [ // información del usuario
        'id' => 1,
        'name' => 'Eduardo'
    ]
);

$jwt = JWT::encode($token, $key);

$data = JWT::decode($jwt, $key, array('HS256'));

var_dump($data);

I do not understand how I can use this example in my web service.

    
asked by Enrique Espinosa 29.12.2018 в 17:12
source

1 answer

2

To implement Json Web Tokens (JWT). The first thing you have to have is a user table.

The first part is a common and current login. This part will answer you with the one json.

The request must contain the following:

  • User (user id key)
  • Password (secret)

You must validate this data in your database, if these exist you must create a token with the methods of jwt.

is what you have.

$token = array(
    'iat' => $time, // Tiempo que inició el token
    'exp' => $time + (60*60), // Tiempo que expirará el token (+1 hora)
    'data' => [ // información del usuario
       'id' => 1, // key 
       'name' => 'Eduardo' // secret
  ]
);
$jwt = JWT::encode($token, $key);

The variable jwt will become a json, which you should respond with something like that.

return $jwt;

Now every time you make requests to your API you will have to send in the headers this example token:

axios.post(
  url, 
  {
     _token: Token_jwt
  }
).then(
   res=>{ 
   }
);

Finally, all the requests that arrive at your api must contain the token and this must be valid. therefore you must interpret it.

<?PHP


    // obviamente tambien tienes que importar la libreria de jwt
    $key = 'Tu clave de la aplicacion';
    if(empty($_POST['_token'])){
      $data = (objetc)JWT::decode($jwt, $key, array('HS256'));
      if($data->exp > time()){
        return abort(401);
      }
    }else{
      return abort(401);
    }




        $hostname_localhost = "localhost";
        $database_localhost = "mgrex";
        $username_localhost = "root";
        $password_localhost = "";

        $json = array();

        if(isset($_GET["empresa"]) && isset($_GET["rol"])){
            $empresa = $_GET["empresa"];
            $rol = $_GET["rol"];

            $conexion = mysqli_connect($hostname_localhost,$username_localhost,$password_localhost,$database_localhost);
            mysqli_set_charset($conexion, "utf8");
            $consulta = "select * from inicio WHERE empresa = '{$empresa}' AND rol = '{$rol}'";
            $resultado = mysqli_query($conexion, $consulta);

            while($registro=mysqli_fetch_array($resultado)){
                $json['inicio'][]=$registro;    
            }

        }else{
                    $resultar["tituloNoticia"]='No registrado';
                    $resultar["subtituloNoticia"]='No registrado';
                    $resultar["imagenNoticia"]='No registrado';
                    $resultar["descripcionNoticia"]='No registrado';
                    $resultar["empresa"]='No registrado';
                    $resultar["rol"]='No registrado';
                    $json['inicio'][]=$resultar;

        }
            mysqli_close($conexion);
            echo json_encode($json);

        ?> 
    
answered by 30.12.2018 / 07:59
source