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

前端 未结 2 1657
无人及你
无人及你 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 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

提交回复
热议问题