mirror of
https://github.com/elyby/accounts.git
synced 2025-05-31 14:11:46 +05:30
Все реализации Grant'ов для oAuth перенесены в проект. Форк league/oauth2-client больше не используется
This commit is contained in:
@ -1,67 +1,40 @@
|
|||||||
<?php
|
<?php
|
||||||
namespace api\components\OAuth2;
|
namespace api\components\OAuth2;
|
||||||
|
|
||||||
use api\components\OAuth2\Storage\AuthCodeStorage;
|
use api\components\OAuth2\Storage;
|
||||||
use api\components\OAuth2\Storage\RefreshTokenStorage;
|
|
||||||
use api\components\OAuth2\Storage\AccessTokenStorage;
|
|
||||||
use api\components\OAuth2\Storage\ClientStorage;
|
|
||||||
use api\components\OAuth2\Storage\ScopeStorage;
|
|
||||||
use api\components\OAuth2\Storage\SessionStorage;
|
|
||||||
use api\components\OAuth2\Utils\KeyAlgorithm\UuidAlgorithm;
|
use api\components\OAuth2\Utils\KeyAlgorithm\UuidAlgorithm;
|
||||||
use League\OAuth2\Server\AuthorizationServer;
|
use League\OAuth2\Server\AuthorizationServer;
|
||||||
use League\OAuth2\Server\Grant;
|
|
||||||
use League\OAuth2\Server\Util\SecureKey;
|
use League\OAuth2\Server\Util\SecureKey;
|
||||||
use yii\base\InvalidConfigException;
|
use yii\base\Component as BaseComponent;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @property AuthorizationServer $authServer
|
* @property AuthorizationServer $authServer
|
||||||
*/
|
*/
|
||||||
class Component extends \yii\base\Component {
|
class Component extends BaseComponent {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @var AuthorizationServer
|
* @var AuthorizationServer
|
||||||
*/
|
*/
|
||||||
private $_authServer;
|
private $_authServer;
|
||||||
|
|
||||||
/**
|
public function getAuthServer(): AuthorizationServer {
|
||||||
* @var string[]
|
|
||||||
*/
|
|
||||||
public $grantTypes = [];
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @var array grant type => class
|
|
||||||
*/
|
|
||||||
public $grantMap = [
|
|
||||||
'authorization_code' => Grant\AuthCodeGrant::class,
|
|
||||||
'client_credentials' => Grant\ClientCredentialsGrant::class,
|
|
||||||
'password' => Grant\PasswordGrant::class,
|
|
||||||
'refresh_token' => Grant\RefreshTokenGrant::class,
|
|
||||||
];
|
|
||||||
|
|
||||||
public function getAuthServer() {
|
|
||||||
if ($this->_authServer === null) {
|
if ($this->_authServer === null) {
|
||||||
$authServer = new AuthorizationServer();
|
$authServer = new AuthorizationServer();
|
||||||
$authServer->setAccessTokenStorage(new AccessTokenStorage());
|
$authServer->setAccessTokenStorage(new Storage\AccessTokenStorage());
|
||||||
$authServer->setClientStorage(new ClientStorage());
|
$authServer->setClientStorage(new Storage\ClientStorage());
|
||||||
$authServer->setScopeStorage(new ScopeStorage());
|
$authServer->setScopeStorage(new Storage\ScopeStorage());
|
||||||
$authServer->setSessionStorage(new SessionStorage());
|
$authServer->setSessionStorage(new Storage\SessionStorage());
|
||||||
$authServer->setAuthCodeStorage(new AuthCodeStorage());
|
$authServer->setAuthCodeStorage(new Storage\AuthCodeStorage());
|
||||||
$authServer->setRefreshTokenStorage(new RefreshTokenStorage());
|
$authServer->setRefreshTokenStorage(new Storage\RefreshTokenStorage());
|
||||||
$authServer->setScopeDelimiter(',');
|
$authServer->setScopeDelimiter(',');
|
||||||
$authServer->setAccessTokenTTL(86400); // 1d
|
$authServer->setAccessTokenTTL(86400); // 1d
|
||||||
|
|
||||||
|
$authServer->addGrantType(new Grants\AuthCodeGrant());
|
||||||
|
$authServer->addGrantType(new Grants\RefreshTokenGrant());
|
||||||
|
$authServer->addGrantType(new Grants\ClientCredentialsGrant());
|
||||||
|
|
||||||
$this->_authServer = $authServer;
|
$this->_authServer = $authServer;
|
||||||
|
|
||||||
foreach ($this->grantTypes as $grantType) {
|
|
||||||
if (!isset($this->grantMap[$grantType])) {
|
|
||||||
throw new InvalidConfigException('Invalid grant type');
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @var Grant\GrantTypeInterface $grant */
|
|
||||||
$grant = new $this->grantMap[$grantType]();
|
|
||||||
$this->_authServer->addGrantType($grant);
|
|
||||||
}
|
|
||||||
|
|
||||||
SecureKey::setAlgorithm(new UuidAlgorithm());
|
SecureKey::setAlgorithm(new UuidAlgorithm());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,21 +1,221 @@
|
|||||||
<?php
|
<?php
|
||||||
namespace api\components\OAuth2\Grants;
|
namespace api\components\OAuth2\Grants;
|
||||||
|
|
||||||
use api\components\OAuth2\Entities;
|
use api\components\OAuth2\Entities\AccessTokenEntity;
|
||||||
use League\OAuth2\Server\Entity\ClientEntity;
|
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 League\OAuth2\Server\Entity\AuthCodeEntity as BaseAuthCodeEntity;
|
||||||
|
use League\OAuth2\Server\Entity\ClientEntity as BaseClientEntity;
|
||||||
|
use League\OAuth2\Server\Event\ClientAuthenticationFailedEvent;
|
||||||
|
use League\OAuth2\Server\Exception;
|
||||||
|
use League\OAuth2\Server\Grant\AbstractGrant;
|
||||||
|
use League\OAuth2\Server\Util\SecureKey;
|
||||||
|
|
||||||
class AuthCodeGrant extends \League\OAuth2\Server\Grant\AuthCodeGrant {
|
class AuthCodeGrant extends AbstractGrant {
|
||||||
|
|
||||||
protected function createAccessTokenEntity() {
|
protected $identifier = 'authorization_code';
|
||||||
return new Entities\AccessTokenEntity($this->server);
|
|
||||||
|
protected $responseType = 'code';
|
||||||
|
|
||||||
|
protected $authTokenTTL = 600;
|
||||||
|
|
||||||
|
protected $requireClientSecret = true;
|
||||||
|
|
||||||
|
public function setAuthTokenTTL(int $authTokenTTL): void {
|
||||||
|
$this->authTokenTTL = $authTokenTTL;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function createRefreshTokenEntity() {
|
public function setRequireClientSecret(bool $required): void {
|
||||||
return new Entities\RefreshTokenEntity($this->server);
|
$this->requireClientSecret = $required;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function createSessionEntity() {
|
public function shouldRequireClientSecret(): bool {
|
||||||
return new Entities\SessionEntity($this->server);
|
return $this->requireClientSecret;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check authorize parameters
|
||||||
|
*
|
||||||
|
* @return AuthorizeParams Authorize request parameters
|
||||||
|
* @throws Exception\OAuthException
|
||||||
|
*
|
||||||
|
* @throws
|
||||||
|
*/
|
||||||
|
public function checkAuthorizeParams(): AuthorizeParams {
|
||||||
|
// Get required params
|
||||||
|
$clientId = $this->server->getRequest()->query->get('client_id');
|
||||||
|
if ($clientId === null) {
|
||||||
|
throw new Exception\InvalidRequestException('client_id');
|
||||||
|
}
|
||||||
|
|
||||||
|
$redirectUri = $this->server->getRequest()->query->get('redirect_uri');
|
||||||
|
if ($redirectUri === null) {
|
||||||
|
throw new Exception\InvalidRequestException('redirect_uri');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate client ID and redirect URI
|
||||||
|
$client = $this->server->getClientStorage()->get($clientId, null, $redirectUri, $this->getIdentifier());
|
||||||
|
if (!$client instanceof ClientEntity) {
|
||||||
|
$this->server->getEventEmitter()->emit(new ClientAuthenticationFailedEvent($this->server->getRequest()));
|
||||||
|
throw new Exception\InvalidClientException();
|
||||||
|
}
|
||||||
|
|
||||||
|
$state = $this->server->getRequest()->query->get('state');
|
||||||
|
if ($state === null && $this->server->stateParamRequired()) {
|
||||||
|
throw new Exception\InvalidRequestException('state', $redirectUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
$responseType = $this->server->getRequest()->query->get('response_type');
|
||||||
|
if ($responseType === null) {
|
||||||
|
throw new Exception\InvalidRequestException('response_type', $redirectUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure response type is one that is recognised
|
||||||
|
if (!in_array($responseType, $this->server->getResponseTypes(), true)) {
|
||||||
|
throw new Exception\UnsupportedResponseTypeException($responseType, $redirectUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate any scopes that are in the request
|
||||||
|
$scopeParam = $this->server->getRequest()->query->get('scope', '');
|
||||||
|
$scopes = $this->validateScopes($scopeParam, $client, $redirectUri);
|
||||||
|
|
||||||
|
return new AuthorizeParams($client, $redirectUri, $state, $responseType, $scopes);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse a new authorize request
|
||||||
|
*
|
||||||
|
* @param string $type The session owner's type
|
||||||
|
* @param string $typeId The session owner's ID
|
||||||
|
* @param AuthorizeParams $authParams The authorize request $_GET parameters
|
||||||
|
*
|
||||||
|
* @return string An authorisation code
|
||||||
|
*/
|
||||||
|
public function newAuthorizeRequest(string $type, string $typeId, AuthorizeParams $authParams): string {
|
||||||
|
// Create a new session
|
||||||
|
$session = new SessionEntity($this->server);
|
||||||
|
$session->setOwner($type, $typeId);
|
||||||
|
$session->associateClient($authParams->getClient());
|
||||||
|
|
||||||
|
// Create a new auth code
|
||||||
|
$authCode = new AuthCodeEntity($this->server);
|
||||||
|
$authCode->setId(SecureKey::generate());
|
||||||
|
$authCode->setRedirectUri($authParams->getRedirectUri());
|
||||||
|
$authCode->setExpireTime(time() + $this->authTokenTTL);
|
||||||
|
|
||||||
|
foreach ($authParams->getScopes() as $scope) {
|
||||||
|
$authCode->associateScope($scope);
|
||||||
|
$session->associateScope($scope);
|
||||||
|
}
|
||||||
|
|
||||||
|
$session->save();
|
||||||
|
$authCode->setSession($session);
|
||||||
|
$authCode->save();
|
||||||
|
|
||||||
|
return $authCode->generateRedirectUri($authParams->getState());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Complete the auth code grant
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
|
*
|
||||||
|
* @throws 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());
|
||||||
|
if ($clientSecret === null && $this->shouldRequireClientSecret()) {
|
||||||
|
throw new Exception\InvalidRequestException('client_secret');
|
||||||
|
}
|
||||||
|
|
||||||
|
$redirectUri = $this->server->getRequest()->request->get('redirect_uri');
|
||||||
|
if ($redirectUri === null) {
|
||||||
|
throw new Exception\InvalidRequestException('redirect_uri');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate client ID and client secret
|
||||||
|
$client = $this->server->getClientStorage()->get($clientId, $clientSecret, $redirectUri, $this->getIdentifier());
|
||||||
|
if (!$client instanceof BaseClientEntity) {
|
||||||
|
$this->server->getEventEmitter()->emit(new ClientAuthenticationFailedEvent($this->server->getRequest()));
|
||||||
|
throw new Exception\InvalidClientException();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate the auth code
|
||||||
|
$authCode = $this->server->getRequest()->request->get('code');
|
||||||
|
if ($authCode === null) {
|
||||||
|
throw new Exception\InvalidRequestException('code');
|
||||||
|
}
|
||||||
|
|
||||||
|
$code = $this->server->getAuthCodeStorage()->get($authCode);
|
||||||
|
if (($code instanceof BaseAuthCodeEntity) === false) {
|
||||||
|
throw new Exception\InvalidRequestException('code');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure the auth code hasn't expired
|
||||||
|
if ($code->isExpired()) {
|
||||||
|
throw new Exception\InvalidRequestException('code');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check redirect URI presented matches redirect URI originally used in authorize request
|
||||||
|
if ($code->getRedirectUri() !== $redirectUri) {
|
||||||
|
throw new Exception\InvalidRequestException('redirect_uri');
|
||||||
|
}
|
||||||
|
|
||||||
|
$session = $code->getSession();
|
||||||
|
$session->associateClient($client);
|
||||||
|
|
||||||
|
$authCodeScopes = $code->getScopes();
|
||||||
|
|
||||||
|
// Generate the access token
|
||||||
|
$accessToken = new AccessTokenEntity($this->server);
|
||||||
|
$accessToken->setId(SecureKey::generate()); // TODO: generate code based on permissions
|
||||||
|
$accessToken->setExpireTime($this->getAccessTokenTTL() + time());
|
||||||
|
|
||||||
|
foreach ($authCodeScopes as $authCodeScope) {
|
||||||
|
$session->associateScope($authCodeScope);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($session->getScopes() as $scope) {
|
||||||
|
$accessToken->associateScope($scope);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->server->getTokenType()->setSession($session);
|
||||||
|
$this->server->getTokenType()->setParam('access_token', $accessToken->getId());
|
||||||
|
$this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL());
|
||||||
|
|
||||||
|
// Выдаём refresh_token, если запрошен offline_access
|
||||||
|
if (isset($accessToken->getScopes()[OauthScope::OFFLINE_ACCESS])) {
|
||||||
|
/** @var RefreshTokenGrant $refreshTokenGrant */
|
||||||
|
$refreshTokenGrant = $this->server->getGrantType('refresh_token');
|
||||||
|
$refreshToken = new RefreshTokenEntity($this->server);
|
||||||
|
$refreshToken->setId(SecureKey::generate());
|
||||||
|
$refreshToken->setExpireTime($refreshTokenGrant->getRefreshTokenTTL() + time());
|
||||||
|
$this->server->getTokenType()->setParam('refresh_token', $refreshToken->getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Expire the auth code
|
||||||
|
$code->expire();
|
||||||
|
|
||||||
|
// Save all the things
|
||||||
|
$accessToken->setSession($session);
|
||||||
|
$accessToken->save();
|
||||||
|
|
||||||
|
if (isset($refreshToken)) {
|
||||||
|
$refreshToken->setAccessToken($accessToken);
|
||||||
|
$refreshToken->save();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->server->getTokenType()->generateResponse();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
58
api/components/OAuth2/Grants/AuthorizeParams.php
Normal file
58
api/components/OAuth2/Grants/AuthorizeParams.php
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
<?php
|
||||||
|
namespace api\components\OAuth2\Grants;
|
||||||
|
|
||||||
|
use api\components\OAuth2\Entities\ClientEntity;
|
||||||
|
|
||||||
|
class AuthorizeParams {
|
||||||
|
|
||||||
|
private $client;
|
||||||
|
|
||||||
|
private $redirectUri;
|
||||||
|
|
||||||
|
private $state;
|
||||||
|
|
||||||
|
private $responseType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var \api\components\OAuth2\Entities\ScopeEntity[]
|
||||||
|
*/
|
||||||
|
private $scopes;
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
ClientEntity $client,
|
||||||
|
string $redirectUri,
|
||||||
|
?string $state,
|
||||||
|
string $responseType,
|
||||||
|
array $scopes
|
||||||
|
) {
|
||||||
|
$this->client = $client;
|
||||||
|
$this->redirectUri = $redirectUri;
|
||||||
|
$this->state = $state;
|
||||||
|
$this->responseType = $responseType;
|
||||||
|
$this->scopes = $scopes;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getClient(): ClientEntity {
|
||||||
|
return $this->client;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getRedirectUri(): string {
|
||||||
|
return $this->redirectUri;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getState(): ?string {
|
||||||
|
return $this->state;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getResponseType(): string {
|
||||||
|
return $this->responseType;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return \api\components\OAuth2\Entities\ScopeEntity[]
|
||||||
|
*/
|
||||||
|
public function getScopes(): array {
|
||||||
|
return $this->scopes ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,21 +1,72 @@
|
|||||||
<?php
|
<?php
|
||||||
namespace api\components\OAuth2\Grants;
|
namespace api\components\OAuth2\Grants;
|
||||||
|
|
||||||
use api\components\OAuth2\Entities;
|
use api\components\OAuth2\Entities\AccessTokenEntity;
|
||||||
use League\OAuth2\Server\Entity\ClientEntity;
|
use api\components\OAuth2\Entities\SessionEntity;
|
||||||
|
use League\OAuth2\Server\Entity\ClientEntity as BaseClientEntity;
|
||||||
|
use League\OAuth2\Server\Event;
|
||||||
|
use League\OAuth2\Server\Exception;
|
||||||
|
use League\OAuth2\Server\Grant\AbstractGrant;
|
||||||
|
use League\OAuth2\Server\Util\SecureKey;
|
||||||
|
|
||||||
class ClientCredentialsGrant extends \League\OAuth2\Server\Grant\ClientCredentialsGrant {
|
class ClientCredentialsGrant extends AbstractGrant {
|
||||||
|
|
||||||
protected function createAccessTokenEntity() {
|
protected $identifier = 'client_credentials';
|
||||||
return new Entities\AccessTokenEntity($this->server);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function createRefreshTokenEntity() {
|
/**
|
||||||
return new Entities\RefreshTokenEntity($this->server);
|
* @return array
|
||||||
}
|
* @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');
|
||||||
|
}
|
||||||
|
|
||||||
protected function createSessionEntity() {
|
$clientSecret = $this->server->getRequest()->request->get('client_secret',
|
||||||
return new Entities\SessionEntity($this->server);
|
$this->server->getRequest()->getPassword());
|
||||||
|
if ($clientSecret === null) {
|
||||||
|
throw new Exception\InvalidRequestException('client_secret');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate client ID and client secret
|
||||||
|
$client = $this->server->getClientStorage()->get($clientId, $clientSecret, null, $this->getIdentifier());
|
||||||
|
if (!$client instanceof BaseClientEntity) {
|
||||||
|
$this->server->getEventEmitter()->emit(new Event\ClientAuthenticationFailedEvent($this->server->getRequest()));
|
||||||
|
throw new Exception\InvalidClientException();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate any scopes that are in the request
|
||||||
|
$scopeParam = $this->server->getRequest()->request->get('scope', '');
|
||||||
|
$scopes = $this->validateScopes($scopeParam, $client);
|
||||||
|
|
||||||
|
// Create a new session
|
||||||
|
$session = new SessionEntity($this->server);
|
||||||
|
$session->setOwner('client', $client->getId());
|
||||||
|
$session->associateClient($client);
|
||||||
|
|
||||||
|
// Generate an access token
|
||||||
|
$accessToken = new AccessTokenEntity($this->server);
|
||||||
|
$accessToken->setId(SecureKey::generate());
|
||||||
|
$accessToken->setExpireTime($this->getAccessTokenTTL() + time());
|
||||||
|
|
||||||
|
// Associate scopes with the session and access token
|
||||||
|
foreach ($scopes as $scope) {
|
||||||
|
$session->associateScope($scope);
|
||||||
|
$accessToken->associateScope($scope);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save everything
|
||||||
|
$session->save();
|
||||||
|
$accessToken->setSession($session);
|
||||||
|
$accessToken->save();
|
||||||
|
|
||||||
|
$this->server->getTokenType()->setSession($session);
|
||||||
|
$this->server->getTokenType()->setParam('access_token', $accessToken->getId());
|
||||||
|
$this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL());
|
||||||
|
|
||||||
|
return $this->server->getTokenType()->generateResponse();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -1,29 +1,49 @@
|
|||||||
<?php
|
<?php
|
||||||
namespace api\components\OAuth2\Grants;
|
namespace api\components\OAuth2\Grants;
|
||||||
|
|
||||||
use api\components\OAuth2\Entities;
|
use api\components\OAuth2\Entities\AccessTokenEntity;
|
||||||
|
use api\components\OAuth2\Entities\RefreshTokenEntity;
|
||||||
use ErrorException;
|
use ErrorException;
|
||||||
use League\OAuth2\Server\Entity\ClientEntity as OriginalClientEntity;
|
use League\OAuth2\Server\Entity\AccessTokenEntity as BaseAccessTokenEntity;
|
||||||
use League\OAuth2\Server\Entity\ClientEntity;
|
use League\OAuth2\Server\Entity\ClientEntity as BaseClientEntity;
|
||||||
use League\OAuth2\Server\Entity\RefreshTokenEntity as OriginalRefreshTokenEntity;
|
use League\OAuth2\Server\Entity\RefreshTokenEntity as BaseRefreshTokenEntity;
|
||||||
use League\OAuth2\Server\Event;
|
use League\OAuth2\Server\Event\ClientAuthenticationFailedEvent;
|
||||||
use League\OAuth2\Server\Exception;
|
use League\OAuth2\Server\Exception;
|
||||||
|
use League\OAuth2\Server\Grant\AbstractGrant;
|
||||||
use League\OAuth2\Server\Util\SecureKey;
|
use League\OAuth2\Server\Util\SecureKey;
|
||||||
|
|
||||||
class RefreshTokenGrant extends \League\OAuth2\Server\Grant\RefreshTokenGrant {
|
class RefreshTokenGrant extends AbstractGrant {
|
||||||
|
|
||||||
public $refreshTokenRotate = false;
|
protected $identifier = 'refresh_token';
|
||||||
|
|
||||||
protected function createAccessTokenEntity() {
|
protected $refreshTokenTTL = 604800;
|
||||||
return new Entities\AccessTokenEntity($this->server);
|
|
||||||
|
protected $refreshTokenRotate = false;
|
||||||
|
|
||||||
|
protected $requireClientSecret = true;
|
||||||
|
|
||||||
|
public function setRefreshTokenTTL($refreshTokenTTL): void {
|
||||||
|
$this->refreshTokenTTL = $refreshTokenTTL;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function createRefreshTokenEntity() {
|
public function getRefreshTokenTTL(): int {
|
||||||
return new Entities\RefreshTokenEntity($this->server);
|
return $this->refreshTokenTTL;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function createSessionEntity() {
|
public function setRefreshTokenRotation(bool $refreshTokenRotate = true): void {
|
||||||
return new Entities\SessionEntity($this->server);
|
$this->refreshTokenRotate = $refreshTokenRotate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function shouldRotateRefreshTokens(): bool {
|
||||||
|
return $this->refreshTokenRotate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setRequireClientSecret(string $required): void {
|
||||||
|
$this->requireClientSecret = $required;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function shouldRequireClientSecret(): bool {
|
||||||
|
return $this->requireClientSecret;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -47,10 +67,11 @@ class RefreshTokenGrant extends \League\OAuth2\Server\Grant\RefreshTokenGrant {
|
|||||||
* Поэтому мы расширили логику RefreshTokenEntity и она теперь знает о сессии, в рамках которой была создана
|
* Поэтому мы расширили логику RefreshTokenEntity и она теперь знает о сессии, в рамках которой была создана
|
||||||
*
|
*
|
||||||
* @inheritdoc
|
* @inheritdoc
|
||||||
|
* @throws \League\OAuth2\Server\Exception\OAuthException
|
||||||
*/
|
*/
|
||||||
public function completeFlow() {
|
public function completeFlow(): array {
|
||||||
$clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser());
|
$clientId = $this->server->getRequest()->request->get('client_id', $this->server->getRequest()->getUser());
|
||||||
if (is_null($clientId)) {
|
if ($clientId === null) {
|
||||||
throw new Exception\InvalidRequestException('client_id');
|
throw new Exception\InvalidRequestException('client_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -58,31 +79,25 @@ class RefreshTokenGrant extends \League\OAuth2\Server\Grant\RefreshTokenGrant {
|
|||||||
'client_secret',
|
'client_secret',
|
||||||
$this->server->getRequest()->getPassword()
|
$this->server->getRequest()->getPassword()
|
||||||
);
|
);
|
||||||
if ($this->shouldRequireClientSecret() && is_null($clientSecret)) {
|
if ($clientSecret === null && $this->shouldRequireClientSecret()) {
|
||||||
throw new Exception\InvalidRequestException('client_secret');
|
throw new Exception\InvalidRequestException('client_secret');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate client ID and client secret
|
// Validate client ID and client secret
|
||||||
$client = $this->server->getClientStorage()->get(
|
$client = $this->server->getClientStorage()->get($clientId, $clientSecret, null, $this->getIdentifier());
|
||||||
$clientId,
|
if (($client instanceof BaseClientEntity) === false) {
|
||||||
$clientSecret,
|
$this->server->getEventEmitter()->emit(new ClientAuthenticationFailedEvent($this->server->getRequest()));
|
||||||
null,
|
|
||||||
$this->getIdentifier()
|
|
||||||
);
|
|
||||||
|
|
||||||
if (($client instanceof OriginalClientEntity) === false) {
|
|
||||||
$this->server->getEventEmitter()->emit(new Event\ClientAuthenticationFailedEvent($this->server->getRequest()));
|
|
||||||
throw new Exception\InvalidClientException();
|
throw new Exception\InvalidClientException();
|
||||||
}
|
}
|
||||||
|
|
||||||
$oldRefreshTokenParam = $this->server->getRequest()->request->get('refresh_token', null);
|
$oldRefreshTokenParam = $this->server->getRequest()->request->get('refresh_token');
|
||||||
if ($oldRefreshTokenParam === null) {
|
if ($oldRefreshTokenParam === null) {
|
||||||
throw new Exception\InvalidRequestException('refresh_token');
|
throw new Exception\InvalidRequestException('refresh_token');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate refresh token
|
// Validate refresh token
|
||||||
$oldRefreshToken = $this->server->getRefreshTokenStorage()->get($oldRefreshTokenParam);
|
$oldRefreshToken = $this->server->getRefreshTokenStorage()->get($oldRefreshTokenParam);
|
||||||
if (($oldRefreshToken instanceof OriginalRefreshTokenEntity) === false) {
|
if (($oldRefreshToken instanceof BaseRefreshTokenEntity) === false) {
|
||||||
throw new Exception\InvalidRefreshException();
|
throw new Exception\InvalidRefreshException();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -91,14 +106,15 @@ class RefreshTokenGrant extends \League\OAuth2\Server\Grant\RefreshTokenGrant {
|
|||||||
throw new Exception\InvalidRefreshException();
|
throw new Exception\InvalidRefreshException();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @var Entities\AccessTokenEntity|null $oldAccessToken */
|
/** @var AccessTokenEntity|null $oldAccessToken */
|
||||||
$oldAccessToken = $oldRefreshToken->getAccessToken();
|
$oldAccessToken = $oldRefreshToken->getAccessToken();
|
||||||
if ($oldAccessToken instanceof Entities\AccessTokenEntity) {
|
if ($oldAccessToken instanceof AccessTokenEntity) {
|
||||||
// Get the scopes for the original session
|
// Get the scopes for the original session
|
||||||
$session = $oldAccessToken->getSession();
|
$session = $oldAccessToken->getSession();
|
||||||
} else {
|
} else {
|
||||||
if (!$oldRefreshToken instanceof Entities\RefreshTokenEntity) {
|
if (!$oldRefreshToken instanceof RefreshTokenEntity) {
|
||||||
throw new ErrorException('oldRefreshToken must be instance of ' . Entities\RefreshTokenEntity::class);
|
/** @noinspection ExceptionsAnnotatingAndHandlingInspection */
|
||||||
|
throw new ErrorException('oldRefreshToken must be instance of ' . RefreshTokenEntity::class);
|
||||||
}
|
}
|
||||||
|
|
||||||
$session = $oldRefreshToken->getSession();
|
$session = $oldRefreshToken->getSession();
|
||||||
@ -126,8 +142,8 @@ class RefreshTokenGrant extends \League\OAuth2\Server\Grant\RefreshTokenGrant {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Generate a new access token and assign it the correct sessions
|
// Generate a new access token and assign it the correct sessions
|
||||||
$newAccessToken = $this->createAccessTokenEntity();
|
$newAccessToken = new AccessTokenEntity($this->server);
|
||||||
$newAccessToken->setId(SecureKey::generate());
|
$newAccessToken->setId(SecureKey::generate()); // TODO: generate based on permissions
|
||||||
$newAccessToken->setExpireTime($this->getAccessTokenTTL() + time());
|
$newAccessToken->setExpireTime($this->getAccessTokenTTL() + time());
|
||||||
$newAccessToken->setSession($session);
|
$newAccessToken->setSession($session);
|
||||||
|
|
||||||
@ -136,7 +152,7 @@ class RefreshTokenGrant extends \League\OAuth2\Server\Grant\RefreshTokenGrant {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Expire the old token and save the new one
|
// Expire the old token and save the new one
|
||||||
($oldAccessToken instanceof Entities\AccessTokenEntity) && $oldAccessToken->expire();
|
$oldAccessToken instanceof BaseAccessTokenEntity && $oldAccessToken->expire();
|
||||||
$newAccessToken->save();
|
$newAccessToken->save();
|
||||||
|
|
||||||
$this->server->getTokenType()->setSession($session);
|
$this->server->getTokenType()->setSession($session);
|
||||||
@ -148,7 +164,7 @@ class RefreshTokenGrant extends \League\OAuth2\Server\Grant\RefreshTokenGrant {
|
|||||||
$oldRefreshToken->expire();
|
$oldRefreshToken->expire();
|
||||||
|
|
||||||
// Generate a new refresh token
|
// Generate a new refresh token
|
||||||
$newRefreshToken = $this->createRefreshTokenEntity();
|
$newRefreshToken = new RefreshTokenEntity($this->server);
|
||||||
$newRefreshToken->setId(SecureKey::generate());
|
$newRefreshToken->setId(SecureKey::generate());
|
||||||
$newRefreshToken->setExpireTime($this->getRefreshTokenTTL() + time());
|
$newRefreshToken->setExpireTime($this->getRefreshTokenTTL() + time());
|
||||||
$newRefreshToken->setAccessToken($newAccessToken);
|
$newRefreshToken->setAccessToken($newAccessToken);
|
||||||
|
@ -3,13 +3,13 @@ namespace api\models;
|
|||||||
|
|
||||||
use api\components\OAuth2\Exception\AcceptRequiredException;
|
use api\components\OAuth2\Exception\AcceptRequiredException;
|
||||||
use api\components\OAuth2\Exception\AccessDeniedException;
|
use api\components\OAuth2\Exception\AccessDeniedException;
|
||||||
|
use api\components\OAuth2\Grants\AuthCodeGrant;
|
||||||
|
use api\components\OAuth2\Grants\AuthorizeParams;
|
||||||
use common\models\Account;
|
use common\models\Account;
|
||||||
use common\models\OauthClient;
|
use common\models\OauthClient;
|
||||||
use common\models\OauthScope;
|
|
||||||
use League\OAuth2\Server\AuthorizationServer;
|
use League\OAuth2\Server\AuthorizationServer;
|
||||||
use League\OAuth2\Server\Exception\InvalidGrantException;
|
use League\OAuth2\Server\Exception\InvalidGrantException;
|
||||||
use League\OAuth2\Server\Exception\OAuthException;
|
use League\OAuth2\Server\Exception\OAuthException;
|
||||||
use League\OAuth2\Server\Grant\AuthCodeGrant;
|
|
||||||
use League\OAuth2\Server\Grant\GrantTypeInterface;
|
use League\OAuth2\Server\Grant\GrantTypeInterface;
|
||||||
use Yii;
|
use Yii;
|
||||||
use yii\helpers\ArrayHelper;
|
use yii\helpers\ArrayHelper;
|
||||||
@ -45,14 +45,13 @@ class OauthProcess {
|
|||||||
public function validate(): array {
|
public function validate(): array {
|
||||||
try {
|
try {
|
||||||
$authParams = $this->getAuthorizationCodeGrant()->checkAuthorizeParams();
|
$authParams = $this->getAuthorizationCodeGrant()->checkAuthorizeParams();
|
||||||
/** @var \League\OAuth2\Server\Entity\ClientEntity $client */
|
$client = $authParams->getClient();
|
||||||
$client = $authParams['client'];
|
|
||||||
/** @var \common\models\OauthClient $clientModel */
|
/** @var \common\models\OauthClient $clientModel */
|
||||||
$clientModel = OauthClient::findOne($client->getId());
|
$clientModel = OauthClient::findOne($client->getId());
|
||||||
$response = $this->buildSuccessResponse(
|
$response = $this->buildSuccessResponse(
|
||||||
Yii::$app->request->getQueryParams(),
|
Yii::$app->request->getQueryParams(),
|
||||||
$clientModel,
|
$clientModel,
|
||||||
$authParams['scopes']
|
$authParams->getScopes()
|
||||||
);
|
);
|
||||||
} catch (OAuthException $e) {
|
} catch (OAuthException $e) {
|
||||||
$response = $this->buildErrorResponse($e);
|
$response = $this->buildErrorResponse($e);
|
||||||
@ -85,10 +84,8 @@ class OauthProcess {
|
|||||||
$grant = $this->getAuthorizationCodeGrant();
|
$grant = $this->getAuthorizationCodeGrant();
|
||||||
$authParams = $grant->checkAuthorizeParams();
|
$authParams = $grant->checkAuthorizeParams();
|
||||||
$account = Yii::$app->user->identity;
|
$account = Yii::$app->user->identity;
|
||||||
/** @var \League\OAuth2\Server\Entity\ClientEntity $client */
|
|
||||||
$client = $authParams['client'];
|
|
||||||
/** @var \common\models\OauthClient $clientModel */
|
/** @var \common\models\OauthClient $clientModel */
|
||||||
$clientModel = OauthClient::findOne($client->getId());
|
$clientModel = OauthClient::findOne($authParams->getClient()->getId());
|
||||||
|
|
||||||
if (!$this->canAutoApprove($account, $clientModel, $authParams)) {
|
if (!$this->canAutoApprove($account, $clientModel, $authParams)) {
|
||||||
$isAccept = Yii::$app->request->post('accept');
|
$isAccept = Yii::$app->request->post('accept');
|
||||||
@ -97,7 +94,7 @@ class OauthProcess {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!$isAccept) {
|
if (!$isAccept) {
|
||||||
throw new AccessDeniedException($authParams['redirect_uri']);
|
throw new AccessDeniedException($authParams->getRedirectUri());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -135,7 +132,6 @@ class OauthProcess {
|
|||||||
* @return array
|
* @return array
|
||||||
*/
|
*/
|
||||||
public function getToken(): array {
|
public function getToken(): array {
|
||||||
$this->attachRefreshTokenGrantIfNeeded();
|
|
||||||
try {
|
try {
|
||||||
$response = $this->server->issueAccessToken();
|
$response = $this->server->issueAccessToken();
|
||||||
} catch (OAuthException $e) {
|
} catch (OAuthException $e) {
|
||||||
@ -149,66 +145,26 @@ class OauthProcess {
|
|||||||
return $response;
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Этот метод нужен за тем, что \League\OAuth2\Server\AuthorizationServer не предоставляет
|
|
||||||
* метода для проверки, можно ли выдавать refresh_token для пришедшего токена. Он просто
|
|
||||||
* выдаёт refresh_token, если этот grant присутствует в конфигурации сервера. Так что чтобы
|
|
||||||
* как-то решить эту проблему, мы не включаем RefreshTokenGrant в базовую конфигурацию сервера,
|
|
||||||
* а подключаем его только в том случае, если у auth_token есть право на рефреш или если это
|
|
||||||
* и есть запрос на refresh токена.
|
|
||||||
*/
|
|
||||||
private function attachRefreshTokenGrantIfNeeded(): void {
|
|
||||||
if ($this->server->hasGrantType('refresh_token')) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$grantType = Yii::$app->request->post('grant_type');
|
|
||||||
if ($grantType === 'authorization_code' && Yii::$app->request->post('code')) {
|
|
||||||
$authCode = Yii::$app->request->post('code');
|
|
||||||
$codeModel = $this->server->getAuthCodeStorage()->get($authCode);
|
|
||||||
if ($codeModel === null) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$scopes = $codeModel->getScopes();
|
|
||||||
if (!array_key_exists(OauthScope::OFFLINE_ACCESS, $scopes)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} elseif ($grantType === 'refresh_token') {
|
|
||||||
// Это валидный кейс
|
|
||||||
} else {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$grantClass = Yii::$app->oauth->grantMap['refresh_token'];
|
|
||||||
/** @var \League\OAuth2\Server\Grant\RefreshTokenGrant $grant */
|
|
||||||
$grant = new $grantClass;
|
|
||||||
|
|
||||||
$this->server->addGrantType($grant);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Метод проверяет, может ли текущий пользователь быть автоматически авторизован
|
* Метод проверяет, может ли текущий пользователь быть автоматически авторизован
|
||||||
* для указанного клиента без запроса доступа к необходимому списку прав
|
* для указанного клиента без запроса доступа к необходимому списку прав
|
||||||
*
|
*
|
||||||
* @param Account $account
|
* @param Account $account
|
||||||
* @param OauthClient $client
|
* @param OauthClient $client
|
||||||
* @param array $oauthParams
|
* @param AuthorizeParams $oauthParams
|
||||||
*
|
*
|
||||||
* @return bool
|
* @return bool
|
||||||
*/
|
*/
|
||||||
private function canAutoApprove(Account $account, OauthClient $client, array $oauthParams): bool {
|
private function canAutoApprove(Account $account, OauthClient $client, AuthorizeParams $oauthParams): bool {
|
||||||
if ($client->is_trusted) {
|
if ($client->is_trusted) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @var \League\OAuth2\Server\Entity\ScopeEntity[] $scopes */
|
|
||||||
$scopes = $oauthParams['scopes'];
|
|
||||||
/** @var \common\models\OauthSession|null $session */
|
/** @var \common\models\OauthSession|null $session */
|
||||||
$session = $account->getOauthSessions()->andWhere(['client_id' => $client->id])->one();
|
$session = $account->getOauthSessions()->andWhere(['client_id' => $client->id])->one();
|
||||||
if ($session !== null) {
|
if ($session !== null) {
|
||||||
$existScopes = $session->getScopes()->members();
|
$existScopes = $session->getScopes()->members();
|
||||||
if (empty(array_diff(array_keys($scopes), $existScopes))) {
|
if (empty(array_diff(array_keys($oauthParams->getScopes()), $existScopes))) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -216,11 +172,18 @@ class OauthProcess {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private function buildSuccessResponse(array $params, OauthClient $client, array $scopes): array {
|
/**
|
||||||
|
* @param array $queryParams
|
||||||
|
* @param OauthClient $client
|
||||||
|
* @param \api\components\OAuth2\Entities\ScopeEntity[] $scopes
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
private function buildSuccessResponse(array $queryParams, OauthClient $client, array $scopes): array {
|
||||||
return [
|
return [
|
||||||
'success' => true,
|
'success' => true,
|
||||||
// Возвращаем только те ключи, которые имеют реальное отношение к oAuth параметрам
|
// Возвращаем только те ключи, которые имеют реальное отношение к oAuth параметрам
|
||||||
'oAuth' => array_intersect_key($params, array_flip([
|
'oAuth' => array_intersect_key($queryParams, array_flip([
|
||||||
'client_id',
|
'client_id',
|
||||||
'redirect_uri',
|
'redirect_uri',
|
||||||
'response_type',
|
'response_type',
|
||||||
@ -230,7 +193,7 @@ class OauthProcess {
|
|||||||
'client' => [
|
'client' => [
|
||||||
'id' => $client->id,
|
'id' => $client->id,
|
||||||
'name' => $client->name,
|
'name' => $client->name,
|
||||||
'description' => ArrayHelper::getValue($params, 'description', $client->description),
|
'description' => ArrayHelper::getValue($queryParams, 'description', $client->description),
|
||||||
],
|
],
|
||||||
'session' => [
|
'session' => [
|
||||||
'scopes' => array_keys($scopes),
|
'scopes' => array_keys($scopes),
|
||||||
|
@ -71,12 +71,6 @@ return [
|
|||||||
],
|
],
|
||||||
'oauth' => [
|
'oauth' => [
|
||||||
'class' => api\components\OAuth2\Component::class,
|
'class' => api\components\OAuth2\Component::class,
|
||||||
'grantTypes' => ['authorization_code', 'client_credentials'],
|
|
||||||
'grantMap' => [
|
|
||||||
'authorization_code' => api\components\OAuth2\Grants\AuthCodeGrant::class,
|
|
||||||
'refresh_token' => api\components\OAuth2\Grants\RefreshTokenGrant::class,
|
|
||||||
'client_credentials' => api\components\OAuth2\Grants\ClientCredentialsGrant::class,
|
|
||||||
],
|
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
'container' => [
|
'container' => [
|
||||||
|
@ -9,7 +9,7 @@
|
|||||||
"yiisoft/yii2": "2.0.12",
|
"yiisoft/yii2": "2.0.12",
|
||||||
"yiisoft/yii2-swiftmailer": "*",
|
"yiisoft/yii2-swiftmailer": "*",
|
||||||
"ramsey/uuid": "^3.5.0",
|
"ramsey/uuid": "^3.5.0",
|
||||||
"league/oauth2-server": "dev-improvements#fbaa9b0bd3d8050235ba7dde90f731764122bc20",
|
"league/oauth2-server": "^4.1",
|
||||||
"yiisoft/yii2-redis": "~2.0.0",
|
"yiisoft/yii2-redis": "~2.0.0",
|
||||||
"guzzlehttp/guzzle": "^6.0.0",
|
"guzzlehttp/guzzle": "^6.0.0",
|
||||||
"php-amqplib/php-amqplib": "^2.6.2",
|
"php-amqplib/php-amqplib": "^2.6.2",
|
||||||
@ -51,10 +51,6 @@
|
|||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git@gitlab.ely.by:elyby/email-renderer.git"
|
"url": "git@gitlab.ely.by:elyby/email-renderer.git"
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"type": "git",
|
|
||||||
"url": "git@gitlab.ely.by:elyby/oauth2-server.git"
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "git@github.com:erickskrauch/php-mock-mockery.git"
|
"url": "git@github.com:erickskrauch/php-mock-mockery.git"
|
||||||
|
Reference in New Issue
Block a user