2017-08-16 121 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 :( –