thinkphp3 php jwt,ThinkPHP5 使用 JWT 进行加密

8745649e6e74bac7aaf6343ef03ec05d.png

- 使用 Composer安装此扩展

- 代码示例<?php

/**

* [InterCommon-接口公用]

* @Author RainCyan

* @DateTime 2019-08-12T16:38:08+0800

*/

namespace app\hladmin\controller;

use think\Controller;

use \Firebase\JWT\JWT;

class InterCommonController extends Controller {

private $key = "123456789";

//客户端获取TOKEN

public function _getJwtToken(){

try {

$string = input("string");

if (empty($string)) {

throw new \Exception("请传入需要加密string", -105);

}

$jwt = $this->_setJwtToken($string);

throw new \Exception($jwt, 200);

} catch (\Exception $e) {

return json(array("code"=>$e->getCode(), "msg"=>$e->getMessage()));

}

}

//签发token

private function _setJwtToken($string=""){

$key = $this->key;

$time = time();

$token = array(

"iss" => "http://ml.cn",

"aud" => "http://ml.cn",

'iat' => $time, //签发时间

'nbf' => $time + 10, //在什么时间之后该jwt才可用

'exp' => $time + 10, //过期时间

"string" => $string

);

$jwt = JWT::encode($token, $key);

return $jwt;

}

//解析token

protected function _readJwtToken($jwt){

$key = $this->key;

try {

JWT::$leeway = 60;//当前时间减去60,把时间留点余地

$decoded = JWT::decode($jwt, $key, ['HS256']); //HS256方式,这里要和签发的时候对应

$arr = (array)$decoded;

return json_msg(200, "success", $arr);

} catch(\Firebase\JWT\SignatureInvalidException $e) { //签名不正确

return json_msg(-101, $e->getMessage());

}catch(\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用

return json_msg(-102, $e->getMessage());

}catch(\Firebase\JWT\ExpiredException $e) { // token过期

return json_msg(-103, $e->getMessage());

}catch(Exception $e) { //其他错误

return json_msg(-104, $e->getMessage());

}

}

//测试解析

public function _writeJwtToken($token){

halt($this->_readJwtToken($token));

}

}

?>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值