JWT (JSON Web Token) in PHP without using a third-party library. How to sign?

There are several libraries in PHP for implementing JSON Web Tokens (JWT), such as php-jwt . I write my own very small and simple class, but I can’t understand why my signature completes the verification here , although I tried to adhere to the standard. I tried for hours and I was stuck. Please, help!

My code is simple

//build the headers $headers = ['alg'=>'HS256','typ'=>'JWT']; $headers_encoded = base64url_encode(json_encode($headers)); //build the payload $payload = ['sub'=>'1234567890','name'=>'John Doe', 'admin'=>true]; $payload_encoded = base64url_encode(json_encode($payload)); //build the signature $key = 'secret'; $signature = hash_hmac('SHA256',"$headers_encoded.$payload_encoded",$key); //build and return the token $token = "$headers_encoded.$payload_encoded.$signature"; echo $token; 

base64url_encode function:

 function base64url_encode($data) { return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); } 

My headers and payload ideally match the default JWT standard for site validation, but my signature does not match, so my token is marked as invalid. This standard seems really simple, so what's wrong with my signature?

+5
source share
1 answer

I solved it! I did not understand that the signature itself should be encoded in base64. In addition, I needed to set the last optional parameter of the hash_hmac function to $raw_output=true (see the documents . In short, I needed to change my code from the original:

 //build the signature $key = 'secret'; $signature = hash_hmac('SHA256',"$headers_encoded.$payload_encoded",$key); //build and return the token $token = "$headers_encoded.$payload_encoded.$signature"; 

To the corrected:

 //build the signature $key = 'secret'; $signature = hash_hmac('SHA256',"$headers_encoded.$payload_encoded",$key,true); $signature_encoded = base64url_encode($signature); //build and return the token $token = "$headers_encoded.$payload_encoded.$signature_encoded"; echo $token; 
+12
source

Source: https://habr.com/ru/post/1236210/


All Articles