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

前端 未结 2 1663
无人及你
无人及你 2020-12-30 07:16

There are a few libraries for implementing JSON Web Tokens (JWT) in PHP, such as php-jwt. I am writing my own, very small and simple class but cannot figure out why my sign

2条回答
  •  感动是毒
    2020-12-30 07:56

    I solved it! I did not realize that the signature itself needs to be base64 encoded. In addition, I needed to set the last optional parameter of the hash_hmac function to $raw_output=true (see the docs. 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;
    

提交回复
热议问题