【问题标题】:PHP JWT Invalid signaturePHP JWT 无效签名
【发布时间】:2018-01-24 16:44:24
【问题描述】:

鉴于此代码:

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/验证 有效载荷被很好地解密了......可能是什么问题?

【问题讨论】:

    标签: php jwt encode signature


    【解决方案1】:

    在计算 HMAC 时,您在 $header.payload 周围使用单引号,而不是双引号;前者使用文字串,不展开变量:

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

    【讨论】:

    • 哇,真快!谢谢,就是这样!我猜是基本的 PHP 知识,但我来自 JS :(
    猜你喜欢
    • 1970-01-01
    • 2017-05-30
    • 2016-12-29
    • 2020-01-21
    • 1970-01-01
    • 2018-06-14
    • 2019-08-04
    • 2018-05-08
    • 2019-01-02
    相关资源
    最近更新 更多