不使用第三方库的PHP中的JWT(JSON Web Token).怎么签?

Bee*_*ice 11 php authentication json sha jwt

有一些用于在PHP中实现JSON Web令牌(JWT)的库,例如php-jwt.我正在编写自己的,非常小而简单的类,但无法弄清楚为什么我的签名未能在此验证,即使我已经尝试坚持标准.我已经尝试了几个小时而且我被卡住了.请帮忙!

我的代码很简单

//build the headers
$headers = ['alg'=>'HS256','typ'=>'JWT'];
$headers_encoded = base64url_encode(json_encode($headers));

//build the payload
$payload = ['sub'=>'1234567890','name'=>'John Doe', 'admin'=>true];
$payload_encoded = base64url_encode(json_encode($payload));

//build the signature
$key = 'secret';
$signature = hash_hmac('SHA256',"$headers_encoded.$payload_encoded",$key);

//build and return the token
$token = "$headers_encoded.$payload_encoded.$signature";
echo $token;
Run Code Online (Sandbox Code Playgroud)

base64url_encode函数:

function base64url_encode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
Run Code Online (Sandbox Code Playgroud)

我的标头和有效负载与验证网站的默认JWT 完全匹配,但我的签名不匹配,因此我的标记被标记为无效.这个标准看起来真的很简单,所以我的签名有什么问题?

Bee*_*ice 18

我解决了!我没有意识到签名本身需要base64编码.另外,我需要设置hash_hmac函数的最后一个可选参数$raw_output=true(参见文档.简而言之,我需要从原始代码更改我的代码:

//build the signature
$key = 'secret';
$signature = hash_hmac('SHA256',"$headers_encoded.$payload_encoded",$key);

//build and return the token
$token = "$headers_encoded.$payload_encoded.$signature";
Run Code Online (Sandbox Code Playgroud)

纠正的:

//build the signature
$key = 'secret';
$signature = hash_hmac('SHA256',"$headers_encoded.$payload_encoded",$key,true);
$signature_encoded = base64url_encode($signature);

//build and return the token
$token = "$headers_encoded.$payload_encoded.$signature_encoded";
echo $token;
Run Code Online (Sandbox Code Playgroud)


Chr*_*ian 11

如果你想使用RS256(而不是像OP那样的HS256)来解决它,你可以这样使用它:

//build the headers
$headers = ['alg'=>'RS256','typ'=>'JWT'];
$headers_encoded = base64url_encode(json_encode($headers));

//build the payload
$payload = ['sub'=>'1234567890','name'=>'John Doe', 'admin'=>true];
$payload_encoded = base64url_encode(json_encode($payload));

//build the signature
$key = "-----BEGIN PRIVATE KEY----- ....";
openssl_sign("$headers_encoded.$payload_encoded", $signature, $key, 'sha256WithRSAEncryption'); 
$signature_encoded = base64url_encode($signature);

//build and return the token
$token = "$headers_encoded.$payload_encoded.$signature_encoded";
echo $token;
Run Code Online (Sandbox Code Playgroud)

我花了比我愿意承认的更长的时间