<?php
namespace tool\token;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;
class Token
{
public static function toke($id){
$signer = new Sha256();
$time = time();
$token = (new Builder())->issuedBy('http://tp.com') // Configures the issuer (iss claim)
->canOnlyBeUsedBy('http://729.org') // Configures the audience (aud claim)
->identifiedBy(1, 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 + 3600) // Configures the expiration time of the token (exp claim)
->with('uid', $id)->sign($signer,'zhangsan') // Configures a new claim, called "uid"
->getToken();
return (string)$token;
}
public static function getToke($token){
$user_id=null;
$token = (new Parser())->parse((string) $token);
$data = new ValidationData(); // It will use the current time to validate (iat, nbf and exp)
$data->setIssuer('http://tp.com');
$data->setAudience('http://729.org');
$data->setId(1);
if (!$token->validate($data)) {
return 11;
}
$signer = new Sha256();
if (!$token->verify($signer, 'zhangsan')) {
//签名验证失败
return 22;
}
//从token中获取用户id
$user_id = $token->getClaim('uid');
return $user_id;
}
}
composer 代码
composer require lcobucci/jwt 3.3
本篇文章没有封装$_SERVER头部取出部分,必须进行传值。
|