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類庫,網上自行下載


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM