With the help of an article from DZone Security, I managed to generate a JWT token by doing the following
- Define the base64UrlEncode function which replaces + with -, / with _ and = with ''.
function base64UrlEncode($text)
{
return str_replace(
['+', '/', '='],
['-', '_', ''],
base64_encode($text)
);
}
- Encode the headers using base64UrlEncode
$headers = [ "alg" => "HS512"];
$headers_encoded = $this->base64UrlEncode(json_encode($headers));
- Encode the Payload using Base64 URL encode as well
$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));
- Using the Key/secret build the signature
$key = "fcvxcnfrhrtghkfghgwerikdf";
$signature = hash_hmac('sha512',"$headers_encoded.$payload_encoded",$key,true);
5 Encode the signature
$signature_encoded = $this->base64UrlEncode($signature);
- Build and return the token
$token = "$headers_encoded.$payload_encoded.$signature_encoded";