Replace emarref/jwt with lcobucci/jwt

Refactor all JWT-related components
Replace RS256 with ES256 as a preferred JWT algorithm
This commit is contained in:
ErickSkrauch
2019-08-01 12:17:12 +03:00
parent 4c2a9cc172
commit 45c2ed601d
47 changed files with 805 additions and 621 deletions

View File

@@ -1,60 +0,0 @@
<?php
namespace api\components\User;
use common\models\Account;
use common\models\AccountSession;
use Emarref\Jwt\Claim\Expiration;
class AuthenticationResult {
/**
* @var Account
*/
private $account;
/**
* @var string
*/
private $jwt;
/**
* @var AccountSession|null
*/
private $session;
public function __construct(Account $account, string $jwt, ?AccountSession $session) {
$this->account = $account;
$this->jwt = $jwt;
$this->session = $session;
}
public function getAccount(): Account {
return $this->account;
}
public function getJwt(): string {
return $this->jwt;
}
public function getSession(): ?AccountSession {
return $this->session;
}
public function getAsResponse() {
$token = (new Jwt())->deserialize($this->getJwt());
/** @noinspection NullPointerExceptionInspection */
$response = [
'access_token' => $this->getJwt(),
'expires_in' => $token->getPayload()->findClaimByName(Expiration::NAME)->getValue() - time(),
];
$session = $this->getSession();
if ($session !== null) {
$response['refresh_token'] = $session->refresh_token;
}
return $response;
}
}

View File

@@ -3,28 +3,11 @@ declare(strict_types=1);
namespace api\components\User;
use api\exceptions\ThisShouldNotHappenException;
use common\models\Account;
use common\models\AccountSession;
use common\rbac\Roles as R;
use DateInterval;
use DateTime;
use Emarref\Jwt\Algorithm\AlgorithmInterface;
use Emarref\Jwt\Algorithm\Hs256;
use Emarref\Jwt\Algorithm\Rs256;
use Emarref\Jwt\Claim;
use Emarref\Jwt\Encryption\Asymmetric as AsymmetricEncryption;
use Emarref\Jwt\Encryption\EncryptionInterface;
use Emarref\Jwt\Encryption\Factory as EncryptionFactory;
use Emarref\Jwt\Exception\VerificationException;
use Emarref\Jwt\HeaderParameter\Custom;
use Emarref\Jwt\Token;
use Emarref\Jwt\Verification\Context as VerificationContext;
use Exception;
use InvalidArgumentException;
use Webmozart\Assert\Assert;
use Yii;
use yii\base\InvalidConfigException;
use yii\web\UnauthorizedHttpException;
use yii\web\User as YiiUserComponent;
@@ -41,52 +24,29 @@ class Component extends YiiUserComponent {
public const KEEP_SITE_SESSIONS = 2;
public const KEEP_CURRENT_SESSION = 4;
public const JWT_SUBJECT_PREFIX = 'ely|';
private const LATEST_JWT_VERSION = 1;
public $enableSession = false;
public $loginUrl = null;
public $identityClass = Identity::class;
public $secret;
public $publicKeyPath;
public $privateKeyPath;
public $expirationTimeout = 'PT1H';
public $sessionTimeout = 'P7D';
private $publicKey;
private $privateKey;
/**
* @var Token[]
* We don't use the standard web authorization mechanism via cookies.
* Therefore, only one static method findIdentityByAccessToken is used from
* the whole IdentityInterface interface, which is implemented in the factory.
* The method only used from loginByAccessToken from base class.
*
* @var string
*/
private static $parsedTokensCache = [];
public function init() {
parent::init();
Assert::notEmpty($this->secret, 'secret must be specified');
Assert::notEmpty($this->publicKeyPath, 'public key path must be specified');
Assert::notEmpty($this->privateKeyPath, 'private key path must be specified');
}
public $identityClass = IdentityFactory::class;
public function findIdentityByAccessToken($accessToken): ?IdentityInterface {
if (empty($accessToken)) {
return null;
}
/** @var \api\components\User\IdentityInterface|string $identityClass */
$identityClass = $this->identityClass;
try {
return $identityClass::findIdentityByAccessToken($accessToken);
return IdentityFactory::findIdentityByAccessToken($accessToken);
} catch (UnauthorizedHttpException $e) {
// TODO: if this exception is catched there, how it forms "Token expired" exception?
// Do nothing. It's okay to catch this.
} catch (Exception $e) {
Yii::error($e);
@@ -95,77 +55,6 @@ class Component extends YiiUserComponent {
return null;
}
public function createJwtAuthenticationToken(Account $account, AccountSession $session = null): Token {
$token = $this->createToken($account);
if ($session !== null) {
$token->addClaim(new Claim\JwtId($session->id));
} else {
// If we don't remember a session, the token should live longer
// so that the session doesn't end while working with the account
$token->addClaim(new Claim\Expiration((new DateTime())->add(new DateInterval($this->sessionTimeout))));
}
return $token;
}
public function renewJwtAuthenticationToken(AccountSession $session): AuthenticationResult {
$transaction = Yii::$app->db->beginTransaction();
$account = $session->account;
$token = $this->createToken($account);
$token->addClaim(new Claim\JwtId($session->id));
$jwt = $this->serializeToken($token);
$result = new AuthenticationResult($account, $jwt, $session);
$session->setIp(Yii::$app->request->userIP);
$session->last_refreshed_at = time();
if (!$session->save()) {
throw new ThisShouldNotHappenException('Cannot update session info');
}
$transaction->commit();
return $result;
}
public function serializeToken(Token $token): string {
$encryption = $this->getEncryptionForVersion(self::LATEST_JWT_VERSION);
$this->prepareEncryptionForEncoding($encryption);
return (new Jwt())->serialize($token, $encryption);
}
/**
* @param string $jwtString
* @return Token
* @throws VerificationException in case when some Claim not pass the validation
*/
public function parseToken(string $jwtString): Token {
$token = &self::$parsedTokensCache[$jwtString];
if ($token === null) {
$jwt = new Jwt();
try {
$notVerifiedToken = $jwt->deserialize($jwtString);
} catch (Exception $e) {
throw new VerificationException('Incorrect token encoding', 0, $e);
}
$versionHeader = $notVerifiedToken->getHeader()->findParameterByName('v');
$version = $versionHeader ? $versionHeader->getValue() : 0;
$encryption = $this->getEncryptionForVersion($version);
$this->prepareEncryptionForDecoding($encryption);
$context = new VerificationContext($encryption);
$context->setSubject(self::JWT_SUBJECT_PREFIX);
$jwt->verify($notVerifiedToken, $context);
$token = $notVerifiedToken;
}
return $token;
}
/**
* The method searches AccountSession model, which one has been used to create current JWT token.
* null will be returned in case when any of the following situations occurred:
@@ -188,17 +77,17 @@ class Component extends YiiUserComponent {
}
try {
$token = $this->parseToken($bearer);
} catch (VerificationException $e) {
$token = Yii::$app->tokens->parse($bearer);
} catch (InvalidArgumentException $e) {
return null;
}
$sessionId = $token->getPayload()->findClaimByName(Claim\JwtId::NAME);
if ($sessionId === null) {
$sessionId = $token->getClaim('jti', false);
if ($sessionId === false) {
return null;
}
return AccountSession::findOne($sessionId->getValue());
return AccountSession::findOne($sessionId);
}
public function terminateSessions(Account $account, int $mode = 0): void {
@@ -222,66 +111,6 @@ class Component extends YiiUserComponent {
}
}
private function getPublicKey() {
if (empty($this->publicKey)) {
if (!($this->publicKey = file_get_contents($this->publicKeyPath))) {
throw new InvalidConfigException('invalid public key path');
}
}
return $this->publicKey;
}
private function getPrivateKey() {
if (empty($this->privateKey)) {
if (!($this->privateKey = file_get_contents($this->privateKeyPath))) {
throw new InvalidConfigException('invalid private key path');
}
}
return $this->privateKey;
}
private function createToken(Account $account): Token {
$token = new Token();
$token->addHeader(new Custom('v', 1));
foreach ($this->getClaims($account) as $claim) {
$token->addClaim($claim);
}
return $token;
}
/**
* @param Account $account
* @return Claim\AbstractClaim[]
*/
private function getClaims(Account $account): array {
$currentTime = new DateTime();
return [
new ScopesClaim([R::ACCOUNTS_WEB_USER]),
new Claim\IssuedAt($currentTime),
new Claim\Expiration($currentTime->add(new DateInterval($this->expirationTimeout))),
new Claim\Subject(self::JWT_SUBJECT_PREFIX . $account->id),
];
}
private function getEncryptionForVersion(int $version): EncryptionInterface {
return EncryptionFactory::create($this->getAlgorithm($version ?? 0));
}
private function getAlgorithm(int $version): AlgorithmInterface {
switch ($version) {
case 0:
return new Hs256($this->secret);
case 1:
return new Rs256();
}
throw new InvalidArgumentException('Unsupported token version');
}
private function getBearerToken(): ?string {
$authHeader = Yii::$app->request->getHeaders()->get('Authorization');
if ($authHeader === null || !preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) {
@@ -291,16 +120,4 @@ class Component extends YiiUserComponent {
return $matches[1];
}
private function prepareEncryptionForEncoding(EncryptionInterface $encryption): void {
if ($encryption instanceof AsymmetricEncryption) {
$encryption->setPrivateKey($this->getPrivateKey());
}
}
private function prepareEncryptionForDecoding(EncryptionInterface $encryption) {
if ($encryption instanceof AsymmetricEncryption) {
$encryption->setPublicKey($this->getPublicKey());
}
}
}

View File

@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace api\components\User;
use yii\web\UnauthorizedHttpException;
class IdentityFactory {
/**
* @throws UnauthorizedHttpException
* @return IdentityInterface
*/
public static function findIdentityByAccessToken($token, $type = null): IdentityInterface {
if (empty($token)) {
throw new UnauthorizedHttpException('Incorrect token');
}
if (substr_count($token, '.') === 2) {
return JwtIdentity::findIdentityByAccessToken($token, $type);
}
return Oauth2Identity::findIdentityByAccessToken($token, $type);
}
}

View File

@@ -1,23 +0,0 @@
<?php
namespace api\components\User;
use Emarref\Jwt\Verification\Context;
use Emarref\Jwt\Verification\SubjectVerifier;
class Jwt extends \Emarref\Jwt\Jwt {
protected function getVerifiers(Context $context): array {
$verifiers = parent::getVerifiers($context);
foreach ($verifiers as $i => $verifier) {
if (!$verifier instanceof SubjectVerifier) {
continue;
}
$verifiers[$i] = new SubjectPrefixVerifier($context->getSubject());
break;
}
return $verifiers;
}
}

View File

@@ -1,82 +1,80 @@
<?php
declare(strict_types=1);
namespace api\components\User;
use api\components\Tokens\TokensFactory;
use common\models\Account;
use Emarref\Jwt\Claim\Subject;
use Emarref\Jwt\Exception\ExpiredException;
use Emarref\Jwt\Token;
use Exception;
use Lcobucci\JWT\Token;
use Lcobucci\JWT\ValidationData;
use Webmozart\Assert\Assert;
use Yii;
use yii\base\NotSupportedException;
use yii\helpers\StringHelper;
use yii\web\UnauthorizedHttpException;
class JwtIdentity implements IdentityInterface {
/**
* @var string
*/
private $rawToken;
/**
* @var Token
*/
private $token;
private function __construct(string $rawToken, Token $token) {
$this->rawToken = $rawToken;
private function __construct(Token $token) {
$this->token = $token;
}
public static function findIdentityByAccessToken($rawToken, $type = null): IdentityInterface {
/** @var \api\components\User\Component $component */
$component = Yii::$app->user;
try {
$token = $component->parseToken($rawToken);
} catch (ExpiredException $e) {
throw new UnauthorizedHttpException('Token expired');
$token = Yii::$app->tokens->parse($rawToken);
} catch (Exception $e) {
Yii::error($e);
throw new UnauthorizedHttpException('Incorrect token');
}
return new self($rawToken, $token);
if (!Yii::$app->tokens->verify($token)) {
throw new UnauthorizedHttpException('Incorrect token');
}
if ($token->isExpired()) {
throw new UnauthorizedHttpException('Token expired');
}
if (!$token->validate(new ValidationData())) {
throw new UnauthorizedHttpException('Incorrect token');
}
$sub = $token->getClaim('sub', false);
if ($sub !== false && strpos($sub, TokensFactory::SUB_ACCOUNT_PREFIX) !== 0) {
throw new UnauthorizedHttpException('Incorrect token');
}
return new self($token);
}
public function getAccount(): ?Account {
/** @var Subject $subject */
$subject = $this->token->getPayload()->findClaimByName(Subject::NAME);
if ($subject === null) {
$subject = $this->token->getClaim('sub', false);
if ($subject === false) {
return null;
}
$value = $subject->getValue();
if (!StringHelper::startsWith($value, Component::JWT_SUBJECT_PREFIX)) {
Yii::warning('Unknown jwt subject: ' . $value);
return null;
}
Assert::startsWith($subject, TokensFactory::SUB_ACCOUNT_PREFIX);
$accountId = (int)mb_substr($subject, mb_strlen(TokensFactory::SUB_ACCOUNT_PREFIX));
$accountId = (int)mb_substr($value, mb_strlen(Component::JWT_SUBJECT_PREFIX));
$account = Account::findOne($accountId);
if ($account === null) {
return null;
}
return $account;
return Account::findOne(['id' => $accountId]);
}
public function getAssignedPermissions(): array {
/** @var Subject $scopesClaim */
$scopesClaim = $this->token->getPayload()->findClaimByName(ScopesClaim::NAME);
if ($scopesClaim === null) {
$scopesClaim = $this->token->getClaim('ely-scopes', false);
if ($scopesClaim === false) {
return [];
}
return explode(',', $scopesClaim->getValue());
return explode(',', $scopesClaim);
}
public function getId(): string {
return $this->rawToken;
return (string)$this->token;
}
public function getAuthKey() {

View File

@@ -1,4 +1,6 @@
<?php
declare(strict_types=1);
namespace api\components\User;
use api\components\OAuth2\Entities\AccessTokenEntity;
@@ -8,10 +10,7 @@ use Yii;
use yii\base\NotSupportedException;
use yii\web\UnauthorizedHttpException;
/**
* @property Account $account
*/
class Identity implements IdentityInterface {
class Oauth2Identity implements IdentityInterface {
/**
* @var AccessTokenEntity
@@ -24,19 +23,10 @@ class Identity implements IdentityInterface {
/**
* @inheritdoc
* @throws \yii\web\UnauthorizedHttpException
* @throws UnauthorizedHttpException
* @return IdentityInterface
*/
public static function findIdentityByAccessToken($token, $type = null): IdentityInterface {
if ($token === null) {
throw new UnauthorizedHttpException('Incorrect token');
}
// Speed-improved analogue of the `count(explode('.', $token)) === 3`
if (substr_count($token, '.') === 2) {
return JwtIdentity::findIdentityByAccessToken($token, $type);
}
/** @var AccessTokenEntity|null $model */
$model = Yii::$app->oauth->getAccessTokenStorage()->get($token);
if ($model === null) {

View File

@@ -1,30 +0,0 @@
<?php
namespace api\components\User;
use Emarref\Jwt\Claim\AbstractClaim;
class ScopesClaim extends AbstractClaim {
public const NAME = 'ely-scopes';
/**
* ScopesClaim constructor.
*
* @param array|string $value
*/
public function __construct($value = null) {
if (is_array($value)) {
$value = implode(',', $value);
}
parent::__construct($value);
}
/**
* @inheritdoc
*/
public function getName(): string {
return self::NAME;
}
}

View File

@@ -1,28 +0,0 @@
<?php
namespace api\components\User;
use Emarref\Jwt\Claim\Subject;
use Emarref\Jwt\Exception\InvalidSubjectException;
use Emarref\Jwt\Token;
use Emarref\Jwt\Verification\VerifierInterface;
use yii\helpers\StringHelper;
class SubjectPrefixVerifier implements VerifierInterface {
private $subjectPrefix;
public function __construct(string $subjectPrefix) {
$this->subjectPrefix = $subjectPrefix;
}
public function verify(Token $token): void {
/** @var Subject $subjectClaim */
$subjectClaim = $token->getPayload()->findClaimByName(Subject::NAME);
$subject = ($subjectClaim === null) ? null : $subjectClaim->getValue();
if (!StringHelper::startsWith($subject, $this->subjectPrefix)) {
throw new InvalidSubjectException();
}
}
}