thinkphp6集成JWT

1.引入php-jwt包

composer require firebase/php-jwt

2.代码

控制器文件:app\api\controller\Jwt.php

<?php
namespace app\api\controller;
use app\BaseController;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT as JWTUtil;
class Jwt extends BaseController
{
    
    
    /**
     * 根据json web token设置的规则生成token
     * @return \think\response\Json
     */
    public function createjwt()
    {
    
    
        $key = md5('dd'); //jwt的签发密钥,验证token的时候需要用到
        $time = time(); //签发时间
        $expire = $time + 14400; //过期时间
        $token = array(
            "user_id" => 1,
            "iss" => "http://www.najingquan.com/",//签发组织
            "aud" => "zz", //签发作者
            "iat" => $time,
            "nbf" => $time,
            "exp" => $expire
        );
        $jwt = JWTUtil::encode($token,$key);
        return show(1,"OK",$jwt);
    }

    /**
     * 验证token
     * @return \think\response\Json
     */
    public function verifyjwt()
    {
    
    
        $jwt= input("jwt");
        $key = md5('dd'); //jwt的签发密钥,验证token的时候需要用到
        try{
    
    
            $jwtAuth = json_encode(JWTUtil::decode($jwt,$key,array("HS256")));
            $authInfo = json_decode($jwtAuth,true);
            if (!$authInfo['user_id']){
    
    
                return show(0,"用户不存在");
            }
            return show(0,"ok");
        }catch (ExpiredException $e){
    
    
            return show(0,"token过期");
        }catch (\Exception $e){
    
    
            return show(0,$e->getMessage());
        }

    }
}

路由:app\api\route\api.php

<?php
use think\facade\Route;
Route::rule("jwt","jwt/createjwt","get");
Route::rule("verifyjwt","jwt/verifyjwt","post");
3.效果如图所示

生成token

图1.生成token

token里面解析的数据

图2.token信息

猜你喜欢

转载自blog.csdn.net/kevlin_V/article/details/108512135