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

前端 未结 2 1646
无人及你
无人及你 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;
    
    0 讨论(0)
  • 2020-12-30 08:07

    If you want to solve it using RS256 (instead of HS256 like OP) you can use it like this:

    //build the headers
    $headers = ['alg'=>'RS256','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 = "-----BEGIN PRIVATE KEY----- ....";
    openssl_sign("$headers_encoded.$payload_encoded", $signature, $key, 'sha256WithRSAEncryption'); 
    $signature_encoded = base64url_encode($signature);
    
    //build and return the token
    $token = "$headers_encoded.$payload_encoded.$signature_encoded";
    echo $token;
    

    Took me way longer than I'd like to admit

    0 讨论(0)
提交回复
热议问题