安装
|
1
|
composer require lcobucci/jwt 3.3 |
封装
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
<?phpnamespace tools\jwt;use Lcobucci\JWT\Builder;use Lcobucci\JWT\Signer\Key;use Lcobucci\JWT\Signer\Hmac\Sha256;use Lcobucci\JWT\ValidationData;use Lcobucci\JWT\Parser;class Token{ static private $_config=[ 'audience' => 'http://127.0.0.1/token',//接收人 'id' => '1806',//token的唯一标识,这里只是一个简单示例 'sign' => 'Mr.cao',//签名密钥 'issuer' => 'http://127.0.0.1/user_id',//签发人 'expire' => 3600*2 //有效期 ]; //生成token static public function getToken($k,$v) { $signer = new Sha256(); $time = time(); $token = (new Builder())->issuedBy(self::$_config['issuer']) // 签发人 ->permittedFor(self::$_config['audience']) // 接收人 ->identifiedBy(self::$_config['id'], true) // 唯一标识 可以自己写,也可以随机生成 ->issuedAt($time) // 签发时间 ->canOnlyBeUsedAfter($time - 1) // 生效时间 ->expiresAt($time + 3600) // 过期时间 ->withClaim($k, $v) // 用户id ->getToken($signer, new Key(self::$_config['sign'])); // 生成token return (string)$token; } //验证token static public function verifyToken($token) { $signer = new Sha256(); $token = (new Parser())->parse((string) $token); $data = new ValidationData(); //验证签发人 $data->setIssuer(self::$_config['issuer']); //验证接收人 $data->setAudience(self::$_config['audience']); //验证唯一表示 $data->setId(self::$_config['id']); //签发人 和上述验证 if($token->verify($signer, self::$_config['sign']) && $token->validate($data)){ return true; }else{ return false; } } //从token中获取信息 static public function getTokenMessege($token) { $res = self::verifyToken($token); if (!$res){ return '无效的token'; } $token = (new Parser())->parse((string)$token); return $token->getClaims(); }} |
使用
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
use tools\jwt\Token; //封装命名空间\类//生成tokenpublic function getToken(){ $token = Token::getToken(5); return $token;}//测试tokenpublic function testToken(Request $request){ //接收token $token = $request->param('token'); $data = Token::getTokenMessege($token); return $data;} |


还没有内容
评论已关闭!