mirror of
https://github.com/elyby/accounts.git
synced 2025-05-31 14:11:46 +05:30
Объединены сущности для авторизации посредством JWT токенов и токенов, выданных через oAuth2.
Все действия, связанные с аккаунтами, теперь вызываются через url `/api/v1/accounts/<id>/<action>`. Добавлена вменяемая система разграничения прав на основе RBAC. Теперь oAuth2 токены генерируются как случайная строка в 40 символов длинной, а не UUID. Исправлен баг с неправильным временем жизни токена в ответе успешного запроса аутентификации. Теперь все unit тесты можно успешно прогнать без наличия интернета.
This commit is contained in:
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -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);
|
||||
}
|
||||
|
@@ -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);
|
||||
}
|
||||
|
@@ -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);
|
||||
|
||||
|
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -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();
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user