PHP JWT签名无效

时间:2017-08-16 13:42:44

标签: php jwt encode signature

鉴于此代码:

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/未验证签名 有效载荷虽然解密得很好......可能是什么问题?

1 个答案:

答案 0 :(得分:1)

在计算HMAC时,您使用$header.payload附近的单引号,而不是双引号;前者使用文字字符串,不扩展变量:

$signature = hash_hmac('SHA256', "$header.$payload", $key, true);