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

@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace api\components\Tokens;
class AlgorithmIsNotDefinedException extends \Exception {
public function __construct(string $algorithmId) {
parent::__construct("Algorithm with id \"{$algorithmId}\" is not defined");
}
}

View File

@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace api\components\Tokens\Algorithms;
use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Key;
interface AlgorithmInterface {
public function getAlgorithmId(): string;
public function getSigner(): Signer;
public function getPrivateKey(): Key;
public function getPublicKey(): Key;
}

View File

@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace api\components\Tokens\Algorithms;
use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Ecdsa\Sha256;
use Lcobucci\JWT\Signer\Key;
class ES256 implements AlgorithmInterface {
/**
* @var string
*/
private $privateKey;
/**
* @var string|null
*/
private $privateKeyPass;
/**
* @var string
*/
private $publicKey;
/**
* @var Key|null
*/
private $loadedPrivateKey;
/**
* @var Key|null
*/
private $loadedPublicKey;
/**
* TODO: document arguments
*
* @param string $privateKey
* @param string|null $privateKeyPass
* @param string $publicKey
*/
public function __construct(string $privateKey, ?string $privateKeyPass, string $publicKey) {
$this->privateKey = $privateKey;
$this->privateKeyPass = $privateKeyPass;
$this->publicKey = $publicKey;
}
public function getAlgorithmId(): string {
return 'ES256';
}
public function getSigner(): Signer {
return new Sha256();
}
public function getPrivateKey(): Key {
if ($this->loadedPrivateKey === null) {
$this->loadedPrivateKey = new Key($this->privateKey, $this->privateKeyPass);
}
return $this->loadedPrivateKey;
}
public function getPublicKey(): Key {
if ($this->loadedPublicKey === null) {
$this->loadedPublicKey = new Key($this->publicKey);
}
return $this->loadedPublicKey;
}
}

View File

@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace api\components\Tokens\Algorithms;
use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key;
class HS256 implements AlgorithmInterface {
/**
* @var string
*/
private $key;
/**
* @var Key|null
*/
private $loadedKey;
public function __construct(string $key) {
$this->key = $key;
}
public function getAlgorithmId(): string {
return 'HS256';
}
public function getSigner(): Signer {
return new Sha256();
}
public function getPrivateKey(): Key {
return $this->loadKey();
}
public function getPublicKey(): Key {
return $this->loadKey();
}
private function loadKey(): Key {
if ($this->loadedKey === null) {
$this->loadedKey = new Key($this->key);
}
return $this->loadedKey;
}
}

View File

@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace api\components\Tokens;
use api\components\Tokens\Algorithms\AlgorithmInterface;
use Webmozart\Assert\Assert;
class AlgorithmsManager {
/**
* @var AlgorithmInterface[]
*/
private $algorithms = [];
public function __construct(array $algorithms = []) {
array_map([$this, 'add'], $algorithms);
}
public function add(AlgorithmInterface $algorithm): self {
$id = $algorithm->getAlgorithmId();
Assert::keyNotExists($this->algorithms, $id, 'passed algorithm is already exists');
$this->algorithms[$algorithm->getSigner()->getAlgorithmId()] = $algorithm;
return $this;
}
/**
* @param string $algorithmId
*
* @return AlgorithmInterface
* @throws AlgorithmIsNotDefinedException
*/
public function get(string $algorithmId): AlgorithmInterface {
if (!isset($this->algorithms[$algorithmId])) {
throw new AlgorithmIsNotDefinedException($algorithmId);
}
return $this->algorithms[$algorithmId];
}
}

View File

@@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
namespace api\components\Tokens;
use Exception;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Token;
use yii\base\Component as BaseComponent;
class Component extends BaseComponent {
private const EXPIRATION_TIMEOUT = 3600; // 1h
private const PREFERRED_ALGORITHM = 'ES256';
/**
* @var string
*/
public $hmacKey;
/**
* @var string
*/
public $publicKeyPath;
/**
* @var string
*/
public $privateKeyPath;
/**
* @var string|null
*/
public $privateKeyPass;
/**
* @var AlgorithmsManager|null
*/
private $algorithmManager;
public function create(array $payloads = [], array $headers = []): Token {
$time = time();
$builder = (new Builder())
->issuedAt($time)
->expiresAt($time + self::EXPIRATION_TIMEOUT);
foreach ($payloads as $claim => $value) {
$builder->withClaim($claim, $value);
}
foreach ($headers as $claim => $value) {
$builder->withHeader($claim, $value);
}
/** @noinspection PhpUnhandledExceptionInspection */
$algorithm = $this->getAlgorithmManager()->get(self::PREFERRED_ALGORITHM);
return $builder->getToken($algorithm->getSigner(), $algorithm->getPrivateKey());
}
/**
* @param string $jwt
*
* @return Token
* @throws \InvalidArgumentException
*/
public function parse(string $jwt): Token {
return (new Parser())->parse($jwt);
}
public function verify(Token $token): bool {
try {
$algorithm = $this->getAlgorithmManager()->get($token->getHeader('alg'));
return $token->verify($algorithm->getSigner(), $algorithm->getPublicKey());
} catch (Exception $e) {
return false;
}
}
private function getAlgorithmManager(): AlgorithmsManager {
if ($this->algorithmManager === null) {
$this->algorithmManager = new AlgorithmsManager([
new Algorithms\HS256($this->hmacKey),
new Algorithms\ES256(
"file://{$this->privateKeyPath}",
$this->privateKeyPass,
"file://{$this->publicKeyPath}"
),
]);
}
return $this->algorithmManager;
}
}

View File

@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace api\components\Tokens;
use common\models\Account;
use common\models\AccountSession;
use Lcobucci\JWT\Token;
use Yii;
class TokensFactory {
public const SUB_ACCOUNT_PREFIX = 'ely|';
public static function createForAccount(Account $account, AccountSession $session = null): Token {
$payloads = [
'ely-scopes' => 'accounts_web_user',
'sub' => self::SUB_ACCOUNT_PREFIX . $account->id,
];
if ($session === null) {
// If we don't remember a session, the token should live longer
// so that the session doesn't end while working with the account
$payloads['exp'] = time() + 60 * 60 * 24 * 7; // 7d
} else {
$payloads['jti'] = $session->id;
}
return Yii::$app->tokens->create($payloads);
}
}

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();
}
}
}

View File

@@ -1,8 +1,11 @@
<?php
return [
'components' => [
'user' => [
'secret' => 'tests-secret-key',
'tokens' => [
'hmacKey' => 'tests-secret-key',
'privateKeyPath' => codecept_data_dir('certs/private.pem'),
'privateKeyPass' => null,
'publicKeyPath' => codecept_data_dir('certs/public.pem'),
],
'reCaptcha' => [
'public' => 'public-key',

View File

@@ -10,9 +10,13 @@ return [
'components' => [
'user' => [
'class' => api\components\User\Component::class,
'secret' => getenv('JWT_USER_SECRET'),
'publicKeyPath' => getenv('JWT_PUBLIC_KEY') ?: 'data/certs/public.crt',
'privateKeyPath' => getenv('JWT_PRIVATE_KEY') ?: 'data/certs/private.key',
],
'tokens' => [
'class' => api\components\Tokens\Component::class,
'hmacKey' => getenv('JWT_USER_SECRET'),
'privateKeyPath' => getenv('JWT_PRIVATE_KEY_PATH') ?: __DIR__ . '/../../data/certs/private.pem',
'privateKeyPass' => getenv('JWT_PRIVATE_KEY_PASS') ?: null,
'publicKeyPath' => getenv('JWT_PUBLIC_KEY_PATH') ?: __DIR__ . '/../../data/certs/public.pem',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,

View File

@@ -51,7 +51,7 @@ class AuthenticationController extends Controller {
public function actionLogin() {
$model = new LoginForm();
$model->load(Yii::$app->request->post());
if (($result = $model->login()) === false) {
if (($result = $model->login()) === null) {
$data = [
'success' => false,
'errors' => $model->getFirstErrors(),
@@ -66,7 +66,7 @@ class AuthenticationController extends Controller {
return array_merge([
'success' => true,
], $result->getAsResponse());
], $result->formatAsOAuth2Response());
}
public function actionLogout() {
@@ -117,7 +117,7 @@ class AuthenticationController extends Controller {
public function actionRecoverPassword() {
$model = new RecoverPasswordForm();
$model->load(Yii::$app->request->post());
if (($result = $model->recoverPassword()) === false) {
if (($result = $model->recoverPassword()) === null) {
return [
'success' => false,
'errors' => $model->getFirstErrors(),
@@ -126,20 +126,20 @@ class AuthenticationController extends Controller {
return array_merge([
'success' => true,
], $result->getAsResponse());
], $result->formatAsOAuth2Response());
}
public function actionRefreshToken() {
$model = new RefreshTokenForm();
$model->load(Yii::$app->request->post());
if (($result = $model->renew()) === false) {
if (($result = $model->renew()) === null) {
return [
'success' => false,
'errors' => $model->getFirstErrors(),
];
}
$response = $result->getAsResponse();
$response = $result->formatAsOAuth2Response();
unset($response['refresh_token']);
return array_merge([

View File

@@ -89,7 +89,7 @@ class SignupController extends Controller {
return array_merge([
'success' => true,
], $result->getAsResponse());
], $result->formatAsOAuth2Response());
}
}

View File

@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace api\models\authentication;
use Lcobucci\JWT\Token;
class AuthenticationResult {
/**
* @var Token
*/
private $token;
/**
* @var string|null
*/
private $refreshToken;
public function __construct(Token $token, string $refreshToken = null) {
$this->token = $token;
$this->refreshToken = $refreshToken;
}
public function getToken(): Token {
return $this->token;
}
public function getRefreshToken(): ?string {
return $this->refreshToken;
}
public function formatAsOAuth2Response(): array {
$response = [
'access_token' => (string)$this->token,
'expires_in' => $this->token->getClaim('exp') - time(),
];
$refreshToken = $this->refreshToken;
if ($refreshToken !== null) {
$response['refresh_token'] = $refreshToken;
}
return $response;
}
}

View File

@@ -4,7 +4,7 @@ declare(strict_types=1);
namespace api\models\authentication;
use api\aop\annotations\CollectModelMetrics;
use api\components\User\AuthenticationResult;
use api\components\Tokens\TokensFactory;
use api\models\base\ApiForm;
use api\validators\EmailActivationKeyValidator;
use common\models\Account;
@@ -25,12 +25,10 @@ class ConfirmEmailForm extends ApiForm {
/**
* @CollectModelMetrics(prefix="signup.confirmEmail")
* @return AuthenticationResult|bool
* @throws \Throwable
*/
public function confirm() {
public function confirm(): ?AuthenticationResult {
if (!$this->validate()) {
return false;
return null;
}
$transaction = Yii::$app->db->beginTransaction();
@@ -39,6 +37,7 @@ class ConfirmEmailForm extends ApiForm {
$confirmModel = $this->key;
$account = $confirmModel->account;
$account->status = Account::STATUS_ACTIVE;
/** @noinspection PhpUnhandledExceptionInspection */
Assert::notSame($confirmModel->delete(), false, 'Unable remove activation key.');
Assert::true($account->save(), 'Unable activate user account.');
@@ -49,12 +48,11 @@ class ConfirmEmailForm extends ApiForm {
$session->generateRefreshToken();
Assert::true($session->save(), 'Cannot save account session model');
$token = Yii::$app->user->createJwtAuthenticationToken($account, $session);
$jwt = Yii::$app->user->serializeToken($token);
$token = TokensFactory::createForAccount($account, $session);
$transaction->commit();
return new AuthenticationResult($account, $jwt, $session);
return new AuthenticationResult($token, $session->refresh_token);
}
}

View File

@@ -4,7 +4,7 @@ declare(strict_types=1);
namespace api\models\authentication;
use api\aop\annotations\CollectModelMetrics;
use api\components\User\AuthenticationResult;
use api\components\Tokens\TokensFactory;
use api\models\base\ApiForm;
use api\traits\AccountFinder;
use api\validators\TotpValidator;
@@ -30,12 +30,12 @@ class LoginForm extends ApiForm {
['login', 'required', 'message' => E::LOGIN_REQUIRED],
['login', 'validateLogin'],
['password', 'required', 'when' => function(self $model) {
['password', 'required', 'when' => function(self $model): bool {
return !$model->hasErrors();
}, 'message' => E::PASSWORD_REQUIRED],
['password', 'validatePassword'],
['totp', 'required', 'when' => function(self $model) {
['totp', 'required', 'when' => function(self $model): bool {
return !$model->hasErrors() && $model->getAccount()->is_otp_enabled;
}, 'message' => E::TOTP_REQUIRED],
['totp', 'validateTotp'],
@@ -97,11 +97,10 @@ class LoginForm extends ApiForm {
/**
* @CollectModelMetrics(prefix="authentication.login")
* @return AuthenticationResult|bool
*/
public function login() {
public function login(): ?AuthenticationResult {
if (!$this->validate()) {
return false;
return null;
}
$transaction = Yii::$app->db->beginTransaction();
@@ -113,21 +112,22 @@ class LoginForm extends ApiForm {
Assert::true($account->save(), 'Unable to upgrade user\'s password');
}
$session = null;
$refreshToken = null;
if ($this->rememberMe) {
$session = new AccountSession();
$session->account_id = $account->id;
$session->setIp(Yii::$app->request->userIP);
$session->generateRefreshToken();
Assert::true($session->save(), 'Cannot save account session model');
$refreshToken = $session->refresh_token;
}
$token = Yii::$app->user->createJwtAuthenticationToken($account, $session);
$jwt = Yii::$app->user->serializeToken($token);
$token = TokensFactory::createForAccount($account, $session);
$transaction->commit();
return new AuthenticationResult($account, $jwt, $session);
return new AuthenticationResult($token, $refreshToken);
}
}

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace api\models\authentication;
use api\aop\annotations\CollectModelMetrics;
use api\components\Tokens\TokensFactory;
use api\models\base\ApiForm;
use api\validators\EmailActivationKeyValidator;
use common\helpers\Error as E;
@@ -38,12 +39,10 @@ class RecoverPasswordForm extends ApiForm {
/**
* @CollectModelMetrics(prefix="authentication.recoverPassword")
* @return \api\components\User\AuthenticationResult|bool
* @throws \Throwable
*/
public function recoverPassword() {
public function recoverPassword(): ?AuthenticationResult {
if (!$this->validate()) {
return false;
return null;
}
$transaction = Yii::$app->db->beginTransaction();
@@ -52,16 +51,16 @@ class RecoverPasswordForm extends ApiForm {
$confirmModel = $this->key;
$account = $confirmModel->account;
$account->password = $this->newPassword;
/** @noinspection PhpUnhandledExceptionInspection */
Assert::notSame($confirmModel->delete(), false, 'Unable remove activation key.');
Assert::true($account->save(), 'Unable activate user account.');
$token = Yii::$app->user->createJwtAuthenticationToken($account);
$jwt = Yii::$app->user->serializeToken($token);
$token = TokensFactory::createForAccount($account);
$transaction->commit();
return new \api\components\User\AuthenticationResult($account, $jwt, null);
return new AuthenticationResult($token);
}
}

View File

@@ -1,10 +1,14 @@
<?php
declare(strict_types=1);
namespace api\models\authentication;
use api\aop\annotations\CollectModelMetrics;
use api\components\Tokens\TokensFactory;
use api\models\base\ApiForm;
use common\helpers\Error as E;
use common\models\AccountSession;
use Webmozart\Assert\Assert;
use Yii;
class RefreshTokenForm extends ApiForm {
@@ -16,41 +20,45 @@ class RefreshTokenForm extends ApiForm {
*/
private $session;
public function rules() {
public function rules(): array {
return [
['refresh_token', 'required', 'message' => E::REFRESH_TOKEN_REQUIRED],
['refresh_token', 'validateRefreshToken'],
];
}
public function validateRefreshToken() {
if (!$this->hasErrors()) {
/** @var AccountSession|null $token */
if ($this->getSession() === null) {
$this->addError('refresh_token', E::REFRESH_TOKEN_NOT_EXISTS);
}
public function validateRefreshToken(): void {
if (!$this->hasErrors() && $this->findSession() === null) {
$this->addError('refresh_token', E::REFRESH_TOKEN_NOT_EXISTS);
}
}
/**
* @CollectModelMetrics(prefix="authentication.renew")
* @return \api\components\User\AuthenticationResult|bool
*/
public function renew() {
public function renew(): ?AuthenticationResult {
if (!$this->validate()) {
return false;
return null;
}
/** @var \api\components\User\Component $component */
$component = Yii::$app->user;
/** @var AccountSession $session */
$session = $this->findSession();
$account = $session->account;
return $component->renewJwtAuthenticationToken($this->getSession());
$transaction = Yii::$app->db->beginTransaction();
$token = TokensFactory::createForAccount($account, $session);
$session->setIp(Yii::$app->request->userIP);
$session->touch('last_refreshed_at');
Assert::true($session->save(), 'Cannot update session info');
$transaction->commit();
return new AuthenticationResult($token, $session->refresh_token);
}
/**
* @return AccountSession|null
*/
public function getSession() {
private function findSession(): ?AccountSession {
if ($this->session === null) {
$this->session = AccountSession::findOne(['refresh_token' => $this->refresh_token]);
}

View File

@@ -0,0 +1,5 @@
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIKrv4e6B9XP7l8F94ZMJotA+7FtjK7k9/olQi7Eb2tgmoAoGCCqGSM49
AwEHoUQDQgAES2Pyq9r0CyyviLaWwq0ki5uy8hr/ZbNO++3j4XP43uLD9/GYkrKG
IRl+Hu5HT+LwZvrFcEaVhPk5CvtV4zlYJg==
-----END EC PRIVATE KEY-----

View File

@@ -0,0 +1,4 @@
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAES2Pyq9r0CyyviLaWwq0ki5uy8hr/
ZbNO++3j4XP43uLD9/GYkrKGIRl+Hu5HT+LwZvrFcEaVhPk5CvtV4zlYJg==
-----END PUBLIC KEY-----

View File

@@ -3,6 +3,7 @@ declare(strict_types=1);
namespace api\tests;
use api\components\Tokens\TokensFactory;
use api\tests\_generated\FunctionalTesterActions;
use Codeception\Actor;
use common\models\Account;
@@ -12,16 +13,15 @@ use Yii;
class FunctionalTester extends Actor {
use FunctionalTesterActions;
public function amAuthenticated(string $asUsername = 'admin') {
public function amAuthenticated(string $asUsername = 'admin'): int {
/** @var Account $account */
$account = Account::findOne(['username' => $asUsername]);
if ($account === null) {
throw new InvalidArgumentException("Cannot find account for username \"{$asUsername}\"");
throw new InvalidArgumentException("Cannot find account with username \"{$asUsername}\"");
}
$token = Yii::$app->user->createJwtAuthenticationToken($account);
$jwt = Yii::$app->user->serializeToken($token);
$this->amBearerAuthenticated($jwt);
$token = TokensFactory::createForAccount($account);
$this->amBearerAuthenticated((string)$token);
return $account->id;
}
@@ -31,10 +31,10 @@ class FunctionalTester extends Actor {
Yii::$app->user->logout();
}
public function canSeeAuthCredentials($expectRefresh = false): void {
public function canSeeAuthCredentials($expectRefreshToken = false): void {
$this->canSeeResponseJsonMatchesJsonPath('$.access_token');
$this->canSeeResponseJsonMatchesJsonPath('$.expires_in');
if ($expectRefresh) {
if ($expectRefreshToken) {
$this->canSeeResponseJsonMatchesJsonPath('$.refresh_token');
} else {
$this->cantSeeResponseJsonMatchesJsonPath('$.refresh_token');

View File

@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace api\tests\unit\components\Tokens;
use api\tests\unit\TestCase;
use InvalidArgumentException;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Token;
use Yii;
class ComponentTest extends TestCase {
/**
* @var \api\components\Tokens\Component
*/
private $component;
protected function _setUp() {
parent::_setUp();
$this->component = Yii::$app->tokens;
}
public function testCreate() {
// Run without any arguments
$token = $this->component->create();
$this->assertSame('ES256', $token->getHeader('alg'));
$this->assertEmpty(array_diff(array_keys($token->getClaims()), ['iat', 'exp']));
$this->assertEqualsWithDelta(time(), $token->getClaim('iat'), 1);
$this->assertEqualsWithDelta(time() + 3600, $token->getClaim('exp'), 2);
// Pass custom payloads
$token = $this->component->create(['find' => 'me']);
$this->assertArrayHasKey('find', $token->getClaims());
$this->assertSame('me', $token->getClaim('find'));
// Pass custom headers
$token = $this->component->create([], ['find' => 'me']);
$this->assertArrayHasKey('find', $token->getHeaders());
$this->assertSame('me', $token->getHeader('find'));
}
public function testParse() {
// Valid token signed with HS256
$token = $this->component->parse('eyJhbGciOiJIUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.ixapBbhaUCejbcPTnFi5nqk75XKd1_lQJd1ZPgGTLEc');
$this->assertValidParsedToken($token, 'HS256');
// Valid token signed with ES256
$token = $this->component->parse('eyJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.M8Kam9bv0BXui3k7Posq_vc0I95Kb_Tw7L2vPdEPlwsHqh1VJHoWtlQc32_SlsotttL7j6RYbffBkRFX2wDGFQ');
$this->assertValidParsedToken($token, 'ES256');
// Valid token signed with ES256, but the signature is invalid
$token = $this->component->parse('eyJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.xxx');
$this->assertValidParsedToken($token, 'ES256');
// Completely invalid token
$this->expectException(InvalidArgumentException::class);
$this->component->parse('How do you tame a horse in Minecraft?');
}
/**
* @dataProvider getVerifyCases
*/
public function testVerify(Token $token, bool $shouldBeValid) {
$this->assertSame($shouldBeValid, $this->component->verify($token));
}
public function getVerifyCases() {
yield 'HS256' => [
(new Parser())->parse('eyJhbGciOiJIUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.ixapBbhaUCejbcPTnFi5nqk75XKd1_lQJd1ZPgGTLEc'),
true,
];
yield 'ES256' => [
(new Parser())->parse('eyJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.M8Kam9bv0BXui3k7Posq_vc0I95Kb_Tw7L2vPdEPlwsHqh1VJHoWtlQc32_SlsotttL7j6RYbffBkRFX2wDGFQ'),
true,
];
yield 'ES256 with an invalid signature' => [
(new Parser())->parse('eyJhbGciOiJFUzI1NiJ9.eyJlbHktc2NvcGVzIjoiYWNjb3VudHNfd2ViX3VzZXIiLCJpYXQiOjE1NjQ1Mjc0NzYsImV4cCI6MTU2NDUzMTA3Niwic3ViIjoiZWx5fDEiLCJqdGkiOjMwNjk1OTJ9.xxx'),
false,
];
}
private function assertValidParsedToken(Token $token, string $expectedAlg) {
$this->assertSame($expectedAlg, $token->getHeader('alg'));
$this->assertSame(1564527476, $token->getClaim('iat'));
$this->assertSame(1564531076, $token->getClaim('exp'));
$this->assertSame('ely|1', $token->getClaim('sub'));
$this->assertSame(3069592, $token->getClaim('jti'));
$this->assertSame('accounts_web_user', $token->getClaim('ely-scopes'));
}
}

View File

@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace api\tests\unit\components\Tokens;
use api\components\Tokens\TokensFactory;
use api\tests\unit\TestCase;
use common\models\Account;
use common\models\AccountSession;
class TokensFactoryTest extends TestCase {
public function testCreateForAccount() {
$account = new Account();
$account->id = 1;
$token = TokensFactory::createForAccount($account);
$this->assertEqualsWithDelta(time(), $token->getClaim('iat'), 1);
$this->assertEqualsWithDelta(time() + 60 * 60 * 24 * 7, $token->getClaim('exp'), 2);
$this->assertSame('ely|1', $token->getClaim('sub'));
$this->assertSame('accounts_web_user', $token->getClaim('ely-scopes'));
$this->assertArrayNotHasKey('jti', $token->getClaims());
$session = new AccountSession();
$session->id = 2;
$token = TokensFactory::createForAccount($account, $session);
$this->assertEqualsWithDelta(time(), $token->getClaim('iat'), 1);
$this->assertEqualsWithDelta(time() + 3600, $token->getClaim('exp'), 2);
$this->assertSame('ely|1', $token->getClaim('sub'));
$this->assertSame('accounts_web_user', $token->getClaim('ely-scopes'));
$this->assertSame(2, $token->getClaim('jti'));
}
}

View File

@@ -4,7 +4,7 @@ declare(strict_types=1);
namespace codeception\api\unit\components\User;
use api\components\User\Component;
use api\components\User\Identity;
use api\components\User\IdentityFactory;
use api\tests\unit\TestCase;
use common\models\Account;
use common\models\AccountSession;
@@ -36,29 +36,7 @@ class ComponentTest extends TestCase {
];
}
public function testCreateJwtAuthenticationToken() {
$this->mockRequest();
// Token without session
$account = new Account(['id' => 1]);
$token = $this->component->createJwtAuthenticationToken($account);
$payloads = $token->getPayload();
$this->assertEqualsWithDelta(time(), $payloads->findClaimByName('iat')->getValue(), 3);
$this->assertEqualsWithDelta(time() + 60 * 60 * 24 * 7, $payloads->findClaimByName('exp')->getValue(), 3);
$this->assertSame('ely|1', $payloads->findClaimByName('sub')->getValue());
$this->assertSame('accounts_web_user', $payloads->findClaimByName('ely-scopes')->getValue());
$this->assertNull($payloads->findClaimByName('jti'));
$session = new AccountSession(['id' => 2]);
$token = $this->component->createJwtAuthenticationToken($account, $session);
$payloads = $token->getPayload();
$this->assertEqualsWithDelta(time(), $payloads->findClaimByName('iat')->getValue(), 3);
$this->assertEqualsWithDelta(time() + 3600, $payloads->findClaimByName('exp')->getValue(), 3);
$this->assertSame('ely|1', $payloads->findClaimByName('sub')->getValue());
$this->assertSame('accounts_web_user', $payloads->findClaimByName('ely-scopes')->getValue());
$this->assertSame(2, $payloads->findClaimByName('jti')->getValue());
}
// TODO: move test to refresh token form
public function testRenewJwtAuthenticationToken() {
$userIP = '192.168.0.1';
$this->mockRequest($userIP);
@@ -83,14 +61,6 @@ class ComponentTest extends TestCase {
$this->assertSame($session->id, $payloads->findClaimByName('jti')->getValue(), 'session has not changed');
}
public function testParseToken() {
$this->mockRequest();
$account = new Account(['id' => 1]);
$token = $this->component->createJwtAuthenticationToken($account);
$jwt = $this->component->serializeToken($token);
$this->component->parseToken($jwt);
}
public function testGetActiveSession() {
/** @var Account $account */
$account = $this->tester->grabFixture('accounts', 'admin');
@@ -172,7 +142,7 @@ class ComponentTest extends TestCase {
private function getComponentConfig() {
return [
'identityClass' => Identity::class,
'identityClass' => IdentityFactory::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => 'secret',

View File

@@ -1,63 +0,0 @@
<?php
namespace api\tests\unit\components\User;
use api\components\User\AuthenticationResult;
use api\tests\unit\TestCase;
use common\models\Account;
use common\models\AccountSession;
use Emarref\Jwt\Algorithm\Hs256;
use Emarref\Jwt\Claim\Expiration;
use Emarref\Jwt\Encryption\Factory as EncryptionFactory;
use Emarref\Jwt\Jwt;
use Emarref\Jwt\Token;
class JwtAuthenticationResultTest extends TestCase {
public function testGetAccount() {
$account = new Account();
$account->id = 123;
$model = new AuthenticationResult($account, '', null);
$this->assertSame($account, $model->getAccount());
}
public function testGetJwt() {
$model = new AuthenticationResult(new Account(), 'mocked jwt', null);
$this->assertSame('mocked jwt', $model->getJwt());
}
public function testGetSession() {
$model = new AuthenticationResult(new Account(), '', null);
$this->assertNull($model->getSession());
$session = new AccountSession();
$session->id = 321;
$model = new AuthenticationResult(new Account(), '', $session);
$this->assertSame($session, $model->getSession());
}
public function testGetAsResponse() {
$jwtToken = $this->createJwtToken(time() + 3600);
$model = new AuthenticationResult(new Account(), $jwtToken, null);
$result = $model->getAsResponse();
$this->assertSame($jwtToken, $result['access_token']);
$this->assertSame(3600, $result['expires_in']);
/** @noinspection SummerTimeUnsafeTimeManipulationInspection */
$jwtToken = $this->createJwtToken(time() + 86400);
$session = new AccountSession();
$session->refresh_token = 'refresh token';
$model = new AuthenticationResult(new Account(), $jwtToken, $session);
$result = $model->getAsResponse();
$this->assertSame($jwtToken, $result['access_token']);
$this->assertSame('refresh token', $result['refresh_token']);
$this->assertSame(86400, $result['expires_in']);
}
private function createJwtToken(int $expires): string {
$token = new Token();
$token->addClaim(new Expiration($expires));
return (new Jwt())->serialize($token, EncryptionFactory::create(new Hs256('123')));
}
}

View File

@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace api\tests\unit\models\authentication;
use api\models\authentication\AuthenticationResult;
use api\tests\unit\TestCase;
use Lcobucci\JWT\Token;
use Yii;
class AuthenticationResultTest extends TestCase {
public function testGetters() {
$token = new Token();
$model = new AuthenticationResult($token);
$this->assertSame($token, $model->getToken());
$this->assertNull($model->getRefreshToken());
$model = new AuthenticationResult($token, 'refresh_token');
$this->assertSame('refresh_token', $model->getRefreshToken());
}
public function testGetAsResponse() {
$token = Yii::$app->tokens->create();
$jwt = (string)$token;
$model = new AuthenticationResult($token);
$result = $model->formatAsOAuth2Response();
$this->assertSame($jwt, $result['access_token']);
$this->assertEqualsWithDelta(3600, $result['expires_in'], 1);
$this->assertArrayNotHasKey('refresh_token', $result);
$model = new AuthenticationResult($token, 'refresh_token');
$result = $model->formatAsOAuth2Response();
$this->assertSame($jwt, $result['access_token']);
$this->assertEqualsWithDelta(3600, $result['expires_in'], 1);
$this->assertSame('refresh_token', $result['refresh_token']);
}
}

View File

@@ -1,11 +1,11 @@
<?php
declare(strict_types=1);
namespace api\tests\_support\models\authentication;
use api\components\User\AuthenticationResult;
use api\models\authentication\ConfirmEmailForm;
use api\tests\unit\TestCase;
use common\models\Account;
use common\models\AccountSession;
use common\models\EmailActivation;
use common\tests\fixtures\EmailActivationFixture;
@@ -21,8 +21,8 @@ class ConfirmEmailFormTest extends TestCase {
$fixture = $this->tester->grabFixture('emailActivations', 'freshRegistrationConfirmation');
$model = $this->createModel($fixture['key']);
$result = $model->confirm();
$this->assertInstanceOf(AuthenticationResult::class, $result);
$this->assertInstanceOf(AccountSession::class, $result->getSession(), 'session was generated');
$this->assertNotNull($result);
$this->assertNotNull($result->getRefreshToken(), 'session was generated');
$activationExists = EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists();
$this->assertFalse($activationExists, 'email activation key is not exist');
/** @var Account $account */

View File

@@ -1,7 +1,8 @@
<?php
declare(strict_types=1);
namespace api\tests\_support\models\authentication;
use api\components\User\AuthenticationResult;
use api\models\authentication\LoginForm;
use api\tests\unit\TestCase;
use Codeception\Specify;
@@ -135,7 +136,7 @@ class LoginFormTest extends TestCase {
'status' => Account::STATUS_ACTIVE,
]),
]);
$this->assertInstanceOf(AuthenticationResult::class, $model->login(), 'model should login user');
$this->assertNotNull($model->login(), 'model should login user');
$this->assertEmpty($model->getErrors(), 'error message should not be set');
}
@@ -144,7 +145,7 @@ class LoginFormTest extends TestCase {
'login' => $this->tester->grabFixture('accounts', 'user-with-old-password-type')['username'],
'password' => '12345678',
]);
$this->assertInstanceOf(AuthenticationResult::class, $model->login());
$this->assertNotNull($model->login());
$this->assertEmpty($model->getErrors());
$this->assertSame(
Account::PASS_HASH_STRATEGY_YII2,

View File

@@ -2,7 +2,7 @@
namespace api\tests\_support\models\authentication;
use api\components\User\Component;
use api\components\User\Identity;
use api\components\User\IdentityFactory;
use api\models\authentication\LogoutForm;
use api\tests\unit\TestCase;
use Codeception\Specify;
@@ -59,7 +59,7 @@ class LogoutFormTest extends TestCase {
private function getComponentArgs() {
return [
'identityClass' => Identity::class,
'identityClass' => IdentityFactory::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => 'secret',

View File

@@ -1,7 +1,8 @@
<?php
declare(strict_types=1);
namespace api\tests\_support\models\authentication;
use api\components\User\AuthenticationResult;
use api\models\authentication\RecoverPasswordForm;
use api\tests\unit\TestCase;
use common\models\Account;
@@ -24,8 +25,8 @@ class RecoverPasswordFormTest extends TestCase {
'newRePassword' => '12345678',
]);
$result = $model->recoverPassword();
$this->assertInstanceOf(AuthenticationResult::class, $result);
$this->assertNull($result->getSession(), 'session was not generated');
$this->assertNotNull($result);
$this->assertNull($result->getRefreshToken(), 'session was not generated');
$this->assertFalse(EmailActivation::find()->andWhere(['key' => $fixture['key']])->exists());
/** @var Account $account */
$account = Account::findOne($fixture['account_id']);

View File

@@ -1,7 +1,8 @@
<?php
declare(strict_types=1);
namespace codeception\api\unit\models\authentication;
use api\components\User\AuthenticationResult;
use api\models\authentication\RefreshTokenForm;
use api\tests\unit\TestCase;
use Codeception\Specify;
@@ -44,7 +45,7 @@ class RefreshTokenFormTest extends TestCase {
public function testRenew() {
$model = new RefreshTokenForm();
$model->refresh_token = $this->tester->grabFixture('sessions', 'admin')['refresh_token'];
$this->assertInstanceOf(AuthenticationResult::class, $model->renew());
$this->assertNotNull($model->renew());
}
}

View File

@@ -2,7 +2,7 @@
namespace api\tests\unit\modules\accounts\models;
use api\components\User\Component;
use api\components\User\Identity;
use api\components\User\IdentityFactory;
use api\modules\accounts\models\ChangePasswordForm;
use api\tests\unit\TestCase;
use common\components\UserPass;
@@ -57,7 +57,7 @@ class ChangePasswordFormTest extends TestCase {
public function testPerformAction() {
$component = mock(Component::class . '[terminateSessions]', [[
'identityClass' => Identity::class,
'identityClass' => IdentityFactory::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => 'secret',
@@ -119,7 +119,7 @@ class ChangePasswordFormTest extends TestCase {
/** @var Component|\Mockery\MockInterface $component */
$component = mock(Component::class . '[terminateSessions]', [[
'identityClass' => Identity::class,
'identityClass' => IdentityFactory::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => 'secret',

View File

@@ -2,7 +2,7 @@
namespace api\tests\unit\modules\accounts\models;
use api\components\User\Component;
use api\components\User\Identity;
use api\components\User\IdentityFactory;
use api\modules\accounts\models\EnableTwoFactorAuthForm;
use api\tests\unit\TestCase;
use common\helpers\Error as E;
@@ -20,7 +20,7 @@ class EnableTwoFactorAuthFormTest extends TestCase {
/** @var Component|\Mockery\MockInterface $component */
$component = mock(Component::class . '[terminateSessions]', [[
'identityClass' => Identity::class,
'identityClass' => IdentityFactory::class,
'enableSession' => false,
'loginUrl' => null,
'secret' => 'secret',