Объединены сущности для авторизации посредством 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

@ -1,8 +0,0 @@
<?php
namespace api\components\ApiUser;
class AccessControl extends \yii\filters\AccessControl {
public $user = 'apiUser';
}

View File

@ -1,21 +0,0 @@
<?php
namespace api\components\ApiUser;
use Yii;
use yii\rbac\CheckAccessInterface;
class AuthChecker implements CheckAccessInterface {
/**
* @inheritdoc
*/
public function checkAccess($token, $permissionName, $params = []) : bool {
$accessToken = Yii::$app->oauth->getAuthServer()->getAccessTokenStorage()->get($token);
if ($accessToken === null) {
return false;
}
return $accessToken->hasScope($permissionName);
}
}

View File

@ -1,24 +0,0 @@
<?php
namespace api\components\ApiUser;
use yii\web\User as YiiUserComponent;
/**
* @property Identity|null $identity
*
* @method Identity|null getIdentity($autoRenew = true)
* @method Identity|null loginByAccessToken($token, $type = null)
*/
class Component extends YiiUserComponent {
public $identityClass = Identity::class;
public $enableSession = false;
public $loginUrl = null;
public function getAccessChecker() {
return new AuthChecker();
}
}

View File

@ -2,9 +2,10 @@
namespace api\components\OAuth2;
use api\components\OAuth2\Storage;
use api\components\OAuth2\Utils\KeyAlgorithm\UuidAlgorithm;
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Util\SecureKey;
use League\OAuth2\Server\Storage\AccessTokenInterface;
use League\OAuth2\Server\Storage\RefreshTokenInterface;
use League\OAuth2\Server\Storage\SessionInterface;
use yii\base\Component as BaseComponent;
/**
@ -34,11 +35,21 @@ class Component extends BaseComponent {
$authServer->addGrantType(new Grants\ClientCredentialsGrant());
$this->_authServer = $authServer;
SecureKey::setAlgorithm(new UuidAlgorithm());
}
return $this->_authServer;
}
public function getAccessTokenStorage(): AccessTokenInterface {
return $this->getAuthServer()->getAccessTokenStorage();
}
public function getRefreshTokenStorage(): RefreshTokenInterface {
return $this->getAuthServer()->getRefreshTokenStorage();
}
public function getSessionStorage(): SessionInterface {
return $this->getAuthServer()->getSessionStorage();
}
}

View File

@ -6,7 +6,7 @@ use api\components\OAuth2\Entities\AuthCodeEntity;
use api\components\OAuth2\Entities\ClientEntity;
use api\components\OAuth2\Entities\RefreshTokenEntity;
use api\components\OAuth2\Entities\SessionEntity;
use common\models\OauthScope;
use api\components\OAuth2\Storage\ScopeStorage;
use League\OAuth2\Server\Entity\AuthCodeEntity as BaseAuthCodeEntity;
use League\OAuth2\Server\Entity\ClientEntity as BaseClientEntity;
use League\OAuth2\Server\Event\ClientAuthenticationFailedEvent;
@ -178,7 +178,7 @@ class AuthCodeGrant extends AbstractGrant {
// Generate the access token
$accessToken = new AccessTokenEntity($this->server);
$accessToken->setId(SecureKey::generate()); // TODO: generate code based on permissions
$accessToken->setId(SecureKey::generate());
$accessToken->setExpireTime($this->getAccessTokenTTL() + time());
foreach ($authCodeScopes as $authCodeScope) {
@ -194,7 +194,7 @@ class AuthCodeGrant extends AbstractGrant {
$this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL());
// Выдаём refresh_token, если запрошен offline_access
if (isset($accessToken->getScopes()[OauthScope::OFFLINE_ACCESS])) {
if (isset($accessToken->getScopes()[ScopeStorage::OFFLINE_ACCESS])) {
/** @var RefreshTokenGrant $refreshTokenGrant */
$refreshTokenGrant = $this->server->getGrantType('refresh_token');
$refreshToken = new RefreshTokenEntity($this->server);
@ -223,12 +223,12 @@ class AuthCodeGrant extends AbstractGrant {
* Так что оборачиваем функцию разбора скоупов, заменяя пробелы на запятые.
*
* @param string $scopeParam
* @param ClientEntity $client
* @param BaseClientEntity $client
* @param string $redirectUri
*
* @return \League\OAuth2\Server\Entity\ScopeEntity[]
*/
public function validateScopes($scopeParam = '', ClientEntity $client, $redirectUri = null) {
public function validateScopes($scopeParam = '', BaseClientEntity $client, $redirectUri = null) {
$scopes = str_replace(' ', $this->server->getScopeDelimiter(), $scopeParam);
return parent::validateScopes($scopes, $client, $redirectUri);
}

View File

@ -18,14 +18,12 @@ class ClientCredentialsGrant extends AbstractGrant {
* @throws \League\OAuth2\Server\Exception\OAuthException
*/
public function completeFlow(): array {
// Get the required params
$clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser());
if ($clientId === null) {
throw new Exception\InvalidRequestException('client_id');
}
$clientSecret = $this->server->getRequest()->request->get('client_secret',
$this->server->getRequest()->getPassword());
$clientSecret = $this->server->getRequest()->request->get('client_secret');
if ($clientSecret === null) {
throw new Exception\InvalidRequestException('client_secret');
}
@ -74,12 +72,12 @@ class ClientCredentialsGrant extends AbstractGrant {
* Так что оборачиваем функцию разбора скоупов, заменяя пробелы на запятые.
*
* @param string $scopeParam
* @param ClientEntity $client
* @param BaseClientEntity $client
* @param string $redirectUri
*
* @return \League\OAuth2\Server\Entity\ScopeEntity[]
*/
public function validateScopes($scopeParam = '', ClientEntity $client, $redirectUri = null) {
public function validateScopes($scopeParam = '', BaseClientEntity $client, $redirectUri = null) {
$scopes = str_replace(' ', $this->server->getScopeDelimiter(), $scopeParam);
return parent::validateScopes($scopes, $client, $redirectUri);
}

View File

@ -51,12 +51,12 @@ class RefreshTokenGrant extends AbstractGrant {
* Так что оборачиваем функцию разбора скоупов, заменяя пробелы на запятые.
*
* @param string $scopeParam
* @param ClientEntity $client
* @param BaseClientEntity $client
* @param string $redirectUri
*
* @return \League\OAuth2\Server\Entity\ScopeEntity[]
*/
public function validateScopes($scopeParam = '', ClientEntity $client, $redirectUri = null) {
public function validateScopes($scopeParam = '', BaseClientEntity $client, $redirectUri = null) {
$scopes = str_replace(' ', $this->server->getScopeDelimiter(), $scopeParam);
return parent::validateScopes($scopes, $client, $redirectUri);
}
@ -143,7 +143,7 @@ class RefreshTokenGrant extends AbstractGrant {
// Generate a new access token and assign it the correct sessions
$newAccessToken = new AccessTokenEntity($this->server);
$newAccessToken->setId(SecureKey::generate()); // TODO: generate based on permissions
$newAccessToken->setId(SecureKey::generate());
$newAccessToken->setExpireTime($this->getAccessTokenTTL() + time());
$newAccessToken->setSession($session);

View File

@ -3,46 +3,84 @@ namespace api\components\OAuth2\Storage;
use api\components\OAuth2\Entities\ClientEntity;
use api\components\OAuth2\Entities\ScopeEntity;
use common\models\OauthScope;
use Assert\Assert;
use common\rbac\Permissions as P;
use League\OAuth2\Server\Storage\AbstractStorage;
use League\OAuth2\Server\Storage\ScopeInterface;
use yii\base\ErrorException;
class ScopeStorage extends AbstractStorage implements ScopeInterface {
public const OFFLINE_ACCESS = 'offline_access';
private const PUBLIC_SCOPES_TO_INTERNAL_PERMISSIONS = [
'account_info' => P::OBTAIN_OWN_ACCOUNT_INFO,
'account_email' => P::OBTAIN_ACCOUNT_EMAIL,
'account_block' => P::BLOCK_ACCOUNT,
'internal_account_info' => P::OBTAIN_EXTENDED_ACCOUNT_INFO,
];
private const AUTHORIZATION_CODE_PERMISSIONS = [
P::OBTAIN_OWN_ACCOUNT_INFO,
P::OBTAIN_ACCOUNT_EMAIL,
P::MINECRAFT_SERVER_SESSION,
self::OFFLINE_ACCESS,
];
private const CLIENT_CREDENTIALS_PERMISSIONS = [
];
private const CLIENT_CREDENTIALS_PERMISSIONS_INTERNAL = [
P::BLOCK_ACCOUNT,
P::OBTAIN_EXTENDED_ACCOUNT_INFO,
];
/**
* @inheritdoc
* @param string $scope
* @param string $grantType передаётся, если запрос поступает из grant. В этом случае нужно отфильтровать
* только те права, которые можно получить на этом grant.
* @param string $clientId
*
* @return ScopeEntity|null
*/
public function get($scope, $grantType = null, $clientId = null) {
$query = OauthScope::find();
public function get($scope, $grantType = null, $clientId = null): ?ScopeEntity {
$permission = $this->convertToInternalPermission($scope);
if ($grantType === 'authorization_code') {
$query->onlyPublic()->usersScopes();
$permissions = self::AUTHORIZATION_CODE_PERMISSIONS;
} elseif ($grantType === 'client_credentials') {
$query->machineScopes();
$permissions = self::CLIENT_CREDENTIALS_PERMISSIONS;
$isTrusted = false;
if ($clientId !== null) {
/** @var ClientEntity $client */
$client = $this->server->getClientStorage()->get($clientId);
if (!$client instanceof ClientEntity) {
throw new ErrorException('client storage must return instance of ' . ClientEntity::class);
}
Assert::that($client)->isInstanceOf(ClientEntity::class);
$isTrusted = $client->isTrusted();
}
if (!$isTrusted) {
$query->onlyPublic();
if ($isTrusted) {
$permissions = array_merge($permissions, self::CLIENT_CREDENTIALS_PERMISSIONS_INTERNAL);
}
} else {
$permissions = array_merge(
self::AUTHORIZATION_CODE_PERMISSIONS,
self::CLIENT_CREDENTIALS_PERMISSIONS,
self::CLIENT_CREDENTIALS_PERMISSIONS_INTERNAL
);
}
$scopes = $query->all();
if (!in_array($scope, $scopes, true)) {
if (!in_array($permission, $permissions, true)) {
return null;
}
$entity = new ScopeEntity($this->server);
$entity->setId($scope);
$entity->setId($permission);
return $entity;
}
private function convertToInternalPermission(string $publicScope): string {
return self::PUBLIC_SCOPES_TO_INTERNAL_PERMISSIONS[$publicScope] ?? $publicScope;
}
}

View File

@ -1,16 +0,0 @@
<?php
namespace api\components\OAuth2\Utils\KeyAlgorithm;
use League\OAuth2\Server\Util\KeyAlgorithm\KeyAlgorithmInterface;
use Ramsey\Uuid\Uuid;
class UuidAlgorithm implements KeyAlgorithmInterface {
/**
* @inheritdoc
*/
public function generate($len = 40) : string {
return Uuid::uuid4()->toString();
}
}

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

@ -1,20 +1,15 @@
<?php
namespace api\components\ApiUser;
namespace api\components\User;
use api\components\OAuth2\Entities\AccessTokenEntity;
use common\models\Account;
use common\models\OauthClient;
use common\models\OauthSession;
use Yii;
use yii\base\NotSupportedException;
use yii\web\IdentityInterface;
use yii\web\UnauthorizedHttpException;
/**
* @property Account $account
* @property OauthClient $client
* @property OauthSession $session
* @property AccessTokenEntity $accessToken
* @property Account $account
*/
class Identity implements IdentityInterface {
@ -25,44 +20,43 @@ class Identity implements IdentityInterface {
/**
* @inheritdoc
* @throws \yii\web\UnauthorizedHttpException
* @return IdentityInterface
*/
public static function findIdentityByAccessToken($token, $type = null): self {
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->getAuthServer()->getAccessTokenStorage()->get($token);
$model = Yii::$app->oauth->getAccessTokenStorage()->get($token);
if ($model === null) {
throw new UnauthorizedHttpException('Incorrect token');
} elseif ($model->isExpired()) {
}
if ($model->isExpired()) {
throw new UnauthorizedHttpException('Token expired');
}
return new static($model);
}
private function __construct(AccessTokenEntity $accessToken) {
$this->_accessToken = $accessToken;
}
public function getAccount(): Account {
public function getAccount(): ?Account {
return $this->getSession()->account;
}
public function getClient(): OauthClient {
return $this->getSession()->client;
}
public function getSession(): OauthSession {
return OauthSession::findOne($this->_accessToken->getSessionId());
}
public function getAccessToken(): AccessTokenEntity {
return $this->_accessToken;
}
/**
* Этот метод используется для получения токена, к которому привязаны права.
* У нас права привязываются к токенам, так что возвращаем именно его id.
* @inheritdoc
* @return string[]
*/
public function getAssignedPermissions(): array {
return array_keys($this->_accessToken->getScopes());
}
public function getId(): string {
return $this->_accessToken->getId();
}
@ -79,4 +73,12 @@ class Identity implements IdentityInterface {
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;
}
}
}