firebase jwt" />
用于验证 jwt 令牌并确保身份验证过程中的真实性和完整性的简单系统。
composer create-project hyperf/hyperf-skeleton "project"
composer require hyperf/watcher --dev
composer require firebase/php-jwt
cd project ; php bin/hyperf.php server:watch ;
jwt_key="***"
路径:/project/.env
router::addroute(['get', 'post'], '/generate', 'app\controller\controllerjwt@generate'); router::addroute(['get', 'post'], '/decode', 'app\controller\controllerjwt@decode');
路径:/project/config/routes.php
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
curl "http://127.0.0.1:9501/generate" response: { "payload": { "uuid": "...0123", "token": "***" }, "token": "***" }
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中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号