I am calling a PHP script with curl API and PHP script return the data in JSON format, I want to use token-based authentication. After a lot of R&D, I found that I can use Firebase JWT authentication.
My curl script is below:
$url = "http://localhost/module/returndata.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
return $result;
and I have a PHP script file(returndata.php) which is return data. Now I want to JWT-Authentication when I called this file. Please suggest me if anyone have an idea regarding it.
Currently, I got some links and created a test file but I don't have an idea how to do it.
<?php
ini_set("display_errors", "1");
error_reporting(E_ALL);
set_time_limit(0);
require_once('vendor/autoload.php');
use \Firebase\JWT\JWT;
define('SECRET_KEY','Admin%^&ttt') ; // secret key can be a random string and keep in secret from anyone
define('ALGORITHM','HS512');
$tokenId = base64_encode(random_bytes(32));
$issuedAt = time();
$notBefore = $issuedAt + 10; //Adding 10 seconds
$expire = $notBefore + 7200; // Adding 60 seconds
$serverName = 'http://localhost/'; /// set your domain name
/*
* Create the token as an array
*/
$data = [
'iat' => $issuedAt, // Issued at: time when the token was generated
'jti' => $tokenId, // Json Token Id: an unique identifier for the token
'iss' => $serverName, // Issuer
'nbf' => $notBefore, // Not before
'exp' => $expire, // Expire
'data' => [ // Data related to the logged user you can set your required data
'id' => "smithjames", // id from the users table
'name' => "admin", // name
]
];
$secretKey = base64_decode(SECRET_KEY);
/// Here we will transform this array into JWT:
$jwt = JWT::encode(
$data, //Data to be encoded in the JWT
$secretKey, // The signing key
ALGORITHM
);
$unencodedArray = ['jwt' => $jwt];
try {
$secretKey = base64_decode(SECRET_KEY);
$DecodedDataArray = JWT::decode($_REQUEST['tokVal'], $secretKey, array(ALGORITHM));
echo "{'status' : 'success' ,'data':".json_encode($DecodedDataArray)." }";die();
} catch (Exception $e) {
echo "{'status' : 'fail' ,'msg':'Unauthorized'}";die();
}
I have already installed "Firebase\JWT\JWT" and working fine but how to implement it.