Skip to content

improved code style #30

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 47 additions & 24 deletions src/JWT.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,29 @@

namespace Ahc\Jwt;

use function array_merge;
use function base64_decode;
use function base64_encode;
use function explode;
use function hash_equals;
use function hash_hmac;
use function is_array;
use function json_decode;
use function json_encode;
use function openssl_pkey_get_details;
use function openssl_sign;
use function openssl_verify;
use function reset;
use function rtrim;
use function strtr;
use function substr_count;
use function time;
use stdClass;
use const JSON_UNESCAPED_SLASHES;
use const OPENSSL_ALGO_SHA256;
use const OPENSSL_ALGO_SHA384;
use const OPENSSL_ALGO_SHA512;

/**
* JSON Web Token (JWT) implementation in PHP5.5+.
*
Expand Down Expand Up @@ -43,9 +66,9 @@ class JWT
'HS256' => 'sha256',
'HS384' => 'sha384',
'HS512' => 'sha512',
'RS256' => \OPENSSL_ALGO_SHA256,
'RS384' => \OPENSSL_ALGO_SHA384,
'RS512' => \OPENSSL_ALGO_SHA512,
'RS256' => OPENSSL_ALGO_SHA256,
'RS384' => OPENSSL_ALGO_SHA384,
'RS512' => OPENSSL_ALGO_SHA512,
];

/** @var string|resource The signature key. */
Expand All @@ -55,7 +78,7 @@ class JWT
protected $keys = [];

/** @var int|null Use setTestTimestamp() to set custom value for time(). Useful for testability. */
protected $timestamp = null;
protected $timestamp;

/** @var string The JWT signing algorithm. Defaults to HS256. */
protected $algo = 'HS256';
Expand Down Expand Up @@ -88,9 +111,9 @@ public function __construct(
) {
$this->validateConfig($key, $algo, $maxAge, $leeway);

if (\is_array($key)) {
if (is_array($key)) {
$this->registerKeys($key);
$key = \reset($key); // use first one!
$key = reset($key); // use first one!
}

$this->key = $key;
Expand All @@ -109,7 +132,7 @@ public function __construct(
*/
public function registerKeys(array $keys): self
{
$this->keys = \array_merge($this->keys, $keys);
$this->keys = array_merge($this->keys, $keys);

return $this;
}
Expand All @@ -129,7 +152,7 @@ public function encode(array $payload, array $header = []): string
$this->validateKid($header);

if (!isset($payload['iat']) && !isset($payload['exp'])) {
$payload['exp'] = ($this->timestamp ?: \time()) + $this->maxAge;
$payload['exp'] = ($this->timestamp ?: time()) + $this->maxAge;
}

$header = $this->urlSafeEncode($header);
Expand All @@ -151,11 +174,11 @@ public function encode(array $payload, array $header = []): string
*/
public function decode(string $token, bool $verify = true): array
{
if (\substr_count($token, '.') < 2) {
if (substr_count($token, '.') < 2) {
throw new JWTException('Invalid token: Incomplete segments', static::ERROR_TOKEN_INVALID);
}

$token = \explode('.', $token, 3);
$token = explode('.', $token, 3);
if (!$verify) {
return (array) $this->urlSafeDecode($token[1]);
}
Expand Down Expand Up @@ -196,13 +219,13 @@ public function setTestTimestamp(int $timestamp = null): self
protected function sign(string $input): string
{
// HMAC SHA.
if (\substr($this->algo, 0, 2) === 'HS') {
return \hash_hmac($this->algos[$this->algo], $input, $this->key, true);
if (strpos($this->algo, 'HS') === 0) {
return hash_hmac($this->algos[$this->algo], $input, $this->key, true);
}

$this->validateKey();

\openssl_sign($input, $signature, $this->key, $this->algos[$this->algo]);
openssl_sign($input, $signature, $this->key, $this->algos[$this->algo]);

return $signature;
}
Expand All @@ -222,15 +245,15 @@ protected function verify(string $input, string $signature): bool
$algo = $this->algos[$this->algo];

// HMAC SHA.
if (\substr($this->algo, 0, 2) === 'HS') {
return \hash_equals($this->urlSafeEncode(\hash_hmac($algo, $input, $this->key, true)), $signature);
if (strpos($this->algo, 'HS') === 0) {
return hash_equals($this->urlSafeEncode(hash_hmac($algo, $input, $this->key, true)), $signature);
}

$this->validateKey();

$pubKey = \openssl_pkey_get_details($this->key)['key'];
$pubKey = openssl_pkey_get_details($this->key)['key'];

return \openssl_verify($input, $this->urlSafeDecode($signature, false), $pubKey, $algo) === 1;
return openssl_verify($input, $this->urlSafeDecode($signature, false), $pubKey, $algo) === 1;
}

/**
Expand All @@ -246,12 +269,12 @@ protected function verify(string $input, string $signature): bool
*/
protected function urlSafeEncode($data): string
{
if (\is_array($data)) {
$data = \json_encode($data, \JSON_UNESCAPED_SLASHES);
if (is_array($data)) {
$data = json_encode($data, JSON_UNESCAPED_SLASHES);
$this->validateLastJson();
}

return \rtrim(\strtr(\base64_encode($data), '+/', '-_'), '=');
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

/**
Expand All @@ -260,17 +283,17 @@ protected function urlSafeEncode($data): string
* @param array|string $data
* @param bool $asJson Whether to parse as JSON (defaults to true).
*
* @throws JWTException When JSON encode fails.
* @return array|stdClass|string
*@throws JWTException When JSON encode fails.
*
* @return array|\stdClass|string
*/
protected function urlSafeDecode($data, bool $asJson = true)
{
if (!$asJson) {
return \base64_decode(\strtr($data, '-_', '+/'));
return base64_decode(strtr($data, '-_', '+/'));
}

$data = \json_decode(\base64_decode(\strtr($data, '-_', '+/')));
$data = json_decode(base64_decode(strtr($data, '-_', '+/')), false);
$this->validateLastJson();

return $data;
Expand Down
4 changes: 3 additions & 1 deletion src/JWTException.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@

namespace Ahc\Jwt;

class JWTException extends \InvalidArgumentException
use InvalidArgumentException;

class JWTException extends InvalidArgumentException
{
// ;)
}
35 changes: 24 additions & 11 deletions src/ValidatesJWT.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,19 @@

namespace Ahc\Jwt;

use OpenSSLAsymmetricKey;
use OpenSSLCertificate;
use OpenSSLCertificateSigningRequest;
use function is_resource;
use function is_string;
use function json_last_error;
use function json_last_error_msg;
use function openssl_get_privatekey;
use function substr;
use function time;
use const JSON_ERROR_NONE;
use const PHP_VERSION_ID;

/**
* JSON Web Token (JWT) implementation in PHP7.
*
Expand Down Expand Up @@ -82,7 +95,7 @@ protected function validateKid(array $header)
*/
protected function validateTimestamps(array $payload)
{
$timestamp = $this->timestamp ?: \time();
$timestamp = $this->timestamp ?: time();
$checks = [
['exp', $this->leeway /* */ , static::ERROR_TOKEN_EXPIRED, 'Expired'],
['iat', $this->maxAge - $this->leeway, static::ERROR_TOKEN_EXPIRED, 'Expired'],
Expand All @@ -106,22 +119,22 @@ protected function validateTimestamps(array $payload)
*/
protected function validateKey()
{
if (\is_string($key = $this->key)) {
if (\substr($key, 0, 7) !== 'file://') {
if (is_string($key = $this->key)) {
if (strpos($key, 'file://') !== 0) {
$key = 'file://' . $key;
}

$this->key = \openssl_get_privatekey($key, $this->passphrase ?: '');
$this->key = openssl_get_privatekey($key, $this->passphrase ?: '');
}

if (\PHP_VERSION_ID < 80000 && !\is_resource($this->key)) {
if (PHP_VERSION_ID < 80000 && !is_resource($this->key)) {
throw new JWTException('Invalid key: Should be resource of private key', static::ERROR_KEY_INVALID);
}

if (\PHP_VERSION_ID > 80000 && !(
$this->key instanceof \OpenSSLAsymmetricKey
|| $this->key instanceof \OpenSSLCertificate
|| $this->key instanceof \OpenSSLCertificateSigningRequest
if (PHP_VERSION_ID > 80000 && !(
$this->key instanceof OpenSSLAsymmetricKey
|| $this->key instanceof OpenSSLCertificate
|| $this->key instanceof OpenSSLCertificateSigningRequest
)) {
throw new JWTException('Invalid key: Should be resource of private key', static::ERROR_KEY_INVALID);
}
Expand All @@ -132,10 +145,10 @@ protected function validateKey()
*/
protected function validateLastJson()
{
if (\JSON_ERROR_NONE === \json_last_error()) {
if (JSON_ERROR_NONE === json_last_error()) {
return;
}

throw new JWTException('JSON failed: ' . \json_last_error_msg(), static::ERROR_JSON_FAILED);
throw new JWTException('JSON failed: ' . json_last_error_msg(), static::ERROR_JSON_FAILED);
}
}