How to generate JWT token in php using with the following parameters Subject, Issuer, Expiry time and payload in the < PAYLOAD > tag.
Sample request from Third Party is shown below
<COMMAND><TYPE>REQUEST</TYPE><INTERFACE>TESTACCOUNT</INTERFACE> <REQUESTID>123</REQUESTID></COMMAND
With the help of an article from DZone Security, I managed to generate a JWT token by doing the following
function base64UrlEncode($text)
{
return str_replace(
['+', '/', '='],
['-', '_', ''],
base64_encode($text)
);
}
$headers = [ "alg" => "HS512"];
$headers_encoded = $this->base64UrlEncode(json_encode($headers));
$issuedAt = time();
$payload = [
"id" =>$this->gen_uuid(), // .setId(UUID.randomUUID().toString())
"sub"=> "TestService", //Subject
"exp"=> $issuedAt+30,
"iss"=> "Baguma Inc", //issuer
"iat"=> $issuedAt, //issued at
"PAYLOAD"=> "<COMMAND><TYPE>REQUEST</TYPE><INTERFACE>TESTACCOUNT</INTERFACE> <REQUESTID>123</REQUESTID></COMMAND"];
$payload_encoded = $this->base64UrlEncode(json_encode($payload));
$key = "fcvxcnfrhrtghkfghgwerikdf";
$signature = hash_hmac('sha512',"$headers_encoded.$payload_encoded",$key,true);
5 Encode the signature
$signature_encoded = $this->base64UrlEncode($signature);
$token = "$headers_encoded.$payload_encoded.$signature_encoded";