tp6 jwt使用父类继承验证token

1.项目前提:tp6单应用
jwt:firebase/php-jwt

composer require firebase/php-jwt

// app/common/jwtauth.php
<?php
// jwt验证
namespace app\common;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\ExpiredException;
use DomainException;
use InvalidArgumentException;
use UnexpectedValueException;
class JwtAuth
{
    private static $key = 'example_key';

    public static function generateToken($data)
    {
        $payload = [
            'iss' => 'http://example.org',
            'aud' => 'wcxt',
        	'nbf' => time()-2,//在此之前不可用
            'iat' => time(),//发布时间
        	'exp' => time()+60,//过期时间
			'data' => $data, //自定义
        ];

        return JWT::encode($payload, self::$key, 'HS256');
    }

    public static function verifyToken($token)
    {
        try {
            $decoded = JWT::decode($token, new Key(self::$key, 'HS256'));
            return ['status' => 200,'msg' => 'token有效'];
        } catch (SignatureInvalidException $e) { //签名不正确
			 return ['status' => 204,'msg' => '签名不正确'];
		} catch (BeforeValidException $e) { // 签名在某个时间点之后才能用
			return ['status' => 203,'msg' => 'token未生效'];
		} catch (ExpiredException $e) { // token过期
			return ['status' => 202,'msg' => '登录超时,请重新登录'];

		} catch (Exception $e) { //其他错误
			return ['status' => 500,'msg' => $e->getMessage()];
		}

    }
}

新设置一个公共php文件

// app/controller/apilist.php
<?php
namespace app\controller;

use app\BaseController;
use app\common\JwtAuth;
use think\Request;

class ApiList extends BaseController // 继承BaseController 这个最初文件

{
    public function initialize() // 官方文档说了,这个方法会先调用
    {
		$token = request()->header('Access-Token');
		if (empty($token)) { // JSON_UNESCAPED_UNICODE使中文不转化
			die(json_encode(['status'=>0,'msg'=>'没有token'],JSON_UNESCAPED_UNICODE));
		} else {
			$result = JwtAuth::verifyToken($token);     				
			if($result['status']!=200){ // token正确执行原来接口文件
			    die(json_encode($result,JSON_UNESCAPED_UNICODE));
			}
			
		}
	}  
}

在其他文件中使用

app/contriller/test.php
<?php
namespace app\controller;

class test extends ApiList
{
    public function initialize()
    {
		parent::initialize();//调用父类ApiList的方法
	}
	  public function index(){
		  return 'hello';
	  }
}

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值