php中文网

PHP HyperF -> Firebase JWT

php中文网

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 hyperfhttpservercontractequestinterface;
use hyperfhttpservercontractesponseinterface;

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://github.com/thiagoeti/php-hyperf-firebase-jwt

立即学习“PHP免费学习笔记(深入)”;

以上就是PHP HyperF -> Firebase JWT的详细内容,更多请关注php中文网其它相关文章!