2017-08-16 108 views
0

鉴于此代码:PHP JWT无效签名

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

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

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

哇,那太快了!谢谢,就是这样!基本的PHP知识我猜,但我来自JS :( –