为什么openssl_verify()无法验证我的JWT令牌签名?

时间:2016-12-19 03:55:40

标签: php jwt php-openssl

代码:

$token = $request->getQueryParams();
$jwt_access_token = $token['access_token'];

$separator = '.';

list($header, $payload, $signature) = explode($separator, $jwt_access_token);

$decoded_signature = base64_decode($signature);

$payload_to_verify = utf8_decode($header . $separator . $payload);

$public_key = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/pubkey.pem');

$verified = openssl_verify($payload_to_verify, $decoded_signature, $public_key, OPENSSL_ALGO_SHA256);

示例访问令牌:

eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpZCI6IjU0YmEzYmQwZDRkYzAxYmZhNmJjYjdjYTIwOTQwY2YzY2NmM2EyNjQiLCJqdGkiOiI1NGJhM2JkMGQ0ZGMwMWJmYTZiY2I3Y2EyMDk0MGNmM2NjZjNhMjY0IiwiaXNzIjoiIiwiYXVkIjoidGVzdGNsaWVudCIsInN1YiI6InNhbGxlIiwiZXhwIjoxNDgyMTIyODY4LCJpYXQiOjE0ODIxMTkyNjgsInRva2VuX3R5cGUiOiJiZWFyZXIiLCJzY29wZSI6bnVsbH0.q-xwz16YbUiaDzdeiNBoaeZIYNx8G6HXLZRMJjpiezotq0nICTokVxuf3OUur6433MhT6wVCUENUeuJfuvLg3wKZWHfXSoTMG77Gkv1Wart6hlIPFqyZ13gyTzquaKRRDoRD9WSBcKXfTF6V59cWHrwAM5nRIQeOzBdYXZPwnV-9RhXUpjUhJ0LKRJsDZ5EwJUFsIDb7oZ70b3uLJqa79h42Dc5mQWj75uIo8mVCmH9N1BPJRn-Hb9ttgpu2oRgDOqsm4zdBz2CfSkPiHa-j6qKEWHocyLQBZ8XLxyvFSAFVIwqv4OVCBHanzbkfY-ZKkKh1THeyiIcrB9ed6vwzRg

公钥:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs3k2ZkpYqCX94B+qC2yc
4atWx+C5d7kFQAgBrbv5gfFuIST0DLt5lvv0OZZI57+ydNXb2G/jyOJPH3ll2mHS
Z+PKAo9aQoL5iYIjz+yYp2Im51LBh4e0Kt1RSjuy4M5RI1JVSsM9rt3NoLMzehv8
57g+uv1T177cJabDvKeqWdD0qR4N7PE/nV0Hrumz5kP4EnYhN0A2wjbXyyyllxhL
nr3Wqii0XJxBF3AwLUlqP1NYhm2wYq0CTjQrgv3/9WCvr4fSzBitzQAP6ZIFRHO3
F8EIaK6r6cDiP2ABmtTrmPAj3ZpqGVBPnvY9yVrqUS0pMxjvvesJiPd2jGrjLQFN
LQIDAQAB
-----END PUBLIC KEY-----

我无法让openssl_verify()函数返回1.它总是返回0(它无法验证令牌)。我不明白为什么。有谁能指出我正确的方向?

1 个答案:

答案 0 :(得分:3)

失败是因为JWS部分不是Base64编码,而是Base64 Url安全编码。

错误来自

  

$ decoding_signature = base64_decode($ signature);

应该是

  

$ decoding_signature = base64_decode(strtr($ signature,' - _','+ /'));