token验证中间件+token验证和颁发

token的颁发和验证

<?php
namespace app\admin\business;
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 static 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
        );
        return JWTUtil::encode($token,$key);
    }

    /**
     * 验证token
     * @return \think\response\Json
     */
    public static function verifyjwt($jwt)
    {
//        $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,"用户不存在");
                throw new ExpiredException('用户不存在');
            }
//            return show(0,"ok");
            return 'ok';

        }catch (ExpiredException $e){
//            return show(0,"token过期");
            throw new ExpiredException('token过期');
        }catch (\Exception $e){
//            return show(0,$e->getMessage());
            throw new ExpiredException($e->getMessage());
        }

    }

   
}

token的获取

public static function getRequestToken()
    {
        if (empty($_SERVER['HTTP_AUTHORIZATION'])){
            return false;
        }
        $header = $_SERVER['HTTP_AUTHORIZATION'];
        $method = 'bearer';

        return trim(str_ireplace($method,'',$header));
    }

注意:伪静态处需要补充

<IfModule mod_rewrite.c>
  Options +FollowSymlinks -Multiviews
  RewriteEngine On
  #增加下面这项
  SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0
</IfModule>

中间件:

public function handle($request, \Closure $next)
    {
        //
        $token = JWT::getRequestToken();

        try {
            JWT::verifyjwt($token);
        }catch (ExpiredException $exception){
            return fail($exception->getMessage());
        }
        return $next($request);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值