合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
# :-: tp5使用lcobucci/jwt 两种写法的推荐第一种,使用的时3.3版本的 ,第二种写法中有方法将会在v4版本弃用。 用的tp5.1,方法写在extend中的 ,根据自己喜好放。第一种和第二种就是方法有点不一样,具体看 ``` https://github.com/lcobucci/jwt/tree/3.4 ``` 安装 ``` composer require lcobucci/jwt composer require lcobucci/jwt 3.3 // 可以指定版本 在后面加上版本号就行 ``` ___ ``` <?php namespace tools\jwt; use Lcobucci\JWT\Builder; use Lcobucci\JWT\Parser; use Lcobucci\JWT\Signer\Hmac\Sha256; use Lcobucci\JWT\Signer\Key; use Lcobucci\JWT\ValidationData; class Token { private static $_config = [ 'audience' => 'http://www.test.cn',//接收人 'id' => 'qwertyuio',//token的唯一标识,这里只是一个简单示例 'issuer' => 'http://api.test.cn',//签发人 'expire' => 3600*24, //有效期 'secret' =>'thisisasecret', // 秘钥 ]; //生成token public static function getToken($user_id){ //签名对象 $signer = new Sha256(); //获取当前时间戳 $time = time(); //设置签发人、接收人、唯一标识、签发时间、立即生效、过期时间、用户id、签名 $token = (new Builder())->issuedBy(self::$_config['issuer']) ->permittedFor(self::$_config['audience']) ->identifiedBy(self::$_config['id'], true) ->issuedAt($time) ->canOnlyBeUsedAfter($time-1) ->expiresAt($time + self::$_config['expire']) ->withClaim('user_id', $user_id) ->getToken($signer,new Key( self::$_config['secret'])); return (string)$token; } //从请求信息中获取token令牌 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)); } //从token中获取用户id (包含token的校验) public static function getUserId($token = null) { $user_id = null; $token = empty($token)?self::getRequestToken():$token; if (!empty($token)) { //为了注销token 加以下if判断代码 $delete_token = cache('delete_token') ?: []; if(in_array($token, $delete_token)){ //token已被删除(注销) return $user_id; } $token = (new Parser())->parse((string) $token); //验证token $data = new ValidationData(); $data->setIssuer(self::$_config['issuer']);//验证的签发人 $data->setAudience(self::$_config['audience']);//验证的接收人 $data->setId(self::$_config['id']);//验证token标识 if (!$token->validate($data)) { //token验证失败 return $user_id; } //验证签名 $signer = new Sha256(); if (!$token->verify($signer, self::$_config['secret'])) { //签名验证失败 return $user_id; } //从token中获取用户id $user_id = $token->getClaim('user_id'); } return $user_id; } } ``` 第二种 ___ ``` <?php namespace tools\jwt; use Lcobucci\JWT\Builder; use Lcobucci\JWT\Parser; use Lcobucci\JWT\Signer\Hmac\Sha256; use Lcobucci\JWT\ValidationData; class Token { private static $_config = [ 'audience' => 'http://www.test.cn',//接收人 'id' => 'qwertyuio',//token的唯一标识,这里只是一个简单示例 'sign' => 'thisisasign',//签名密钥 'issuer' => 'http://api.test.cn',//签发人 'expire' => 3600*24 //有效期 ]; //生成token public static function getToken($user_id){ //签名对象 $signer = new Sha256(); //获取当前时间戳 $time = time(); //设置签发人、接收人、唯一标识、签发时间、立即生效、过期时间、用户id、签名 $token = (new Builder())->issuedBy(self::$_config['issuer']) ->canOnlyBeUsedBy(self::$_config['audience']) ->identifiedBy(self::$_config['id'], true) ->issuedAt($time) ->canOnlyBeUsedAfter($time-1) ->expiresAt($time + self::$_config['expire']) ->with('user_id', $user_id) ->sign($signer, self::$_config['sign']) ->getToken(); return (string)$token; } //从请求信息中获取token令牌 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)); } //从token中获取用户id (包含token的校验) public static function getUserId($token = null) { $user_id = null; $token = empty($token)?self::getRequestToken():$token; if (!empty($token)) { //为了注销token 加以下if判断代码 $delete_token = cache('delete_token') ?: []; if(in_array($token, $delete_token)){ //token已被删除(注销) return $user_id; } $token = (new Parser())->parse((string) $token); //验证token $data = new ValidationData(); $data->setIssuer(self::$_config['issuer']);//验证的签发人 $data->setAudience(self::$_config['audience']);//验证的接收人 $data->setId(self::$_config['id']);//验证token标识 if (!$token->validate($data)) { //token验证失败 return $user_id; } //验证签名 $signer = new Sha256(); if (!$token->verify($signer, self::$_config['sign'])) { //签名验证失败 return $user_id; } //从token中获取用户id $user_id = $token->getClaim('user_id'); } return $user_id; } } ``` ## 基类实例写法 ___ ``` <?php namespace app\api\controller; use think\Controller; use think\Facade\Request; use tools\jwt\Token; class Base extends Controller { protected $uid; protected static $noLogin=['index/test','index/login']; //不需要登录的接口 public function initialize() { parent::initialize(); // TODO: Change the autogenerated stub header("Access-Control-Allow-Origin:*"); header("Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE"); header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding"); try{ $url=strtolower(Request::controller()).'/'.Request::action(); if(!in_array($url,self::$noLogin)){ $user_id=Token::getUserId(); if(empty($user_id)){ echo json(['msg'=>'token不能为空','code'=>403])->send();die; } } // 可以把uid放请求里面 还可以丢属性 $this->uid=$user_id); $this->request->get('user_id',$user_id); $this->request->post('user_id',$user_id); }catch (\Exception $e){ echo json(['msg'=>'token验证失败','code'=>403])->send();die; } } } ```