Объединены сущности для авторизации посредством JWT токенов и токенов, выданных через oAuth2.

Все действия, связанные с аккаунтами, теперь вызываются через url `/api/v1/accounts/<id>/<action>`.
Добавлена вменяемая система разграничения прав на основе RBAC.
Теперь oAuth2 токены генерируются как случайная строка в 40 символов длинной, а не UUID.
Исправлен баг с неправильным временем жизни токена в ответе успешного запроса аутентификации.
Теперь все unit тесты можно успешно прогнать без наличия интернета.
This commit is contained in:
ErickSkrauch
2017-09-19 20:06:16 +03:00
parent 928b3aa7fc
commit dd2c4bc413
173 changed files with 2719 additions and 2748 deletions

View File

@@ -0,0 +1,60 @@
<?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

@@ -1,8 +1,10 @@
<?php
namespace api\components\User;
use api\models\AccountIdentity;
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;
@@ -10,34 +12,33 @@ use Emarref\Jwt\Algorithm\Hs256;
use Emarref\Jwt\Claim;
use Emarref\Jwt\Encryption\Factory as EncryptionFactory;
use Emarref\Jwt\Exception\VerificationException;
use Emarref\Jwt\Jwt;
use Emarref\Jwt\Token;
use Emarref\Jwt\Verification\Context as VerificationContext;
use Exception;
use Yii;
use yii\base\ErrorException;
use yii\base\InvalidConfigException;
use yii\web\IdentityInterface;
use yii\web\User as YiiUserComponent;
/**
* @property AccountSession|null $activeSession
* @property AccountIdentity|null $identity
* @property IdentityInterface|null $identity
*
* @method AccountIdentity|null loginByAccessToken($token, $type = null)
* @method AccountIdentity|null getIdentity($autoRenew = true)
* @method IdentityInterface|null loginByAccessToken($token, $type = null)
* @method IdentityInterface|null getIdentity($autoRenew = true)
*/
class Component extends YiiUserComponent {
const TERMINATE_MINECRAFT_SESSIONS = 1;
const TERMINATE_SITE_SESSIONS = 2;
const DO_NOT_TERMINATE_CURRENT_SESSION = 4;
const TERMINATE_ALL = self::TERMINATE_MINECRAFT_SESSIONS | self::TERMINATE_SITE_SESSIONS;
const KEEP_MINECRAFT_SESSIONS = 1;
const KEEP_SITE_SESSIONS = 2;
const KEEP_CURRENT_SESSION = 4;
const JWT_SUBJECT_PREFIX = 'ely|';
public $enableSession = false;
public $loginUrl = null;
public $identityClass = AccountIdentity::class;
public $identityClass = Identity::class;
public $secret;
@@ -45,6 +46,11 @@ class Component extends YiiUserComponent {
public $sessionTimeout = 'P7D';
/**
* @var Token[]
*/
private static $parsedTokensCache = [];
public function init() {
parent::init();
if (!$this->secret) {
@@ -52,72 +58,60 @@ class Component extends YiiUserComponent {
}
}
/**
* @param IdentityInterface $identity
* @param bool $rememberMe
*
* @return LoginResult|bool
* @throws ErrorException
*/
public function login(IdentityInterface $identity, $rememberMe = false) {
if (!$this->beforeLogin($identity, false, $rememberMe)) {
return false;
public function findIdentityByAccessToken(string $accessToken): ?IdentityInterface {
/** @var \api\components\User\IdentityInterface|string $identityClass */
$identityClass = $this->identityClass;
try {
return $identityClass::findIdentityByAccessToken($accessToken);
} catch (Exception $e) {
Yii::error($e);
return null;
}
}
$this->switchIdentity($identity, 0);
$id = $identity->getId();
public function createJwtAuthenticationToken(Account $account, bool $rememberMe): AuthenticationResult {
$ip = Yii::$app->request->userIP;
$token = $this->createToken($identity);
$token = $this->createToken($account);
if ($rememberMe) {
$session = new AccountSession();
$session->account_id = $id;
$session->account_id = $account->id;
$session->setIp($ip);
$session->generateRefreshToken();
if (!$session->save()) {
throw new ErrorException('Cannot save account session model');
throw new ThisShouldNotHappenException('Cannot save account session model');
}
$token->addClaim(new SessionIdClaim($session->id));
$token->addClaim(new Claim\JwtId($session->id));
} else {
$session = null;
// Если мы не сохраняем сессию, то токен должен жить подольше, чтобы
// не прогорала сессия во время работы с аккаунтом
// Если мы не сохраняем сессию, то токен должен жить подольше,
// чтобы не прогорала сессия во время работы с аккаунтом
$token->addClaim(new Claim\Expiration((new DateTime())->add(new DateInterval($this->sessionTimeout))));
}
$jwt = $this->serializeToken($token);
Yii::info("User '{$id}' logged in from {$ip}.", __METHOD__);
$result = new LoginResult($identity, $jwt, $session);
$this->afterLogin($identity, false, $rememberMe);
return $result;
return new AuthenticationResult($account, $jwt, $session);
}
public function renew(AccountSession $session): RenewResult {
$account = $session->account;
public function renewJwtAuthenticationToken(AccountSession $session): AuthenticationResult {
$transaction = Yii::$app->db->beginTransaction();
try {
$identity = new AccountIdentity($account->attributes);
$token = $this->createToken($identity);
$jwt = $this->serializeToken($token);
$result = new RenewResult($identity, $jwt);
$account = $session->account;
$token = $this->createToken($account);
$token->addClaim(new Claim\JwtId($session->id));
$jwt = $this->serializeToken($token);
$session->setIp(Yii::$app->request->userIP);
$session->last_refreshed_at = time();
if (!$session->save()) {
throw new ErrorException('Cannot update session info');
}
$result = new AuthenticationResult($account, $jwt, $session);
$transaction->commit();
} catch (ErrorException $e) {
$transaction->rollBack();
throw $e;
$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;
}
@@ -126,15 +120,22 @@ class Component extends YiiUserComponent {
* @return Token распаршенный токен
* @throws VerificationException если один из Claims не пройдёт проверку
*/
public function parseToken(string $jwtString) : Token {
$hostInfo = Yii::$app->request->hostInfo;
public function parseToken(string $jwtString): Token {
$token = &self::$parsedTokensCache[$jwtString];
if ($token === null) {
$hostInfo = Yii::$app->request->hostInfo;
$jwt = new Jwt();
$token = $jwt->deserialize($jwtString);
$context = new VerificationContext(EncryptionFactory::create($this->getAlgorithm()));
$context->setAudience($hostInfo);
$context->setIssuer($hostInfo);
$jwt->verify($token, $context);
$jwt = new Jwt();
$notVerifiedToken = $jwt->deserialize($jwtString);
$context = new VerificationContext(EncryptionFactory::create($this->getAlgorithm()));
$context->setAudience($hostInfo);
$context->setIssuer($hostInfo);
$context->setSubject(self::JWT_SUBJECT_PREFIX);
$jwt->verify($notVerifiedToken, $context);
$token = $notVerifiedToken;
}
return $token;
}
@@ -150,19 +151,23 @@ class Component extends YiiUserComponent {
*
* @return AccountSession|null
*/
public function getActiveSession() {
public function getActiveSession(): ?AccountSession {
if ($this->getIsGuest()) {
return null;
}
$bearer = $this->getBearerToken();
if ($bearer === null) {
return null;
}
try {
$token = $this->parseToken($bearer);
} catch (VerificationException $e) {
return null;
}
$sessionId = $token->getPayload()->findClaimByName(SessionIdClaim::NAME);
$sessionId = $token->getPayload()->findClaimByName(Claim\JwtId::NAME);
if ($sessionId === null) {
return null;
}
@@ -170,35 +175,38 @@ class Component extends YiiUserComponent {
return AccountSession::findOne($sessionId->getValue());
}
public function terminateSessions(int $mode = self::TERMINATE_ALL | self::DO_NOT_TERMINATE_CURRENT_SESSION): void {
$identity = $this->getIdentity();
$activeSession = ($mode & self::DO_NOT_TERMINATE_CURRENT_SESSION) ? $this->getActiveSession() : null;
if ($mode & self::TERMINATE_SITE_SESSIONS) {
foreach ($identity->sessions as $session) {
if ($activeSession === null || $activeSession->id !== $session->id) {
public function terminateSessions(Account $account, int $mode = 0): void {
$currentSession = null;
if ($mode & self::KEEP_CURRENT_SESSION) {
$currentSession = $this->getActiveSession();
}
if (!($mode & self::KEEP_SITE_SESSIONS)) {
foreach ($account->sessions as $session) {
if ($currentSession === null || $currentSession->id !== $session->id) {
$session->delete();
}
}
}
if ($mode & self::TERMINATE_MINECRAFT_SESSIONS) {
foreach ($identity->minecraftAccessKeys as $minecraftAccessKey) {
if (!($mode & self::KEEP_MINECRAFT_SESSIONS)) {
foreach ($account->minecraftAccessKeys as $minecraftAccessKey) {
$minecraftAccessKey->delete();
}
}
}
public function getAlgorithm() : AlgorithmInterface {
public function getAlgorithm(): AlgorithmInterface {
return new Hs256($this->secret);
}
protected function serializeToken(Token $token) : string {
protected function serializeToken(Token $token): string {
return (new Jwt())->serialize($token, EncryptionFactory::create($this->getAlgorithm()));
}
protected function createToken(IdentityInterface $identity) : Token {
protected function createToken(Account $account): Token {
$token = new Token();
foreach($this->getClaims($identity) as $claim) {
foreach($this->getClaims($account) as $claim) {
$token->addClaim($claim);
}
@@ -206,25 +214,23 @@ class Component extends YiiUserComponent {
}
/**
* @param IdentityInterface $identity
* @param Account $account
* @return Claim\AbstractClaim[]
*/
protected function getClaims(IdentityInterface $identity) {
protected function getClaims(Account $account): array {
$currentTime = new DateTime();
$hostInfo = Yii::$app->request->hostInfo;
return [
new ScopesClaim([R::ACCOUNTS_WEB_USER]),
new Claim\Audience($hostInfo),
new Claim\Issuer($hostInfo),
new Claim\IssuedAt($currentTime),
new Claim\Expiration($currentTime->add(new DateInterval($this->expirationTimeout))),
new Claim\JwtId($identity->getId()),
new Claim\Subject(self::JWT_SUBJECT_PREFIX . $account->id),
];
}
/**
* @return ?string
*/
private function getBearerToken() {
$authHeader = Yii::$app->request->getHeaders()->get('Authorization');
if ($authHeader === null || !preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) {

View File

@@ -0,0 +1,84 @@
<?php
namespace api\components\User;
use api\components\OAuth2\Entities\AccessTokenEntity;
use common\models\Account;
use common\models\OauthSession;
use Yii;
use yii\base\NotSupportedException;
use yii\web\UnauthorizedHttpException;
/**
* @property Account $account
*/
class Identity implements IdentityInterface {
/**
* @var AccessTokenEntity
*/
private $_accessToken;
/**
* @inheritdoc
* @throws \yii\web\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) {
throw new UnauthorizedHttpException('Incorrect token');
}
if ($model->isExpired()) {
throw new UnauthorizedHttpException('Token expired');
}
return new static($model);
}
public function getAccount(): ?Account {
return $this->getSession()->account;
}
/**
* @return string[]
*/
public function getAssignedPermissions(): array {
return array_keys($this->_accessToken->getScopes());
}
public function getId(): string {
return $this->_accessToken->getId();
}
public function getAuthKey() {
throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth');
}
public function validateAuthKey($authKey) {
throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth');
}
public static function findIdentity($id) {
throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth');
}
private function __construct(AccessTokenEntity $accessToken) {
$this->_accessToken = $accessToken;
}
private function getSession(): OauthSession {
return OauthSession::findOne($this->_accessToken->getSessionId());
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace api\components\User;
use common\models\Account;
interface IdentityInterface extends \yii\web\IdentityInterface {
public static function findIdentityByAccessToken($token, $type = null): IdentityInterface;
/**
* Этот метод используется для получения токена, к которому привязаны права.
* У нас права привязываются к токенам, так что возвращаем именно его id.
*
* @return string
*/
public function getId(): string;
/**
* Метод возвращает аккаунт, который привязан к текущему токену.
* Но не исключено, что токен был выдан и без привязки к аккаунту, так что
* следует это учитывать.
*
* @return Account|null
*/
public function getAccount(): ?Account;
/**
* @return string[]
*/
public function getAssignedPermissions(): array;
}

View File

@@ -0,0 +1,23 @@
<?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

@@ -0,0 +1,94 @@
<?php
namespace api\components\User;
use common\models\Account;
use Emarref\Jwt\Claim\Subject;
use Emarref\Jwt\Exception\ExpiredException;
use Emarref\Jwt\Token;
use Exception;
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;
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');
} catch (Exception $e) {
Yii::error($e);
throw new UnauthorizedHttpException('Incorrect token');
}
return new self($rawToken, $token);
}
public function getAccount(): ?Account {
/** @var Subject $subject */
$subject = $this->token->getPayload()->findClaimByName(Subject::NAME);
if ($subject === null) {
return null;
}
$value = $subject->getValue();
if (!StringHelper::startsWith($value, Component::JWT_SUBJECT_PREFIX)) {
Yii::warning('Unknown jwt subject: ' . $value);
return null;
}
$accountId = (int)mb_substr($value, mb_strlen(Component::JWT_SUBJECT_PREFIX));
$account = Account::findOne($accountId);
if ($account === null) {
return null;
}
return $account;
}
public function getAssignedPermissions(): array {
/** @var Subject $scopesClaim */
$scopesClaim = $this->token->getPayload()->findClaimByName(ScopesClaim::NAME);
if ($scopesClaim === null) {
return [];
}
return explode(',', $scopesClaim->getValue());
}
public function getId(): string {
return $this->rawToken;
}
public function getAuthKey() {
throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth');
}
public function validateAuthKey($authKey) {
throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth');
}
public static function findIdentity($id) {
throw new NotSupportedException('This method used for cookie auth, except we using Bearer auth');
}
private function __construct(string $rawToken, Token $token) {
$this->rawToken = $rawToken;
$this->token = $token;
}
}

View File

@@ -1,67 +0,0 @@
<?php
namespace api\components\User;
use common\models\AccountSession;
use DateInterval;
use DateTime;
use Yii;
use yii\web\IdentityInterface;
class LoginResult {
/**
* @var IdentityInterface
*/
private $identity;
/**
* @var string
*/
private $jwt;
/**
* @var AccountSession|null
*/
private $session;
public function __construct(IdentityInterface $identity, string $jwt, AccountSession $session = null) {
$this->identity = $identity;
$this->jwt = $jwt;
$this->session = $session;
}
public function getIdentity() : IdentityInterface {
return $this->identity;
}
public function getJwt() : string {
return $this->jwt;
}
/**
* @return AccountSession|null
*/
public function getSession() {
return $this->session;
}
public function getAsResponse() {
/** @var Component $component */
$component = Yii::$app->user;
$now = new DateTime();
$expiresIn = (clone $now)->add(new DateInterval($component->expirationTimeout));
$response = [
'access_token' => $this->getJwt(),
'expires_in' => $expiresIn->getTimestamp() - $now->getTimestamp(),
];
$session = $this->getSession();
if ($session !== null) {
$response['refresh_token'] = $session->refresh_token;
}
return $response;
}
}

View File

@@ -1,47 +0,0 @@
<?php
namespace api\components\User;
use DateInterval;
use DateTime;
use Yii;
use yii\web\IdentityInterface;
class RenewResult {
/**
* @var IdentityInterface
*/
private $identity;
/**
* @var string
*/
private $jwt;
public function __construct(IdentityInterface $identity, string $jwt) {
$this->identity = $identity;
$this->jwt = $jwt;
}
public function getIdentity() : IdentityInterface {
return $this->identity;
}
public function getJwt() : string {
return $this->jwt;
}
public function getAsResponse() {
/** @var Component $component */
$component = Yii::$app->user;
$now = new DateTime();
$expiresIn = (clone $now)->add(new DateInterval($component->expirationTimeout));
return [
'access_token' => $this->getJwt(),
'expires_in' => $expiresIn->getTimestamp() - $now->getTimestamp(),
];
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace api\components\User;
use Emarref\Jwt\Claim\AbstractClaim;
class ScopesClaim extends AbstractClaim {
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,17 +0,0 @@
<?php
namespace api\components\User;
use Emarref\Jwt\Claim\AbstractClaim;
class SessionIdClaim extends AbstractClaim {
const NAME = 'sid';
/**
* @inheritdoc
*/
public function getName() {
return self::NAME;
}
}

View File

@@ -0,0 +1,28 @@
<?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;
}
}
}