Thinkphp6集成JWT进行token认证

项目根目录composer下载

引入php-jwt包

composer require firebase/php-jwt

封装方法

 $user_id,
            //签发组织
            "iss" => env("TOKEN.iss",""),
            //签发作者
            "aud" => env("TOKEN.aud",""),
            //签发时间
            "iat" => $time,
            //生效时间
            "nbf" => $time,
            //过期时间
            "exp" => $expire
        );
        //返回token结果
        return json(JWTUtil::encode($token,$key));
    }

    /**
     *  进行token认证
     * @param $jwt
     * @return \think\response\Json
     */
    public static function verifyJwt($jwt)
    {
        //jwt的签发密钥,验证token的时候需要用到
        $key = md5(env("TOKEN.iss"));
        try{
            $jwtAuth = json_encode(JWTUtil::decode($jwt,$key,array("HS256")));
            $authInfo = json_decode($jwtAuth,true);
            if (!$authInfo['user_id']){
                return \json(['code'=>400,'msg'=>'用户名不存在','data'=>[]]);
            }
            return \json($authInfo);
        }catch (ExpiredException $e){
            return \json(['code'=>501,'data'=>[],'msg'=>'token已经过期']);
        }catch (\Exception $e){
            return \json(['code'=>$e->getCode(),'msg'=>$e->getMessage(),'data'=>[]]);
        }
    }
    
        /**从请求信息中获取token令牌
         * @return false|string
         */
        public static function getRequestToken()
        {
            if (empty($_SERVER['HTTP_AUTHORIZATION'])) {
                return false;
            }
            $header = $_SERVER['HTTP_AUTHORIZATION'];
            $method = 'bearer';
            //去除token中可能存在的bearer标识
            return trim(str_ireplace($method, '', $header));
        }


    //鉴权
    public function handle($request, \Closure $next)
    {
        $response = $next($request);

        $route = $request->pathinfo();

        if(!in_array($route,self::$arr))
        {
            $token = Jwt::getRequestToken();

            $res = Jwt::verify($token);

            if($res!="ok")
            {
                return json('验证失败');
            }
        }
        return $response;
}
}

控制器调用封装方法即可

你可能感兴趣的:(php,thinkphp)