Skip to content

Commit

Permalink
Updates JWT::verify to handle openssl errors
Browse files Browse the repository at this point in the history
  • Loading branch information
bshaffer committed Feb 3, 2017
1 parent 3aa3d97 commit f61b4f2
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
14 changes: 9 additions & 5 deletions src/JWT.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public static function decode($jwt, $key, $allowed_algs = array())
throw new UnexpectedValueException('Invalid claims encoding');
}
$sig = static::urlsafeB64Decode($cryptob64);

if (empty($header->alg)) {
throw new UnexpectedValueException('Empty algorithm');
}
Expand Down Expand Up @@ -225,11 +225,15 @@ private static function verify($msg, $signature, $key, $alg)
switch($function) {
case 'openssl':
$success = openssl_verify($msg, $signature, $key, $algorithm);
if (!$success) {
throw new DomainException("OpenSSL unable to verify data: " . openssl_error_string());
} else {
return $signature;
if ($success === 1) {
return true;
} elseif ($success === 0) {
return false;
}
// returns 1 on success, 0 on failure, -1 on error.
throw new DomainException(
'OpenSSL error: ' . openssl_error_string()
);
case 'hash_hmac':
default:
$hash = hash_hmac($algorithm, $msg, $key, true);
Expand Down
29 changes: 27 additions & 2 deletions tests/JWTTest.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
<?php
use \Firebase\JWT\JWT;
namespace Firebase\JWT;

use ArrayObject;
use PHPUnit_Framework_TestCase;

class JWTTest extends PHPUnit_Framework_TestCase
{
public static $opensslVerifyReturnValue;

public function testEncodeDecode()
{
$msg = JWT::encode('abc', 'my_key');
Expand Down Expand Up @@ -253,12 +258,32 @@ public function testMissingAlgorithm()
public function testAdditionalHeaders()
{
$msg = JWT::encode('abc', 'my_key', 'HS256', null, array('cty' => 'test-eit;v=1'));
$this->assertEquals(JWT::decode($msg, 'my_key', array('HS256')), 'abc');
$this->assertEquals(JWT::decode($msg, 'my_key', array('HS256')), 'abc');
}

public function testInvalidSegmentCount()
{
$this->setExpectedException('UnexpectedValueException');
JWT::decode('brokenheader.brokenbody', 'my_key', array('HS256'));
}

public function testVerifyError()
{
$this->setExpectedException('DomainException');
$pkey = openssl_pkey_new();
$msg = JWT::encode('abc', $pkey, 'RS256');
self::$opensslVerifyReturnValue = -1;
JWT::decode($msg, $pkey, array('RS256'));
}
}

/*
* Allows the testing of openssl_verify with an error return value
*/
function openssl_verify($msg, $signature, $key, $algorithm)
{
if (null !== JWTTest::$opensslVerifyReturnValue) {
return JWTTest::$opensslVerifyReturnValue;
}
return \openssl_verify($msg, $signature, $key, $algorithm);
}

0 comments on commit f61b4f2

Please sign in to comment.