PHP HyperF -> Firebase JWT
时间:2025-1-10 20:52 作者:emer 分类: 无
firebase jwt" />
hyperf - 项目
用于验证 jwt 令牌并确保身份验证过程中的真实性和完整性的简单系统。
创建 - 项目
composer create-project hyperf/hyperf-skeleton "project"登录后复制
安装-观察者
composer require hyperf/watcher --dev登录后复制
安装 - firebase jwt
composer require firebase/php-jwt登录后复制
服务器 - 启动
cd project ; php bin/hyperf.php server:watch ;登录后复制
hyperf-app
app-环境
jwt_key="***"登录后复制
路径:/project/.env
app-路由器
router::addroute(['get', 'post'], '/generate', 'appcontrollercontrollerjwt@generate'); router::addroute(['get', 'post'], '/decode', 'appcontrollercontrollerjwt@decode');登录后复制
路径:/project/config/routes.php
app-控制器
namespace appcontroller;
use hyperfdinnotationinject;
use hyperfhttpservercontract
equestinterface;
use hyperfhttpservercontract
esponseinterface;
use function hyperfsupportenv;
use ramseyuuiduuid;
use firebasejwtjwt;
use firebasejwtkey;
class controllerjwt
{
#[inject]
protected requestinterface $request;
#[inject]
protected responseinterface $response;
protected $jwt_key;
public function __construct()
{
$this->jwt_key=env('jwt_key', '***');
}
public function generate()
{
$payload=[
'uuid'=>uuid::uuid4()->tostring(),
'token'=>sha1(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyz')),
];
$token=jwt::encode($payload, $this->jwt_key, 'hs256');
return [
'payload'=>$payload,
'token'=>$token,
];
}
public function decode()
{
$token=$this->request->getheader('authorization')[0] ?? '';
$token=str_replace('bearer ', '', $token);
try {
$decode=jwt::decode($token, new key($this->jwt_key, 'hs256'));
} catch (exception $e){
return $this->response->withstatus(401)->json(['token'=>'invalid']);
}
return [
'token'=>$token,
'decode'=>$decode,
];
}
}
登录后复制
路径:/project/app/controller/controllerjwt.php
执行
get - 生成令牌
curl "http://127.0.0.1:9501/generate"
response:
{
"payload": {
"uuid": "...0123",
"token": "***"
},
"token": "***"
}
登录后复制
get - 解码令牌
curl "http://127.0.0.1:9501/decode" -H "Authorization: Bearer %token%"
Response:
{
"token": "***",
"decode": {
"uuid": "...0123",
"token": "***"
}
}
登录后复制
https://hub.com/thiagoeti/php-hyperf-firebase-jwt
立即学习“”;
以上就是PHP HyperF -> Firebase JWT的详细内容,