首页 >后端开发 >php教程 >PHP HyperF -> Firebase JWT

PHP HyperF -> Firebase JWT

DDD
DDD原创
2024-12-11 09:36:10196浏览

PHP HyperF -> Firebase JWT 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', 'App\Controller\ControllerJWT@generate');
Router::addRoute(['GET', 'POST'], '/decode', 'App\Controller\ControllerJWT@decode');

路径:/project/config/routes.php

APP-控制器

namespace App\Controller;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;

use function Hyperf\Support\env;

use Ramsey\Uuid\Uuid;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

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 HyperF -> Firebase JWT的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn