thinkphp应用中 JWT token的加密解密

实现token  方法:

private function xxxx ($entity) {

$tokenId = base64_encode(\Org\Util\Strings::uuid());
$issuedAt = time();
$notBefore = $issuedAt;
$expire = $notBefore + 86400;
$serverName = getHost();
//载荷
$payload = [
'iat' => $issuedAt,
'jti' => $tokenId,
'iss' => $serverName,
'nbf' => $notBefore,
'exp' => $expire,
'data' => [
'id' => $entity['id'],
'account' => $entity['account'],
'nickname' => $entity['nickname'],
'phone' => $entity['phone'],
'face' => $entity['face']
]
];
$key = C('API_AUTH_KEY');
$secretKey = base64_encode($key);
$token = JWT::encode($payload, $secretKey);
return $token;

}

其他地方可直接调用:$token = $this->xxxx ($userInfo);

 

解密很简单:

1、如果是直接拿到token参数:  

$key = base64_encode(C('API_AUTH_KEY'));
$payload = JWT::decode($token, $key, array('HS256'));
$userInfo = object_array($payload->data);

2、通过请求头获取 token信息

$authinfo = apache_request_headers();
$key = base64_encode(C('API_AUTH_KEY'));
$payload = JWT::decode($authinfo['Authorization'], $key, array('HS256'));
$this->userInfo = object_array($payload->data);

JWT类库,网上自行下载

posted @ 2018-08-28 21:35  Ⅲ人刑  阅读(3735)  评论(0编辑  收藏  举报