鉴于此代码:
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
$key = 'secret';
//setting the header: 'alg' => 'HS256' indicates that this token is signed using HMAC-SHA256
$header = array(
'alg' => 'HS256',
'typ' => 'JWT'
);
// Returns the JSON representation of the header
$header = json_encode($header);
//encodes the $header with base64.
$header = base64url_encode($header);
$payload = array("a" => "b");
$payload = json_encode($payload);
$payload = base64url_encode($payload);
$signature = hash_hmac('SHA256','$header.$payload', $key, true);
$signature = base64url_encode($signature);
echo "$header.$payload.$signature";
返回以下JWT:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhIjoiYiJ9.rhCKIvkwiuNcchxDZnGak8XT1q8lmLhnm8aIxzUioWg
但是https://jwt.io/未验证签名 有效载荷虽然解密得很好......可能是什么问题?
答案 0 :(得分:1)
在计算HMAC时,您使用$header.payload
附近的单引号,而不是双引号;前者使用文字字符串,不扩展变量:
$signature = hash_hmac('SHA256', "$header.$payload", $key, true);