使用PHP原生函数验证jwt token signature
Title: How to verify json web token (jwt) signature by using PHP native functions?
class Jsonwebtoken()
{
public static function verify(string $token)
{
/**应该学习firebase jwt lib,做大量错误处理 */
$tokenParts = explode('.', $token);
list($headb64, $bodyb64, $cryptob64) = $tokenParts;
/** both work */
$pubKey = openssl_get_publickey('file://'.__DIR__.'/jwtRS256.key.pub');
// $pubKey = file_get_contents(__DIR__.'/jwtRS256.key.pub');
$signature = self::urlsafeB64Decode($cryptob64); // from Google Firebase JWT lib
$isVerified = openssl_verify("$headb64.$bodyb64", $signature, $pubKey, OPENSSL_ALGO_SHA256);
return $isVerified === 1; // openssl_verify return value is int
}
/**
* Decode a string with URL-safe Base64.
*
* @param string $input A Base64 encoded string
*
* @return string A decoded string
*/
public static function urlsafeB64Decode(string $input)
{
$remainder = strlen($input) % 4;
if ($remainder) {
$padlen = 4 - $remainder;
$input .= str_repeat('=', $padlen);
}
return base64_decode(strtr($input, '-_', '+/'));
}
}