Search code examples
phpjwt

How to generate JWT in PHP


How to generate JWT token in php using with the following parameters Subject, Issuer, Expiry time and payload in the < PAYLOAD > tag.

  • Id can be any random number of any length.
  • subject is TestService
  • Issuer is Baguma Inc
  • Expiry Time will be 30 sec from current time(ideally ).
  • Payload is the request from Third Party
  • SigningKEY is fcvxcnfrhrtghkfghgwerikdf
  • Signature algorithm will be HS512.

Sample request from Third Party is shown below

<COMMAND><TYPE>REQUEST</TYPE><INTERFACE>TESTACCOUNT</INTERFACE> <REQUESTID>123</REQUESTID></COMMAND


Solution

  • With the help of an article from DZone Security, I managed to generate a JWT token by doing the following

    1. Define the base64UrlEncode function which replaces + with -, / with _ and = with ''.
    function base64UrlEncode($text)
    {
        return str_replace(
            ['+', '/', '='],
            ['-', '_', ''],
            base64_encode($text)
        );
    }
    
    
    1. Encode the headers using base64UrlEncode
    $headers = [ "alg" => "HS512"];
    
    $headers_encoded = $this->base64UrlEncode(json_encode($headers));
    
    1. 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));
    
    1. 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);
    
    1. Build and return the token
    $token = "$headers_encoded.$payload_encoded.$signature_encoded";