全名(JSON Web Tokens)
讓網絡進行安全傳遞
通常被用來作身分驗證、授權
📌 $key = "your_key";
📌 function create($payload, $key)
{
$header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
$header = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
$payload = json_encode($payload);
$payload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
$signature = hash_hmac('sha256',$header . "." . $payload, $key, true);
$signature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
return $header . "." . $payload . "." . $signature;
}
📌 function verify($token, $key)
{
list($header, $payload, $signature) = explode('.', $token);
$valid = hash_hmac('sha256', $header . "." . $payload, $secret_key, true);
$valid = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($valid));
return $signature === $valid;
}
📌 $payload = array(
"user_id" => 123456,
"username" => “test"
);
$jwt = createToken($payload, $key);
$isValid = verifyToken($jwt, $key);
if ($isValid)
{
$decoded = json_decode(base64_decode(explode('.', $jwt)[1]));
echo "Token is valid. User ID: " . $decoded->user_id;
}
else
{
echo "Token is invalid.";
}
這樣我們就實現了一個簡單的JWT