composer下載安裝JWT
composer require lcobucci/jwt 3.3
在extend/tools/jwt創建Token.php,在文件夾中寫入
namespace tools\jwt;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;
class Token
{
public static function createToken($uid = null)
{
$signer = new Sha256();//加密規則
$time = time();//當前時間
$token = (new Builder())
->issuedBy('teacher')//簽發人
->canOnlyBeUsedBy('student')//接收人
->identifiedBy('MarsLei', true) //標題id
->issuedAt($time)//發出令牌的時間
->canOnlyBeUsedAfter($time) //生效時間(即時生效)
->expiresAt($time + 3600) //過期時間
->with('uid', $uid) //用戶id
->sign($signer, 'my') //簽名
->getToken(); //得到token
return (string)$token;
}
public static function verifyToken($token = null)
{
//檢測是否接收到了token
if (empty($token)) {
return 0;
}
//轉化為可以驗證的token
$token = (new Parser())->parse((string)$token);
//驗證基本設置
$data = new ValidationData();
$data->setIssuer('teacher');
$data->setAudience('student');
$data->setId('MarsLei');
if (!$token->validate($data)) {
return 0;
}
//驗證簽名
$signer = new Sha256();
if (!$token->verify($signer, 'my')) {
return 0;
}
//驗證通過,返回用戶id
return $token->getClaim('uid');
}
}
調用Token
//生成Token
$token=Token::createToken($id);
//驗證Token
$res=Token::verifyToken($token);
if ($res==0){
$this->error('Token令牌失效','test/Login/login');
}