You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
64 lines
2.0 KiB
64 lines
2.0 KiB
![]()
2 months ago
|
<?php
|
||
|
|
||
|
use Firebase\JWT\JWT;
|
||
|
use Firebase\JWT\Key;
|
||
|
use Firebase\JWT\ExpiredException;
|
||
|
|
||
|
include_once(SERVER_ROOT."/model/mBase.php");
|
||
|
|
||
|
class mJwt extends mBase {
|
||
|
|
||
|
public $alg='HS256';
|
||
|
public $expire=86400;
|
||
|
public $iss='';
|
||
|
public $sub='';
|
||
|
public $aud='';
|
||
|
public $jti='';
|
||
|
|
||
|
private function getJwtKey() {
|
||
|
return JWT_KEY;
|
||
|
}
|
||
|
|
||
|
// iss: jwt签发者
|
||
|
// sub: jwt所面向的用户
|
||
|
// aud: 接收jwt的一方
|
||
|
// exp: jwt的过期时间,这个过期时间必须要大于签发时间
|
||
|
// nbf: 定义在什么时间之前,该jwt都是不可用的.
|
||
|
// iat: jwt的签发时间
|
||
|
// jti: jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击
|
||
|
public function getJwtEncode($data=array()) {
|
||
|
include_once(SERVER_ROOT."/vendor/autoload.php");
|
||
|
|
||
|
$payload = array();
|
||
|
$payload['iat'] = time();
|
||
|
$payload['nbf'] = time();
|
||
|
if ($this->expire) $payload['exp'] = time()+$this->expire;
|
||
|
if ($this->iss) $payload['iss'] = $this->iss;
|
||
|
if ($this->sub) $payload['sub'] = $this->sub;
|
||
|
if ($this->aud) $payload['aud'] = $this->aud;
|
||
|
if ($this->jti) $payload['jti'] = $this->jti;
|
||
|
if ($data) $payload = array_merge($payload, $data);
|
||
|
|
||
|
return JWT::encode($payload, $this->getJwtKey(), $this->alg);
|
||
|
}
|
||
|
|
||
|
public function getJwtDecode($jwt) {
|
||
|
include_once(SERVER_ROOT."/vendor/autoload.php");
|
||
|
|
||
|
$keyOrKeyArray = new Key($this->getJwtKey(), $this->alg);
|
||
|
|
||
|
JWT::$leeway = 60; // $leeway in seconds
|
||
|
try {
|
||
|
return (array)JWT::decode($jwt, $keyOrKeyArray);
|
||
|
} catch (ExpiredException $e) {
|
||
|
// 当JWT过期时,你可以选择重新登录或者其他逻辑处理
|
||
|
$this->setError("token过期");
|
||
|
return false;
|
||
|
} catch (Exception $e) {
|
||
|
// 其他JWT相关的异常处理
|
||
|
$this->setError("token无效");
|
||
|
return false;
|
||
|
}
|
||
|
}
|
||
|
}
|