Skip to content

Commit aa6419a

Browse files
authored
Updates JWT::verify to handle openssl errors (#159)
1 parent 0f8f85a commit aa6419a

File tree

2 files changed

+36
-7
lines changed

2 files changed

+36
-7
lines changed

src/JWT.php

+9-5
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ public static function decode($jwt, $key, $allowed_algs = array())
8888
throw new UnexpectedValueException('Invalid claims encoding');
8989
}
9090
$sig = static::urlsafeB64Decode($cryptob64);
91-
91+
9292
if (empty($header->alg)) {
9393
throw new UnexpectedValueException('Empty algorithm');
9494
}
@@ -230,11 +230,15 @@ private static function verify($msg, $signature, $key, $alg)
230230
switch($function) {
231231
case 'openssl':
232232
$success = openssl_verify($msg, $signature, $key, $algorithm);
233-
if (!$success) {
234-
throw new DomainException("OpenSSL unable to verify data: " . openssl_error_string());
235-
} else {
236-
return $signature;
233+
if ($success === 1) {
234+
return true;
235+
} elseif ($success === 0) {
236+
return false;
237237
}
238+
// returns 1 on success, 0 on failure, -1 on error.
239+
throw new DomainException(
240+
'OpenSSL error: ' . openssl_error_string()
241+
);
238242
case 'hash_hmac':
239243
default:
240244
$hash = hash_hmac($algorithm, $msg, $key, true);

tests/JWTTest.php

+27-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
11
<?php
2-
use \Firebase\JWT\JWT;
2+
namespace Firebase\JWT;
3+
4+
use ArrayObject;
5+
use PHPUnit_Framework_TestCase;
36

47
class JWTTest extends PHPUnit_Framework_TestCase
58
{
9+
public static $opensslVerifyReturnValue;
10+
611
public function testEncodeDecode()
712
{
813
$msg = JWT::encode('abc', 'my_key');
@@ -253,12 +258,32 @@ public function testMissingAlgorithm()
253258
public function testAdditionalHeaders()
254259
{
255260
$msg = JWT::encode('abc', 'my_key', 'HS256', null, array('cty' => 'test-eit;v=1'));
256-
$this->assertEquals(JWT::decode($msg, 'my_key', array('HS256')), 'abc');
261+
$this->assertEquals(JWT::decode($msg, 'my_key', array('HS256')), 'abc');
257262
}
258263

259264
public function testInvalidSegmentCount()
260265
{
261266
$this->setExpectedException('UnexpectedValueException');
262267
JWT::decode('brokenheader.brokenbody', 'my_key', array('HS256'));
263268
}
269+
270+
public function testVerifyError()
271+
{
272+
$this->setExpectedException('DomainException');
273+
$pkey = openssl_pkey_new();
274+
$msg = JWT::encode('abc', $pkey, 'RS256');
275+
self::$opensslVerifyReturnValue = -1;
276+
JWT::decode($msg, $pkey, array('RS256'));
277+
}
278+
}
279+
280+
/*
281+
* Allows the testing of openssl_verify with an error return value
282+
*/
283+
function openssl_verify($msg, $signature, $key, $algorithm)
284+
{
285+
if (null !== JWTTest::$opensslVerifyReturnValue) {
286+
return JWTTest::$opensslVerifyReturnValue;
287+
}
288+
return \openssl_verify($msg, $signature, $key, $algorithm);
264289
}

0 commit comments

Comments
 (0)