<?php
namespace tools\jwt;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\ValidationData;
use Lcobucci\JWT\Signer\Hmac\Sha256;
class Token{
private static $arr=[
'id' => '123456',
'issuer'=>'liyan',
'aud'=>'yan',
'sign'=>'hhh',
'ext'=>3600*24
];
public static function getToken($uid){
$sign = new Sha256();
$time = time();
$token = (new Builder())->issuedBy(self::$arr['issuer']) // Configures the issuer (iss claim)
->canOnlyBeUsedBy(self::$arr['aud']) // Configures the audience (aud claim)
->identifiedBy(self::$arr['id'], true) // Configures the id (jti claim), replicating as a header item
->issuedAt($time) // Configures the time that the token was issue (iat claim)
->canOnlyBeUsedAfter($time - 1) // Configures the time that the token can be used (nbf claim)
->expiresAt($time + self::$arr['ext']) // Configures the expiration time of the token (exp claim)
->with('uid', $uid)->sign($sign,self::$arr['sign']) // Configures a new claim, called "uid"
->getToken(); // Retrieves the generated token
return (string)$token;
}
public static function getRequestToken(){
if(empty($_SERVER['HTTP_AUTHORIZATION'])){
return false;
}else{
$header =$_SERVER['HTTP_AUTHORIZATION'];
$bearer = 'bearer';
return trim(str_ireplace($bearer,'',$header));
}
}
public static function getId($token=null){
$uid = null;
$token = empty($token)?self::getRequestToken():$token;
if(!empty($token)){
$token = (new Parser())->parse((string) $token);
$data = new ValidationData(); // It will use the current time to validate (iat, nbf and exp)
$data->setIssuer(self::$arr['issuer']);
$data->setAudience(self::$arr['aud']);
$data->setId(self::$arr['id']);
if(!$token->validate($data)){
return $uid;
}
$sign = new Sha256();
if(!$token->verify($sign,self::$arr['sign'])){
return $uid;
}
$uid = $token->getClaim('uid');
}
return $uid;
}
}
下载jwt的composer的代码
composer require lcobucci/jwt 3.3