JWT (JSON Web Token) in PHP without using 3rd-party library. How to sign?(PHP 中的 JWT(JSON Web 令牌),不使用 3rd-party 库.怎么签?)
问题描述
有一些库可以在 PHP 中实现 JSON Web Tokens (JWT),例如 php-jwt.我正在编写自己的非常小而简单的课程,但无法弄清楚为什么我的签名无法通过验证here,即使我已经试图坚持标准.我已经尝试了几个小时,但我被卡住了.请帮忙!
There are a few libraries for implementing JSON Web Tokens (JWT) in PHP, such as php-jwt. I am writing my own, very small and simple class but cannot figure out why my signature fails validation here even though I've tried to stick to the standard. I've been trying for hours and I'm stuck. Please help!
我的代码很简单
//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;
base64url_encode 函数:
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
我的标头和有效负载完全匹配 验证站点的 默认 JWT,但我的签名不匹配,所以我的令牌是标记为无效.这个标准看起来很简单,所以我的签名有什么问题?
My headers and payload perfectly match the validation site's default JWT, but my signature doesn't match so my token is flagged as invalid. This standard seems really straightforward so what's wrong with my signature?
推荐答案
我解决了!我没有意识到签名本身需要进行 base64 编码.此外,我需要将 hash_hmac 函数的最后一个可选参数设置为 $raw_output=true(参见 文档.简而言之,我需要更改原始代码:
I solved it! I did not realize that the signature itself needs to be base64 encoded. In addition, I needed to set the last optional parameter of the hash_hmac function to $raw_output=true (see the docs. In short I needed to change my code from the original:
//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";
致更正:
//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;
这篇关于PHP 中的 JWT(JSON Web 令牌),不使用 3rd-party 库.怎么签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP 中的 JWT(JSON Web 令牌),不使用 3rd-party 库.怎么签?
基础教程推荐
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何替换eregi() 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
