PHP code example of pendant59 / jwt
1. Go to this page and download the library: Download pendant59/jwt library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
pendant59 / jwt example snippets
$config = [
'key' => '2019-pendant59', # 加密Key
'iss' => 'pendant59', # 签发者
'aud' => 'https://github.com/Pendant59', # 接收jwt的用户
'expire' => 6 * 3600, # 过期时间(秒) 默认3小时
'update_limit' => 300, # Token 过期多少秒内可以用于更新 默认300秒
'data' => [ # Token 中包含的加密字段 user_id 为固定值(createJwt()只会选取此处data定义的字段参与加密,如果传入createJwt()的参数中不没有包含此处定义的非固定值键值对,则默认为空)
'user_id',
'nickname'
]
];
$data = [
'user_id' => 1,
'nickname' => 'pendant59',
];
$jwt = new Jwt($config);
# 生成Jwt
$jwt_token = $jwt->createJwt($data);
# 校验Jwt
# 此处校验jwt 不传值的情况下,checkJwt() 会自己取值
# 可以自己从header 头中的 Authorization 中取出jwt字符串并传入checkJwt()
# 如果传值, 以传值为准
if ($jwt_token['code'] == 200) {
# 校验Token
$result = $jwt->checkJwt($jwt_token['data']['token']);
print_r($result);
sleep(5); # 假装客户端 5 秒后 请求更新
# 更新Token
$result = $jwt->updateJwt($jwt_token['data']['token']);
print_r($result);
} else {
print($jwt_token['message']);
}
# 返回值
array(3) {
["code"]=>
int(200)
["message"]=>
string(7) "Success"
["data"]=>
array(3) {
["expire"]=>
int(1555690828)
["user_id"]=>
int(1)
["nickname"]=>
string(9) "pendant59"
}
}
$config = [
'key' => '2019-pendant59', # 加密Key
'iss' => 'pendant59', # 签发者
'aud' => 'https://github.com/Pendant59', # 接收jwt的用户
'expire' => 6 * 3600, # 过期时间(秒) 默认3小时
'update_limit' => 300, # Token 过期多少秒内可以用于更新 默认300秒
'data' => [ # Token 中包含的加密字段 user_id 为必有固定值(createJwt()只会选取此处data定义的字段参与加密,如果传入createJwt()的参数中不没有包含此处定义的非固定值键值对,则默认为空)
'user_id',
'nickname',
'otherKeys'
]
];
$data = [
'user_id' => 1,
'nickname' => 'pendant59',
];
$jwt = (new Jwt())->setConfig($config);
# 生成Jwt
$jwt_token = $jwt->createJwt($data);
# 校验Jwt
# 此处校验jwt 不传值的情况下,checkJwt() 会自己取值
# 可以自己从header 头中的 Authorization 中取出传入checkJwt()
# 如果传值, 以传值为准
if ($jwt_token['code'] == 200) {
# 校验Token
$result = $jwt->checkJwt($jwt_token['data']['token']);
print_r($result);
sleep(5); # 假装客户端 5 秒后 请求更新
# 更新Token
$result = $jwt->updateJwt($jwt_token['data']['token']);
print_r($result);
} else {
print($jwt_token['message']);
}
# 返回值 - 此处$config 定义了多个字段,但是传入createJwt的$data仅包含user_id 所以其他字段默认为空
array(3) {
["code"]=>
int(200)
["message"]=>
string(7) "Success"
["data"]=>
array(4) {
["expire"]=>
int(1555690828)
["user_id"]=>
int(1)
["nickname"]=>
NULL
["otherKeys"]=>
NULL
}
}
# 失败
array(2) {
["code"]=>
int(401)
["message"]=>
string(17) "Token签名错误"
}
# 成功
array(3) {
["code"]=>
int(200)
["message"]=>
string(7) "Success"
["data"]=>
array(3) {
["user_id"]=>
int(1) # user_id 用户标识
["nickname"]=>
NULL # 自定义字段
}
}