From 6008b7502e2d457784206d64baeedba1b76e11af Mon Sep 17 00:00:00 2001 From: Igor Maliy Date: Wed, 17 Jun 2015 01:36:28 +0300 Subject: [PATCH 01/67] v2.0.0 --- .gitignore | 0 Bootstrap.php | 57 +++++++++ LICENSE | 0 Module.php | 108 +++++------------- README.md | 0 commands/empty | 0 composer.json | 1 + controllers/DefaultController.php | 0 filters/ErrorToExceptionFilter.php | 5 +- filters/auth/CompositeAuth.php | 0 grants/UserAuthCredentials.php | 0 messages/en/{oauth2server.php => common.php} | 0 .../m140501_075311_add_oauth2_server.php | 0 models/OauthAccessTokens.php | 0 models/OauthAuthorizationCodes.php | 0 models/OauthClients.php | 0 models/OauthRefreshTokens.php | 0 models/OauthScopes.php | 0 storage/Pdo.php | 0 19 files changed, 90 insertions(+), 81 deletions(-) mode change 100644 => 100755 .gitignore create mode 100644 Bootstrap.php mode change 100644 => 100755 LICENSE mode change 100644 => 100755 Module.php mode change 100644 => 100755 README.md create mode 100644 commands/empty mode change 100644 => 100755 composer.json mode change 100644 => 100755 controllers/DefaultController.php mode change 100644 => 100755 filters/ErrorToExceptionFilter.php mode change 100644 => 100755 filters/auth/CompositeAuth.php mode change 100644 => 100755 grants/UserAuthCredentials.php rename messages/en/{oauth2server.php => common.php} (100%) mode change 100644 => 100755 mode change 100644 => 100755 migrations/m140501_075311_add_oauth2_server.php mode change 100644 => 100755 models/OauthAccessTokens.php mode change 100644 => 100755 models/OauthAuthorizationCodes.php mode change 100644 => 100755 models/OauthClients.php mode change 100644 => 100755 models/OauthRefreshTokens.php mode change 100644 => 100755 models/OauthScopes.php mode change 100644 => 100755 storage/Pdo.php diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 diff --git a/Bootstrap.php b/Bootstrap.php new file mode 100644 index 0000000..bd65763 --- /dev/null +++ b/Bootstrap.php @@ -0,0 +1,57 @@ + 'filsh\yii2\oauth2server\models\OauthClients', + 'OauthAccessTokens' => 'filsh\yii2\oauth2server\models\OauthAccessTokens', + 'OauthAuthorizationCodes' => 'filsh\yii2\oauth2server\models\OauthAuthorizationCodes', + 'OauthRefreshTokens' => 'filsh\yii2\oauth2server\models\OauthRefreshTokens', + 'OauthScopes' => 'filsh\yii2\oauth2server\models\OauthScopes', + ]; + + /** + * @var array Storage's map + */ + private $_storageMap = [ + 'access_token' => 'filsh\yii2\oauth2server\storage\Pdo', + 'authorization_code' => 'filsh\yii2\oauth2server\storage\Pdo', + 'client_credentials' => 'filsh\yii2\oauth2server\storage\Pdo', + 'client' => 'filsh\yii2\oauth2server\storage\Pdo', + 'refresh_token' => 'filsh\yii2\oauth2server\storage\Pdo', + 'user_credentials' => 'filsh\yii2\oauth2server\storage\Pdo', + 'public_key' => 'filsh\yii2\oauth2server\storage\Pdo', + 'jwt_bearer' => 'filsh\yii2\oauth2server\storage\Pdo', + 'scope' => 'filsh\yii2\oauth2server\storage\Pdo', + ]; + + /** + * @inheritdoc + */ + public function bootstrap($app) + { + /** @var $module Module */ + if ($app->hasModule('oauth2') && ($module = $app->getModule('oauth2')) instanceof Module) { + $this->_modelMap = array_merge($this->_modelMap, $module->modelMap); + foreach ($this->_modelMap as $name => $definition) { + \Yii::$container->set("filsh\\yii2\\oauth2server\\models\\" . $name, $definition); + $module->modelMap[$name] = is_array($definition) ? $definition['class'] : $definition; + } + + $this->_storageMap = array_merge($this->_storageMap, $module->storageMap); + foreach ($this->_storageMap as $name => $definition) { + \Yii::$container->set($name, $definition); + $module->storageMap[$name] = is_array($definition) ? $definition['class'] : $definition; + } + + if ($app instanceof \yii\console\Application) { + $module->controllerNamespace = 'filsh\yii2\oauth2server\commands'; + } + } + } +} \ No newline at end of file diff --git a/LICENSE b/LICENSE old mode 100644 new mode 100755 diff --git a/Module.php b/Module.php old mode 100644 new mode 100755 index 496b276..afdd713 --- a/Module.php +++ b/Module.php @@ -3,6 +3,7 @@ namespace filsh\yii2\oauth2server; use \Yii; +use yii\i18n\PhpMessageSource; /** * For example, @@ -35,31 +36,35 @@ */ class Module extends \yii\base\Module { - public $options = []; + const VERSION = '2.0.0'; + /** + * @var array Model's map + */ + public $modelMap = []; + + /** + * @var array Storage's map + */ public $storageMap = []; - public $storageDefault = 'filsh\yii2\oauth2server\storage\Pdo'; - public $grantTypes = []; - public $modelClasses = []; - public $i18n; - + public $options = []; + + public $grantTypes = []; + private $_server; private $_request; - private $_models = []; - /** * @inheritdoc */ public function init() { parent::init(); - $this->modelClasses = array_merge($this->getDefaultModelClasses(), $this->modelClasses); $this->registerTranslations(); } @@ -71,7 +76,10 @@ public function init() public function getServer($force = false) { if($this->_server === null || $force === true) { - $storages = $this->createStorages(); + $storages = []; + foreach($this->storageMap as $name => $value) { + $storages[$name] = \Yii::$container->get($name); + } $server = new \OAuth2\Server($storages, $this->options); foreach($this->grantTypes as $name => $options) { @@ -114,57 +122,11 @@ public function getResponse() { return new \OAuth2\Response(); } - - /** - * Create storages - * @return type - */ - public function createStorages() - { - $connection = Yii::$app->getDb(); - if(!$connection->getIsActive()) { - $connection->open(); - } - - $storages = []; - foreach($this->storageMap as $name => $storage) { - $storages[$name] = Yii::createObject($storage); - } - - $defaults = [ - 'access_token', - 'authorization_code', - 'client_credentials', - 'client', - 'refresh_token', - 'user_credentials', - 'public_key', - 'jwt_bearer', - 'scope', - ]; - foreach($defaults as $name) { - if(!isset($storages[$name])) { - $storages[$name] = Yii::createObject($this->storageDefault); - } - } - - return $storages; - } - /** - * Get object instance of model - * @param string $name - * @param array $config - * @return ActiveRecord - */ - public function model($name, $config = []) - { - if(!isset($this->_models[$name])) { - $className = $this->modelClasses[ucfirst($name)]; - $this->_models[$name] = Yii::createObject(array_merge(['class' => $className], $config)); - } - return $this->_models[$name]; - } + + + + /** * Register translations for this module @@ -172,28 +134,16 @@ public function model($name, $config = []) */ public function registerTranslations() { - Yii::setAlias('@oauth2server', dirname(__FILE__)); - if (empty($this->i18n)) { - $this->i18n = [ - 'class' => 'yii\i18n\PhpMessageSource', - 'basePath' => '@oauth2server/messages', + if(!isset(Yii::$app->get('i18n')->translations['modules/oauth2/*'])) { + Yii::$app->get('i18n')->translations['modules/oauth2/*'] = [ + 'class' => PhpMessageSource::className(), + 'basePath' => __DIR__ . '/messages', ]; } - Yii::$app->i18n->translations['oauth2server'] = $this->i18n; } - - /** - * Get default model classes - * @return array - */ - protected function getDefaultModelClasses() + + public static function t($category, $message, $params = [], $language = null) { - return [ - 'Clients' => 'filsh\yii2\oauth2server\models\OauthClients', - 'AccessTokens' => 'filsh\yii2\oauth2server\models\OauthAccessTokens', - 'AuthorizationCodes' => 'filsh\yii2\oauth2server\models\OauthAuthorizationCodes', - 'RefreshTokens' => 'filsh\yii2\oauth2server\models\OauthRefreshTokens', - 'Scopes' => 'filsh\yii2\oauth2server\models\OauthScopes', - ]; + return Yii::t('modules/oauth2/' . $category, $message, $params, $language); } } diff --git a/README.md b/README.md old mode 100644 new mode 100755 diff --git a/commands/empty b/commands/empty new file mode 100644 index 0000000..e69de29 diff --git a/composer.json b/composer.json old mode 100644 new mode 100755 index 458ac9d..4799e2d --- a/composer.json +++ b/composer.json @@ -25,6 +25,7 @@ } }, "extra": { + "bootstrap": "filsh\\yii2\\oauth2server\\Bootstrap", "branch-alias": { "dev-master": "1.0.x-dev" } diff --git a/controllers/DefaultController.php b/controllers/DefaultController.php old mode 100644 new mode 100755 diff --git a/filters/ErrorToExceptionFilter.php b/filters/ErrorToExceptionFilter.php old mode 100644 new mode 100755 index 9f6f4c7..2c38d8b --- a/filters/ErrorToExceptionFilter.php +++ b/filters/ErrorToExceptionFilter.php @@ -4,6 +4,7 @@ use Yii; use yii\base\Controller; +use filsh\yii2\oauth2server\Module; class ErrorToExceptionFilter extends \yii\base\Behavior { @@ -28,9 +29,9 @@ public function afterAction($event) if(!$isValid) { $status = $response->getStatusCode(); // TODO: необходимо также пробрасывать error_uri - $message = Yii::t('oauth2server', $response->getParameter('error_description')); + $message = Module::t('common', $response->getParameter('error_description')); if($message === null) { - $message = Yii::t('yii', 'An internal server error occurred.'); + $message = Module::t('common', 'An internal server error occurred.'); } throw new \yii\web\HttpException($status, $message); } diff --git a/filters/auth/CompositeAuth.php b/filters/auth/CompositeAuth.php old mode 100644 new mode 100755 diff --git a/grants/UserAuthCredentials.php b/grants/UserAuthCredentials.php old mode 100644 new mode 100755 diff --git a/messages/en/oauth2server.php b/messages/en/common.php old mode 100644 new mode 100755 similarity index 100% rename from messages/en/oauth2server.php rename to messages/en/common.php diff --git a/migrations/m140501_075311_add_oauth2_server.php b/migrations/m140501_075311_add_oauth2_server.php old mode 100644 new mode 100755 diff --git a/models/OauthAccessTokens.php b/models/OauthAccessTokens.php old mode 100644 new mode 100755 diff --git a/models/OauthAuthorizationCodes.php b/models/OauthAuthorizationCodes.php old mode 100644 new mode 100755 diff --git a/models/OauthClients.php b/models/OauthClients.php old mode 100644 new mode 100755 diff --git a/models/OauthRefreshTokens.php b/models/OauthRefreshTokens.php old mode 100644 new mode 100755 diff --git a/models/OauthScopes.php b/models/OauthScopes.php old mode 100644 new mode 100755 diff --git a/storage/Pdo.php b/storage/Pdo.php old mode 100644 new mode 100755 From 056287132e423fab8a957694a99c9781e92951db Mon Sep 17 00:00:00 2001 From: Igor Maliy Date: Wed, 17 Jun 2015 11:02:26 +0300 Subject: [PATCH 02/67] Update composer.json --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 4799e2d..e8432ff 100755 --- a/composer.json +++ b/composer.json @@ -17,7 +17,7 @@ ], "require": { "yiisoft/yii2": "*", - "bshaffer/oauth2-server-php": "v1.3" + "bshaffer/oauth2-server-php": "~1.7.1" }, "autoload": { "psr-4": { From ae4853fd69038f16399107ae863b5cb8167458f6 Mon Sep 17 00:00:00 2001 From: Igor Maliy Date: Thu, 18 Jun 2015 08:46:31 +0300 Subject: [PATCH 03/67] Oauth module v2.0 --- Module.php | 114 +++++++++++++---------------- Request.php | 8 ++ Response.php | 8 ++ Server.php | 35 +++++++++ composer.json | 2 +- controllers/DefaultController.php | 5 +- filters/ErrorToExceptionFilter.php | 2 +- filters/auth/CompositeAuth.php | 5 +- traits/ClassNamespace.php | 11 +++ 9 files changed, 118 insertions(+), 72 deletions(-) create mode 100644 Request.php create mode 100644 Response.php create mode 100644 Server.php create mode 100644 traits/ClassNamespace.php diff --git a/Module.php b/Module.php index afdd713..8ac7ff5 100755 --- a/Module.php +++ b/Module.php @@ -48,16 +48,11 @@ class Module extends \yii\base\Module */ public $storageMap = []; - - - - public $options = []; - public $grantTypes = []; - private $_server; - - private $_request; + public $tokenParamName; + + public $tokenAccessLifetime; /** * @inheritdoc @@ -65,74 +60,39 @@ class Module extends \yii\base\Module public function init() { parent::init(); + $this->registerComponents(); $this->registerTranslations(); } /** - * Get oauth2 server instance - * @param type $force - * @return \OAuth2\Server + * Translate module message + * + * @param string $category + * @param string $message + * @param array $params + * @param string $language + * @return string */ - public function getServer($force = false) + public static function t($category, $message, $params = [], $language = null) { - if($this->_server === null || $force === true) { - $storages = []; - foreach($this->storageMap as $name => $value) { - $storages[$name] = \Yii::$container->get($name); - } - $server = new \OAuth2\Server($storages, $this->options); - - foreach($this->grantTypes as $name => $options) { - if(!isset($storages[$name]) || empty($options['class'])) { - throw new \yii\base\InvalidConfigException('Invalid grant types configuration.'); - } - - $class = $options['class']; - unset($options['class']); - - $reflection = new \ReflectionClass($class); - $config = array_merge([0 => $storages[$name]], [$options]); - - $instance = $reflection->newInstanceArgs($config); - $server->addGrantType($instance); - } - - $this->_server = $server; - } - return $this->_server; + return Yii::t('modules/oauth2/' . $category, $message, $params, $language); } - /** - * Get oauth2 request instance from global variables - * @return \OAuth2\Request - */ - public function getRequest($force = false) + protected function registerComponents() { - if ($this->_request === null || $force) { - $this->_request = \OAuth2\Request::createFromGlobals(); - }; - return $this->_request; + $this->setComponents([ + 'server' => $this->createServer(), + 'request' => Request::createFromGlobals(), + 'response' => new Response() + ]); } - /** - * Get oauth2 response instance - * @return \OAuth2\Response - */ - public function getResponse() - { - return new \OAuth2\Response(); - } - - - - - - /** * Register translations for this module + * * @return array */ - public function registerTranslations() + protected function registerTranslations() { if(!isset(Yii::$app->get('i18n')->translations['modules/oauth2/*'])) { Yii::$app->get('i18n')->translations['modules/oauth2/*'] = [ @@ -142,8 +102,36 @@ public function registerTranslations() } } - public static function t($category, $message, $params = [], $language = null) + protected function createServer() { - return Yii::t('modules/oauth2/' . $category, $message, $params, $language); + $storages = []; + foreach(array_keys($this->storageMap) as $name) { + $storages[$name] = \Yii::$container->get($name); + } + $server = \Yii::$container->get(Server::className(), [ + $storages, + [ + 'token_param_name' => $this->tokenParamName, + 'access_lifetime' => $this->tokenAccessLifetime, + /** add more ... */ + ] + ]); + + foreach($this->grantTypes as $name => $options) { + if(!isset($storages[$name]) || empty($options['class'])) { + throw new \yii\base\InvalidConfigException('Invalid grant types configuration.'); + } + + $class = $options['class']; + unset($options['class']); + + $reflection = new \ReflectionClass($class); + $config = array_merge([0 => $storages[$name]], [$options]); + + $instance = $reflection->newInstanceArgs($config); + $server->addGrantType($instance); + } + + return $server; } } diff --git a/Request.php b/Request.php new file mode 100644 index 0000000..b8c03df --- /dev/null +++ b/Request.php @@ -0,0 +1,8 @@ +module = $module; + parent::__construct($storage, $config, $grantTypes, $responseTypes, $tokenType, $scopeUtil, $clientAssertionType); + } + + public function handleTokenRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null) + { + if($request === null) { + $request = $this->module->get('request'); + } + return parent::handleTokenRequest($request, $response); + } + + public function verifyResourceRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null, $scope = null) + { + if($request === null) { + $request = $this->module->get('request'); + } + parent::verifyResourceRequest($request, $response, $scope); + } +} diff --git a/composer.json b/composer.json index e8432ff..7052c37 100755 --- a/composer.json +++ b/composer.json @@ -17,7 +17,7 @@ ], "require": { "yiisoft/yii2": "*", - "bshaffer/oauth2-server-php": "~1.7.1" + "bshaffer/oauth2-server-php": "~1.7" }, "autoload": { "psr-4": { diff --git a/controllers/DefaultController.php b/controllers/DefaultController.php index 255850d..1fb6201 100755 --- a/controllers/DefaultController.php +++ b/controllers/DefaultController.php @@ -22,10 +22,7 @@ public function behaviors() public function actionToken() { - $server = $this->module->getServer(); - $request = $this->module->getRequest(); - $response = $server->handleTokenRequest($request); - + $response = $this->module->get('server')->handleTokenRequest(); return $response->getParameters(); } } \ No newline at end of file diff --git a/filters/ErrorToExceptionFilter.php b/filters/ErrorToExceptionFilter.php index 2c38d8b..f64838e 100755 --- a/filters/ErrorToExceptionFilter.php +++ b/filters/ErrorToExceptionFilter.php @@ -20,7 +20,7 @@ public function events() */ public function afterAction($event) { - $response = Yii::$app->getModule('oauth2')->getServer()->getResponse(); + $response = Yii::$app->getModule('oauth2')->get('response'); $isValid = true; if($response !== null) { diff --git a/filters/auth/CompositeAuth.php b/filters/auth/CompositeAuth.php index 38ad308..3363d59 100755 --- a/filters/auth/CompositeAuth.php +++ b/filters/auth/CompositeAuth.php @@ -11,9 +11,8 @@ class CompositeAuth extends \yii\filters\auth\CompositeAuth */ public function beforeAction($action) { - $oauthServer = Yii::$app->getModule('oauth2')->getServer(); - $oauthRequest = Yii::$app->getModule('oauth2')->getRequest(); - $oauthServer->verifyResourceRequest($oauthRequest); + $server = Yii::$app->getModule('oauth2')->getServer(); + $server->verifyResourceRequest(); return parent::beforeAction($action); } diff --git a/traits/ClassNamespace.php b/traits/ClassNamespace.php new file mode 100644 index 0000000..fa5b8e0 --- /dev/null +++ b/traits/ClassNamespace.php @@ -0,0 +1,11 @@ + Date: Fri, 19 Jun 2015 08:12:03 +0300 Subject: [PATCH 04/67] Oauth module v2.0 --- Module.php | 114 +++++++++++++++++------------ Server.php | 12 +-- controllers/DefaultController.php | 2 +- exceptions/HttpException.php | 25 +++++++ filters/ErrorToExceptionFilter.php | 23 ++++-- grants/UserAuthCredentials.php | 65 ---------------- 6 files changed, 115 insertions(+), 126 deletions(-) create mode 100644 exceptions/HttpException.php delete mode 100755 grants/UserAuthCredentials.php diff --git a/Module.php b/Module.php index 8ac7ff5..87cfb3d 100755 --- a/Module.php +++ b/Module.php @@ -48,6 +48,9 @@ class Module extends \yii\base\Module */ public $storageMap = []; + /** + * @var array GrantTypes map + */ public $grantTypes = []; public $tokenParamName; @@ -60,39 +63,77 @@ class Module extends \yii\base\Module public function init() { parent::init(); - $this->registerComponents(); $this->registerTranslations(); } /** - * Translate module message + * Gets Oauth2 Server * - * @param string $category - * @param string $message - * @param array $params - * @param string $language - * @return string + * @return \filsh\yii2\oauth2server\Server + * @throws \yii\base\InvalidConfigException */ - public static function t($category, $message, $params = [], $language = null) + public function getServer() { - return Yii::t('modules/oauth2/' . $category, $message, $params, $language); + if(!$this->has('server')) { + $storages = []; + foreach(array_keys($this->storageMap) as $name) { + $storages[$name] = \Yii::$container->get($name); + } + + $grantTypes = []; + foreach($this->grantTypes as $name => $options) { + if(!isset($storages[$name]) || empty($options['class'])) { + throw new \yii\base\InvalidConfigException('Invalid grant types configuration.'); + } + + $class = $options['class']; + unset($options['class']); + + $reflection = new \ReflectionClass($class); + $config = array_merge([0 => $storages[$name]], [$options]); + + $instance = $reflection->newInstanceArgs($config); + $grantTypes[$name] = $instance; + } + + $server = \Yii::$container->get(Server::className(), [ + $this, + $storages, + [ + 'token_param_name' => $this->tokenParamName, + 'access_lifetime' => $this->tokenAccessLifetime, + /** add more ... */ + ], + $grantTypes + ]); + + $this->set('server', $server); + } + return $this->get('server'); } - protected function registerComponents() + public function getRequest() { - $this->setComponents([ - 'server' => $this->createServer(), - 'request' => Request::createFromGlobals(), - 'response' => new Response() - ]); + if(!$this->has('request')) { + $this->set('request', Request::createFromGlobals()); + } + return $this->get('request'); } + public function getResponse() + { + if(!$this->has('response')) { + $this->set('response', new Response()); + } + return $this->get('response'); + } + /** * Register translations for this module * * @return array */ - protected function registerTranslations() + public function registerTranslations() { if(!isset(Yii::$app->get('i18n')->translations['modules/oauth2/*'])) { Yii::$app->get('i18n')->translations['modules/oauth2/*'] = [ @@ -102,36 +143,17 @@ protected function registerTranslations() } } - protected function createServer() + /** + * Translate module message + * + * @param string $category + * @param string $message + * @param array $params + * @param string $language + * @return string + */ + public static function t($category, $message, $params = [], $language = null) { - $storages = []; - foreach(array_keys($this->storageMap) as $name) { - $storages[$name] = \Yii::$container->get($name); - } - $server = \Yii::$container->get(Server::className(), [ - $storages, - [ - 'token_param_name' => $this->tokenParamName, - 'access_lifetime' => $this->tokenAccessLifetime, - /** add more ... */ - ] - ]); - - foreach($this->grantTypes as $name => $options) { - if(!isset($storages[$name]) || empty($options['class'])) { - throw new \yii\base\InvalidConfigException('Invalid grant types configuration.'); - } - - $class = $options['class']; - unset($options['class']); - - $reflection = new \ReflectionClass($class); - $config = array_merge([0 => $storages[$name]], [$options]); - - $instance = $reflection->newInstanceArgs($config); - $server->addGrantType($instance); - } - - return $server; + return Yii::t('modules/oauth2/' . $category, $message, $params, $language); } } diff --git a/Server.php b/Server.php index f85ee20..669d341 100644 --- a/Server.php +++ b/Server.php @@ -17,19 +17,19 @@ public function __construct(Module $module, $storage = array(), array $config = parent::__construct($storage, $config, $grantTypes, $responseTypes, $tokenType, $scopeUtil, $clientAssertionType); } - public function handleTokenRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null) + public function verifyResourceRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null, $scope = null) { if($request === null) { - $request = $this->module->get('request'); + $request = $this->module->getRequest(); } - return parent::handleTokenRequest($request, $response); + parent::verifyResourceRequest($request, $response, $scope); } - public function verifyResourceRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null, $scope = null) + public function handleTokenRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null) { if($request === null) { - $request = $this->module->get('request'); + $request = $this->module->getRequest(); } - parent::verifyResourceRequest($request, $response, $scope); + return parent::handleTokenRequest($request, $response); } } diff --git a/controllers/DefaultController.php b/controllers/DefaultController.php index 1fb6201..34bab9b 100755 --- a/controllers/DefaultController.php +++ b/controllers/DefaultController.php @@ -22,7 +22,7 @@ public function behaviors() public function actionToken() { - $response = $this->module->get('server')->handleTokenRequest(); + $response = $this->module->getServer()->handleTokenRequest(); return $response->getParameters(); } } \ No newline at end of file diff --git a/exceptions/HttpException.php b/exceptions/HttpException.php new file mode 100644 index 0000000..a5cda38 --- /dev/null +++ b/exceptions/HttpException.php @@ -0,0 +1,25 @@ +errorUri = $errorUri; + parent::__construct($status, $message, $code, $previous); + } +} \ No newline at end of file diff --git a/filters/ErrorToExceptionFilter.php b/filters/ErrorToExceptionFilter.php index f64838e..7b13e44 100755 --- a/filters/ErrorToExceptionFilter.php +++ b/filters/ErrorToExceptionFilter.php @@ -5,9 +5,13 @@ use Yii; use yii\base\Controller; use filsh\yii2\oauth2server\Module; +use filsh\yii2\oauth2server\exceptions\HttpException; class ErrorToExceptionFilter extends \yii\base\Behavior { + /** + * @inheritdoc + */ public function events() { return [Controller::EVENT_AFTER_ACTION => 'afterAction']; @@ -20,20 +24,23 @@ public function events() */ public function afterAction($event) { - $response = Yii::$app->getModule('oauth2')->get('response'); + $response = Yii::$app->getModule('oauth2')->getServer()->getResponse(); $isValid = true; if($response !== null) { $isValid = $response->isInformational() || $response->isSuccessful() || $response->isRedirection(); } if(!$isValid) { - $status = $response->getStatusCode(); - // TODO: необходимо также пробрасывать error_uri - $message = Module::t('common', $response->getParameter('error_description')); - if($message === null) { - $message = Module::t('common', 'An internal server error occurred.'); - } - throw new \yii\web\HttpException($status, $message); + throw new HttpException($response->getStatusCode(), $this->getErrorMessage($response), $response->getParameter('error_uri')); + } + } + + protected function getErrorMessage(\OAuth2\Response $response) + { + $message = Module::t('common', $response->getParameter('error_description')); + if($message === null) { + $message = Module::t('common', 'An internal server error occurred.'); } + return $message; } } diff --git a/grants/UserAuthCredentials.php b/grants/UserAuthCredentials.php deleted file mode 100755 index efac5e4..0000000 --- a/grants/UserAuthCredentials.php +++ /dev/null @@ -1,65 +0,0 @@ -userStorage = $userStorage; - parent::__construct($storage, $config); - } - - public function getQuerystringIdentifier() - { - return 'user_authkey_credentials'; - } - - public function createAccessToken(\OAuth2\ResponseType\AccessTokenInterface $accessToken, $client_id, $user_id, $scope) - { - return $accessToken->createAccessToken($client_id, $user_id, $scope); - } - - public function getUserId() - { - return $this->userInfo['user_id']; - } - - public function getScope() - { - return isset($this->userInfo['scope']) ? $this->userInfo['scope'] : null; - } - - public function validateRequest(\OAuth2\RequestInterface $request, \OAuth2\ResponseInterface $response) - { - if (!$request->request('authkey') || !$request->request('username')) { - $response->setError(400, 'invalid_request', 'Missing parameters: "authkey" and "username" required'); - return null; - } - - if (!$this->userStorage->findIdentityByAccessToken($request->request('authkey'))) { - $response->setError(401, 'invalid_grant', 'Invalid user authkey'); - return null; - } - - $userInfo = $this->userStorage->getUserDetails($request->request('username')); - - if (empty($userInfo)) { - $response->setError(400, 'invalid_grant', 'Unable to retrieve user information'); - return null; - } - - if (!isset($userInfo['user_id'])) { - throw new \LogicException('you must set the user_id on the array returned by getUserDetails'); - } - - $this->userInfo = $userInfo; - - return parent::validateRequest($request, $response); - } -} \ No newline at end of file From e05fff97252f9e067cf0eae276ea36e9e87ae3e2 Mon Sep 17 00:00:00 2001 From: Maliy Igor Date: Fri, 19 Jun 2015 15:30:06 +0300 Subject: [PATCH 05/67] v2.0.0 --- Bootstrap.php | 2 ++ Module.php | 28 +++++++++---------- Server.php | 6 ++++ ...faultController.php => RestController.php} | 2 +- 4 files changed, 23 insertions(+), 15 deletions(-) rename controllers/{DefaultController.php => RestController.php} (91%) diff --git a/Bootstrap.php b/Bootstrap.php index bd65763..b9b15db 100644 --- a/Bootstrap.php +++ b/Bootstrap.php @@ -2,6 +2,8 @@ namespace filsh\yii2\oauth2server; +use yii\web\GroupUrlRule; + class Bootstrap implements \yii\base\BootstrapInterface { /** diff --git a/Module.php b/Module.php index 87cfb3d..108ccb2 100755 --- a/Module.php +++ b/Module.php @@ -11,26 +11,20 @@ * ```php * 'oauth2' => [ * 'class' => 'filsh\yii2\oauth2server\Module', - * 'options' => [ - * 'token_param_name' => 'accessToken', - * 'access_lifetime' => 3600 - * ], + * 'tokenParamName' => 'accessToken', + * 'tokenAccessLifetime' => 3600 * 24, * 'storageMap' => [ - * 'user_credentials' => 'common\models\User' + * 'user_credentials' => 'common\models\User', * ], * 'grantTypes' => [ - * 'client_credentials' => [ - * 'class' => '\OAuth2\GrantType\ClientCredentials', - * 'allow_public_clients' => false - * ], * 'user_credentials' => [ - * 'class' => '\OAuth2\GrantType\UserCredentials' + * 'class' => 'OAuth2\GrantType\UserCredentials', * ], * 'refresh_token' => [ - * 'class' => '\OAuth2\GrantType\RefreshToken', + * 'class' => 'OAuth2\GrantType\RefreshToken', * 'always_issue_new_refresh_token' => true * ] - * ], + * ] * ] * ``` */ @@ -49,12 +43,18 @@ class Module extends \yii\base\Module public $storageMap = []; /** - * @var array GrantTypes map + * @var array GrantTypes collection */ public $grantTypes = []; + /** + * @var string name of access token parameter + */ public $tokenParamName; + /** + * @var type max access lifetime + */ public $tokenAccessLifetime; /** @@ -95,7 +95,7 @@ public function getServer() $instance = $reflection->newInstanceArgs($config); $grantTypes[$name] = $instance; } - + $server = \Yii::$container->get(Server::className(), [ $this, $storages, diff --git a/Server.php b/Server.php index 669d341..78e78ac 100644 --- a/Server.php +++ b/Server.php @@ -17,6 +17,12 @@ public function __construct(Module $module, $storage = array(), array $config = parent::__construct($storage, $config, $grantTypes, $responseTypes, $tokenType, $scopeUtil, $clientAssertionType); } + public function createAccessToken($clientId, $userId, $scope = null, $includeRefreshToken = true) + { + $accessToken = $this->getAccessTokenResponseType(); + return $accessToken->createAccessToken($clientId, $userId, $scope, $includeRefreshToken); + } + public function verifyResourceRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null, $scope = null) { if($request === null) { diff --git a/controllers/DefaultController.php b/controllers/RestController.php similarity index 91% rename from controllers/DefaultController.php rename to controllers/RestController.php index 34bab9b..c9978b3 100755 --- a/controllers/DefaultController.php +++ b/controllers/RestController.php @@ -6,7 +6,7 @@ use yii\helpers\ArrayHelper; use filsh\yii2\oauth2server\filters\ErrorToExceptionFilter; -class DefaultController extends \yii\rest\Controller +class RestController extends \yii\rest\Controller { /** * @inheritdoc From dac22a35444a6325cf075b62ac6fbc55f88080a7 Mon Sep 17 00:00:00 2001 From: Igor Maliy Date: Sat, 20 Jun 2015 10:02:23 +0300 Subject: [PATCH 06/67] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0c6bb6c..d186ca2 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ php composer.phar require --prefer-dist filsh/yii2-oauth2-server "*" or add ```json -"filsh/yii2-oauth2-server": "~2.0.0" +"filsh/yii2-oauth2-server": "~2.0" ``` to the require section of your composer.json. @@ -28,7 +28,7 @@ To use this extension, simply add the following code in your application config 'oauth2' => [ 'class' => 'filsh\yii2\oauth2server\Module', 'tokenParamName' => 'accessToken', - 'tokenAccessLifetime' => 3600 24, + 'tokenAccessLifetime' => 3600 * 24, 'storageMap' => [ 'user_credentials' => 'common\models\User', ], From e5084e39f303f47f5c6093e2509b730eeb8279e4 Mon Sep 17 00:00:00 2001 From: Dmitri Savustjan Date: Fri, 3 Jul 2015 15:44:48 +0300 Subject: [PATCH 07/67] Update Server.php fixed verifyResourceRequest. It prevented function from return result of parent check. Always returned null (false). --- Server.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Server.php b/Server.php index 78e78ac..5535573 100644 --- a/Server.php +++ b/Server.php @@ -28,7 +28,7 @@ public function verifyResourceRequest(\OAuth2\RequestInterface $request = null, if($request === null) { $request = $this->module->getRequest(); } - parent::verifyResourceRequest($request, $response, $scope); + return parent::verifyResourceRequest($request, $response, $scope); } public function handleTokenRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null) From 3a32949f446b73b3e604f7efefcc58a13e1d0cad Mon Sep 17 00:00:00 2001 From: freezy Date: Mon, 6 Jul 2015 10:30:53 +0200 Subject: [PATCH 08/67] Updated Module params phpDocs --- Module.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Module.php b/Module.php index 108ccb2..cf9b792 100755 --- a/Module.php +++ b/Module.php @@ -48,12 +48,12 @@ class Module extends \yii\base\Module public $grantTypes = []; /** - * @var string name of access token parameter + * @var string Name of access token parameter */ public $tokenParamName; /** - * @var type max access lifetime + * @var integer Max access token lifetime in seconds */ public $tokenAccessLifetime; From b005ade43a30688697162c546067ed34be90cc1a Mon Sep 17 00:00:00 2001 From: freezy Date: Mon, 6 Jul 2015 10:35:34 +0200 Subject: [PATCH 09/67] Added option to set custom ResponseTypes --- Module.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Module.php b/Module.php index cf9b792..eb68adc 100755 --- a/Module.php +++ b/Module.php @@ -46,6 +46,11 @@ class Module extends \yii\base\Module * @var array GrantTypes collection */ public $grantTypes = []; + + /** + * @var array ResponseTypes collection + */ + public $responseTypes = []; /** * @var string Name of access token parameter @@ -104,7 +109,8 @@ public function getServer() 'access_lifetime' => $this->tokenAccessLifetime, /** add more ... */ ], - $grantTypes + $grantTypes, + $this->responseTypes ]); $this->set('server', $server); From 505816d8c53a2dff28fb45c26d9b77f494f13e0f Mon Sep 17 00:00:00 2001 From: Philip Date: Mon, 13 Jul 2015 18:29:14 +0300 Subject: [PATCH 10/67] Prefixes table is not set in filsh\yii2\oauth2server\storage\Pdo exception 'PDOException' with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "oauth_access_tokens" does not exist --- storage/Pdo.php | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/storage/Pdo.php b/storage/Pdo.php index 9bc7707..d1799da 100644 --- a/storage/Pdo.php +++ b/storage/Pdo.php @@ -2,6 +2,8 @@ namespace filsh\yii2\oauth2server\storage; +use Yii; + class Pdo extends \OAuth2\Storage\Pdo { public $dsn; @@ -31,5 +33,17 @@ public function __construct($connection = null, $config = array()) } parent::__construct($connection, $config); + + $this->config = array_merge(array( + 'client_table' => Yii::$app->db->tablePrefix.'oauth_clients', + 'access_token_table' => Yii::$app->db->tablePrefix.'oauth_access_tokens', + 'refresh_token_table' => Yii::$app->db->tablePrefix.'oauth_refresh_tokens', + 'code_table' => Yii::$app->db->tablePrefix.'oauth_authorization_codes', + 'user_table' => Yii::$app->db->tablePrefix.'oauth_users', + 'jwt_table' => Yii::$app->db->tablePrefix.'oauth_jwt', + 'jti_table' => Yii::$app->db->tablePrefix.'oauth_jti', + 'scope_table' => Yii::$app->db->tablePrefix.'oauth_scopes', + 'public_key_table' => Yii::$app->db->tablePrefix.'oauth_public_keys', + ), $config); } -} \ No newline at end of file +} From e2bf9559baf0ae2cbb8d30c9061d218c1ca790f4 Mon Sep 17 00:00:00 2001 From: Rodrigo Zani Date: Mon, 13 Jul 2015 17:34:41 -0300 Subject: [PATCH 11/67] adding support when OAuth2 is nested to another module --- Bootstrap.php | 62 +++++++++++++++++++++++----------- filters/auth/CompositeAuth.php | 28 +++++++++++++-- 2 files changed, 67 insertions(+), 23 deletions(-) diff --git a/Bootstrap.php b/Bootstrap.php index b9b15db..755b37e 100644 --- a/Bootstrap.php +++ b/Bootstrap.php @@ -6,54 +6,76 @@ class Bootstrap implements \yii\base\BootstrapInterface { + /** * @var array Model's map */ private $_modelMap = [ - 'OauthClients' => 'filsh\yii2\oauth2server\models\OauthClients', - 'OauthAccessTokens' => 'filsh\yii2\oauth2server\models\OauthAccessTokens', - 'OauthAuthorizationCodes' => 'filsh\yii2\oauth2server\models\OauthAuthorizationCodes', - 'OauthRefreshTokens' => 'filsh\yii2\oauth2server\models\OauthRefreshTokens', - 'OauthScopes' => 'filsh\yii2\oauth2server\models\OauthScopes', + 'OauthClients' => 'filsh\yii2\oauth2server\models\OauthClients', + 'OauthAccessTokens' => 'filsh\yii2\oauth2server\models\OauthAccessTokens', + 'OauthAuthorizationCodes' => 'filsh\yii2\oauth2server\models\OauthAuthorizationCodes', + 'OauthRefreshTokens' => 'filsh\yii2\oauth2server\models\OauthRefreshTokens', + 'OauthScopes' => 'filsh\yii2\oauth2server\models\OauthScopes', ]; - + /** * @var array Storage's map */ private $_storageMap = [ - 'access_token' => 'filsh\yii2\oauth2server\storage\Pdo', - 'authorization_code' => 'filsh\yii2\oauth2server\storage\Pdo', - 'client_credentials' => 'filsh\yii2\oauth2server\storage\Pdo', - 'client' => 'filsh\yii2\oauth2server\storage\Pdo', - 'refresh_token' => 'filsh\yii2\oauth2server\storage\Pdo', - 'user_credentials' => 'filsh\yii2\oauth2server\storage\Pdo', - 'public_key' => 'filsh\yii2\oauth2server\storage\Pdo', - 'jwt_bearer' => 'filsh\yii2\oauth2server\storage\Pdo', - 'scope' => 'filsh\yii2\oauth2server\storage\Pdo', + 'access_token' => 'filsh\yii2\oauth2server\storage\Pdo', + 'authorization_code' => 'filsh\yii2\oauth2server\storage\Pdo', + 'client_credentials' => 'filsh\yii2\oauth2server\storage\Pdo', + 'client' => 'filsh\yii2\oauth2server\storage\Pdo', + 'refresh_token' => 'filsh\yii2\oauth2server\storage\Pdo', + 'user_credentials' => 'filsh\yii2\oauth2server\storage\Pdo', + 'public_key' => 'filsh\yii2\oauth2server\storage\Pdo', + 'jwt_bearer' => 'filsh\yii2\oauth2server\storage\Pdo', + 'scope' => 'filsh\yii2\oauth2server\storage\Pdo', ]; - + /** * @inheritdoc */ public function bootstrap($app) { /** @var $module Module */ - if ($app->hasModule('oauth2') && ($module = $app->getModule('oauth2')) instanceof Module) { + $module = $this->getModuleNested('oauth2', $app); + + if ($module instanceof Module) { $this->_modelMap = array_merge($this->_modelMap, $module->modelMap); foreach ($this->_modelMap as $name => $definition) { \Yii::$container->set("filsh\\yii2\\oauth2server\\models\\" . $name, $definition); $module->modelMap[$name] = is_array($definition) ? $definition['class'] : $definition; } - + $this->_storageMap = array_merge($this->_storageMap, $module->storageMap); foreach ($this->_storageMap as $name => $definition) { \Yii::$container->set($name, $definition); $module->storageMap[$name] = is_array($definition) ? $definition['class'] : $definition; } - + if ($app instanceof \yii\console\Application) { $module->controllerNamespace = 'filsh\yii2\oauth2server\commands'; } } } -} \ No newline at end of file + + public function getModuleNested($needle, $app) + { + /** @var $module Module */ + if (($module = $app->getModule($needle)) !== null) + return $module; + + foreach ($app->getModules() as $id => $module) { + $server = $app->getModule($id)->getModule($needle); + if ($server != null) { + return $server; + } else { + $this->getModuleNested($module->getModules()); + } + } + + return false; + } + +} diff --git a/filters/auth/CompositeAuth.php b/filters/auth/CompositeAuth.php index 3363d59..6a0b912 100755 --- a/filters/auth/CompositeAuth.php +++ b/filters/auth/CompositeAuth.php @@ -6,14 +6,36 @@ class CompositeAuth extends \yii\filters\auth\CompositeAuth { + /** * @inheritdoc */ public function beforeAction($action) { - $server = Yii::$app->getModule('oauth2')->getServer(); + $module = $this->getModuleNested('oauth2', Yii::$app); + + $server = $module->getServer(); $server->verifyResourceRequest(); - + return parent::beforeAction($action); } -} \ No newline at end of file + + public function getModuleNested($needle, $app) + { + /** @var $module Module */ + if (($module = $app->getModule($needle)) !== null) + return $module; + + foreach ($app->getModules() as $id => $module) { + $server = $app->getModule($id)->getModule($needle); + if ($server != null) { + return $server; + } else { + $this->getModuleNested($module->getModules()); + } + } + + return false; + } + +} From 0c05c5baa3ac8f67ea885490b5981a938a13352f Mon Sep 17 00:00:00 2001 From: Maliy Igor Date: Tue, 14 Jul 2015 11:23:55 +0300 Subject: [PATCH 12/67] Prefixes table is not set in filsh\yii2\oauth2server\storage\Pdo --- storage/Pdo.php | 39 ++++++++++++++++++++++----------------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/storage/Pdo.php b/storage/Pdo.php index d1799da..6f0376a 100644 --- a/storage/Pdo.php +++ b/storage/Pdo.php @@ -17,12 +17,29 @@ class Pdo extends \OAuth2\Storage\Pdo public function __construct($connection = null, $config = array()) { if($connection === null) { - if(!empty($this->connection)) { - $connection = \Yii::$app->get($this->connection); - if(!$connection->getIsActive()) { - $connection->open(); + if($this->connection !== null && \Yii::$app->has($this->connection)) { + $db = \Yii::$app->get($this->connection); + if(!($db instanceof \yii\db\Connection)) { + throw new \yii\base\InvalidConfigException; } - $connection = $connection->pdo; + + if(!$db->getIsActive()) { + $db->open(); + } + + $connection = $db->pdo; + $config = array_merge(array( + 'client_table' => $db->tablePrefix . 'oauth_clients', + 'access_token_table' => $db->tablePrefix . 'oauth_access_tokens', + 'refresh_token_table' => $db->tablePrefix . 'oauth_refresh_tokens', + 'code_table' => $db->tablePrefix . 'oauth_authorization_codes', + 'user_table' => $db->tablePrefix . 'oauth_users', + 'jwt_table' => $db->tablePrefix . 'oauth_jwt', + 'jti_table' => $db->tablePrefix . 'oauth_jti', + 'scope_table' => $db->tablePrefix . 'oauth_scopes', + 'public_key_table' => $db->tablePrefix . 'oauth_public_keys', + ), $config); + } else { $connection = [ 'dsn' => $this->dsn, @@ -33,17 +50,5 @@ public function __construct($connection = null, $config = array()) } parent::__construct($connection, $config); - - $this->config = array_merge(array( - 'client_table' => Yii::$app->db->tablePrefix.'oauth_clients', - 'access_token_table' => Yii::$app->db->tablePrefix.'oauth_access_tokens', - 'refresh_token_table' => Yii::$app->db->tablePrefix.'oauth_refresh_tokens', - 'code_table' => Yii::$app->db->tablePrefix.'oauth_authorization_codes', - 'user_table' => Yii::$app->db->tablePrefix.'oauth_users', - 'jwt_table' => Yii::$app->db->tablePrefix.'oauth_jwt', - 'jti_table' => Yii::$app->db->tablePrefix.'oauth_jti', - 'scope_table' => Yii::$app->db->tablePrefix.'oauth_scopes', - 'public_key_table' => Yii::$app->db->tablePrefix.'oauth_public_keys', - ), $config); } } From 608f3869ef9d69494785761ffe2fd9ac55851164 Mon Sep 17 00:00:00 2001 From: Maliy Igor Date: Tue, 14 Jul 2015 11:29:54 +0300 Subject: [PATCH 13/67] Prefixes table is not set in filsh\yii2\oauth2server\storage\Pdo --- storage/Pdo.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/storage/Pdo.php b/storage/Pdo.php index 6f0376a..3a14b5d 100644 --- a/storage/Pdo.php +++ b/storage/Pdo.php @@ -2,8 +2,6 @@ namespace filsh\yii2\oauth2server\storage; -use Yii; - class Pdo extends \OAuth2\Storage\Pdo { public $dsn; @@ -20,7 +18,7 @@ public function __construct($connection = null, $config = array()) if($this->connection !== null && \Yii::$app->has($this->connection)) { $db = \Yii::$app->get($this->connection); if(!($db instanceof \yii\db\Connection)) { - throw new \yii\base\InvalidConfigException; + throw new \yii\base\InvalidConfigException('Connection component must implement \yii\db\Connection.'); } if(!$db->getIsActive()) { From 009b1af0da5b15716dad480e431a60fd27fbd1f9 Mon Sep 17 00:00:00 2001 From: Igor Maliy Date: Wed, 17 Jun 2015 01:36:28 +0300 Subject: [PATCH 14/67] v2.0.0 --- .gitignore | 0 Bootstrap.php | 57 +++++++++ LICENSE | 0 Module.php | 108 +++++------------- README.md | 0 commands/empty | 0 composer.json | 1 + controllers/DefaultController.php | 0 filters/ErrorToExceptionFilter.php | 5 +- filters/auth/CompositeAuth.php | 0 grants/UserAuthCredentials.php | 0 messages/en/{oauth2server.php => common.php} | 0 .../m140501_075311_add_oauth2_server.php | 0 models/OauthAccessTokens.php | 0 models/OauthAuthorizationCodes.php | 0 models/OauthClients.php | 0 models/OauthRefreshTokens.php | 0 models/OauthScopes.php | 0 storage/Pdo.php | 0 19 files changed, 90 insertions(+), 81 deletions(-) mode change 100644 => 100755 .gitignore create mode 100644 Bootstrap.php mode change 100644 => 100755 LICENSE mode change 100644 => 100755 Module.php mode change 100644 => 100755 README.md create mode 100644 commands/empty mode change 100644 => 100755 composer.json mode change 100644 => 100755 controllers/DefaultController.php mode change 100644 => 100755 filters/ErrorToExceptionFilter.php mode change 100644 => 100755 filters/auth/CompositeAuth.php mode change 100644 => 100755 grants/UserAuthCredentials.php rename messages/en/{oauth2server.php => common.php} (100%) mode change 100644 => 100755 mode change 100644 => 100755 migrations/m140501_075311_add_oauth2_server.php mode change 100644 => 100755 models/OauthAccessTokens.php mode change 100644 => 100755 models/OauthAuthorizationCodes.php mode change 100644 => 100755 models/OauthClients.php mode change 100644 => 100755 models/OauthRefreshTokens.php mode change 100644 => 100755 models/OauthScopes.php mode change 100644 => 100755 storage/Pdo.php diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 diff --git a/Bootstrap.php b/Bootstrap.php new file mode 100644 index 0000000..bd65763 --- /dev/null +++ b/Bootstrap.php @@ -0,0 +1,57 @@ + 'filsh\yii2\oauth2server\models\OauthClients', + 'OauthAccessTokens' => 'filsh\yii2\oauth2server\models\OauthAccessTokens', + 'OauthAuthorizationCodes' => 'filsh\yii2\oauth2server\models\OauthAuthorizationCodes', + 'OauthRefreshTokens' => 'filsh\yii2\oauth2server\models\OauthRefreshTokens', + 'OauthScopes' => 'filsh\yii2\oauth2server\models\OauthScopes', + ]; + + /** + * @var array Storage's map + */ + private $_storageMap = [ + 'access_token' => 'filsh\yii2\oauth2server\storage\Pdo', + 'authorization_code' => 'filsh\yii2\oauth2server\storage\Pdo', + 'client_credentials' => 'filsh\yii2\oauth2server\storage\Pdo', + 'client' => 'filsh\yii2\oauth2server\storage\Pdo', + 'refresh_token' => 'filsh\yii2\oauth2server\storage\Pdo', + 'user_credentials' => 'filsh\yii2\oauth2server\storage\Pdo', + 'public_key' => 'filsh\yii2\oauth2server\storage\Pdo', + 'jwt_bearer' => 'filsh\yii2\oauth2server\storage\Pdo', + 'scope' => 'filsh\yii2\oauth2server\storage\Pdo', + ]; + + /** + * @inheritdoc + */ + public function bootstrap($app) + { + /** @var $module Module */ + if ($app->hasModule('oauth2') && ($module = $app->getModule('oauth2')) instanceof Module) { + $this->_modelMap = array_merge($this->_modelMap, $module->modelMap); + foreach ($this->_modelMap as $name => $definition) { + \Yii::$container->set("filsh\\yii2\\oauth2server\\models\\" . $name, $definition); + $module->modelMap[$name] = is_array($definition) ? $definition['class'] : $definition; + } + + $this->_storageMap = array_merge($this->_storageMap, $module->storageMap); + foreach ($this->_storageMap as $name => $definition) { + \Yii::$container->set($name, $definition); + $module->storageMap[$name] = is_array($definition) ? $definition['class'] : $definition; + } + + if ($app instanceof \yii\console\Application) { + $module->controllerNamespace = 'filsh\yii2\oauth2server\commands'; + } + } + } +} \ No newline at end of file diff --git a/LICENSE b/LICENSE old mode 100644 new mode 100755 diff --git a/Module.php b/Module.php old mode 100644 new mode 100755 index 496b276..afdd713 --- a/Module.php +++ b/Module.php @@ -3,6 +3,7 @@ namespace filsh\yii2\oauth2server; use \Yii; +use yii\i18n\PhpMessageSource; /** * For example, @@ -35,31 +36,35 @@ */ class Module extends \yii\base\Module { - public $options = []; + const VERSION = '2.0.0'; + /** + * @var array Model's map + */ + public $modelMap = []; + + /** + * @var array Storage's map + */ public $storageMap = []; - public $storageDefault = 'filsh\yii2\oauth2server\storage\Pdo'; - public $grantTypes = []; - public $modelClasses = []; - public $i18n; - + public $options = []; + + public $grantTypes = []; + private $_server; private $_request; - private $_models = []; - /** * @inheritdoc */ public function init() { parent::init(); - $this->modelClasses = array_merge($this->getDefaultModelClasses(), $this->modelClasses); $this->registerTranslations(); } @@ -71,7 +76,10 @@ public function init() public function getServer($force = false) { if($this->_server === null || $force === true) { - $storages = $this->createStorages(); + $storages = []; + foreach($this->storageMap as $name => $value) { + $storages[$name] = \Yii::$container->get($name); + } $server = new \OAuth2\Server($storages, $this->options); foreach($this->grantTypes as $name => $options) { @@ -114,57 +122,11 @@ public function getResponse() { return new \OAuth2\Response(); } - - /** - * Create storages - * @return type - */ - public function createStorages() - { - $connection = Yii::$app->getDb(); - if(!$connection->getIsActive()) { - $connection->open(); - } - - $storages = []; - foreach($this->storageMap as $name => $storage) { - $storages[$name] = Yii::createObject($storage); - } - - $defaults = [ - 'access_token', - 'authorization_code', - 'client_credentials', - 'client', - 'refresh_token', - 'user_credentials', - 'public_key', - 'jwt_bearer', - 'scope', - ]; - foreach($defaults as $name) { - if(!isset($storages[$name])) { - $storages[$name] = Yii::createObject($this->storageDefault); - } - } - - return $storages; - } - /** - * Get object instance of model - * @param string $name - * @param array $config - * @return ActiveRecord - */ - public function model($name, $config = []) - { - if(!isset($this->_models[$name])) { - $className = $this->modelClasses[ucfirst($name)]; - $this->_models[$name] = Yii::createObject(array_merge(['class' => $className], $config)); - } - return $this->_models[$name]; - } + + + + /** * Register translations for this module @@ -172,28 +134,16 @@ public function model($name, $config = []) */ public function registerTranslations() { - Yii::setAlias('@oauth2server', dirname(__FILE__)); - if (empty($this->i18n)) { - $this->i18n = [ - 'class' => 'yii\i18n\PhpMessageSource', - 'basePath' => '@oauth2server/messages', + if(!isset(Yii::$app->get('i18n')->translations['modules/oauth2/*'])) { + Yii::$app->get('i18n')->translations['modules/oauth2/*'] = [ + 'class' => PhpMessageSource::className(), + 'basePath' => __DIR__ . '/messages', ]; } - Yii::$app->i18n->translations['oauth2server'] = $this->i18n; } - - /** - * Get default model classes - * @return array - */ - protected function getDefaultModelClasses() + + public static function t($category, $message, $params = [], $language = null) { - return [ - 'Clients' => 'filsh\yii2\oauth2server\models\OauthClients', - 'AccessTokens' => 'filsh\yii2\oauth2server\models\OauthAccessTokens', - 'AuthorizationCodes' => 'filsh\yii2\oauth2server\models\OauthAuthorizationCodes', - 'RefreshTokens' => 'filsh\yii2\oauth2server\models\OauthRefreshTokens', - 'Scopes' => 'filsh\yii2\oauth2server\models\OauthScopes', - ]; + return Yii::t('modules/oauth2/' . $category, $message, $params, $language); } } diff --git a/README.md b/README.md old mode 100644 new mode 100755 diff --git a/commands/empty b/commands/empty new file mode 100644 index 0000000..e69de29 diff --git a/composer.json b/composer.json old mode 100644 new mode 100755 index 458ac9d..4799e2d --- a/composer.json +++ b/composer.json @@ -25,6 +25,7 @@ } }, "extra": { + "bootstrap": "filsh\\yii2\\oauth2server\\Bootstrap", "branch-alias": { "dev-master": "1.0.x-dev" } diff --git a/controllers/DefaultController.php b/controllers/DefaultController.php old mode 100644 new mode 100755 diff --git a/filters/ErrorToExceptionFilter.php b/filters/ErrorToExceptionFilter.php old mode 100644 new mode 100755 index 9f6f4c7..2c38d8b --- a/filters/ErrorToExceptionFilter.php +++ b/filters/ErrorToExceptionFilter.php @@ -4,6 +4,7 @@ use Yii; use yii\base\Controller; +use filsh\yii2\oauth2server\Module; class ErrorToExceptionFilter extends \yii\base\Behavior { @@ -28,9 +29,9 @@ public function afterAction($event) if(!$isValid) { $status = $response->getStatusCode(); // TODO: необходимо также пробрасывать error_uri - $message = Yii::t('oauth2server', $response->getParameter('error_description')); + $message = Module::t('common', $response->getParameter('error_description')); if($message === null) { - $message = Yii::t('yii', 'An internal server error occurred.'); + $message = Module::t('common', 'An internal server error occurred.'); } throw new \yii\web\HttpException($status, $message); } diff --git a/filters/auth/CompositeAuth.php b/filters/auth/CompositeAuth.php old mode 100644 new mode 100755 diff --git a/grants/UserAuthCredentials.php b/grants/UserAuthCredentials.php old mode 100644 new mode 100755 diff --git a/messages/en/oauth2server.php b/messages/en/common.php old mode 100644 new mode 100755 similarity index 100% rename from messages/en/oauth2server.php rename to messages/en/common.php diff --git a/migrations/m140501_075311_add_oauth2_server.php b/migrations/m140501_075311_add_oauth2_server.php old mode 100644 new mode 100755 diff --git a/models/OauthAccessTokens.php b/models/OauthAccessTokens.php old mode 100644 new mode 100755 diff --git a/models/OauthAuthorizationCodes.php b/models/OauthAuthorizationCodes.php old mode 100644 new mode 100755 diff --git a/models/OauthClients.php b/models/OauthClients.php old mode 100644 new mode 100755 diff --git a/models/OauthRefreshTokens.php b/models/OauthRefreshTokens.php old mode 100644 new mode 100755 diff --git a/models/OauthScopes.php b/models/OauthScopes.php old mode 100644 new mode 100755 diff --git a/storage/Pdo.php b/storage/Pdo.php old mode 100644 new mode 100755 From 519f154960ddc0ffda26d3f5e13499b2764f7e47 Mon Sep 17 00:00:00 2001 From: Igor Maliy Date: Wed, 17 Jun 2015 11:02:26 +0300 Subject: [PATCH 15/67] Update composer.json --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 4799e2d..e8432ff 100755 --- a/composer.json +++ b/composer.json @@ -17,7 +17,7 @@ ], "require": { "yiisoft/yii2": "*", - "bshaffer/oauth2-server-php": "v1.3" + "bshaffer/oauth2-server-php": "~1.7.1" }, "autoload": { "psr-4": { From baf3ac9460396ba4b1ad9cd4a6f37c723f2de308 Mon Sep 17 00:00:00 2001 From: Igor Maliy Date: Thu, 18 Jun 2015 08:46:31 +0300 Subject: [PATCH 16/67] Oauth module v2.0 --- Module.php | 114 +++++++++++++---------------- Request.php | 8 ++ Response.php | 8 ++ Server.php | 35 +++++++++ composer.json | 2 +- controllers/DefaultController.php | 5 +- filters/ErrorToExceptionFilter.php | 2 +- filters/auth/CompositeAuth.php | 5 +- traits/ClassNamespace.php | 11 +++ 9 files changed, 118 insertions(+), 72 deletions(-) create mode 100644 Request.php create mode 100644 Response.php create mode 100644 Server.php create mode 100644 traits/ClassNamespace.php diff --git a/Module.php b/Module.php index afdd713..8ac7ff5 100755 --- a/Module.php +++ b/Module.php @@ -48,16 +48,11 @@ class Module extends \yii\base\Module */ public $storageMap = []; - - - - public $options = []; - public $grantTypes = []; - private $_server; - - private $_request; + public $tokenParamName; + + public $tokenAccessLifetime; /** * @inheritdoc @@ -65,74 +60,39 @@ class Module extends \yii\base\Module public function init() { parent::init(); + $this->registerComponents(); $this->registerTranslations(); } /** - * Get oauth2 server instance - * @param type $force - * @return \OAuth2\Server + * Translate module message + * + * @param string $category + * @param string $message + * @param array $params + * @param string $language + * @return string */ - public function getServer($force = false) + public static function t($category, $message, $params = [], $language = null) { - if($this->_server === null || $force === true) { - $storages = []; - foreach($this->storageMap as $name => $value) { - $storages[$name] = \Yii::$container->get($name); - } - $server = new \OAuth2\Server($storages, $this->options); - - foreach($this->grantTypes as $name => $options) { - if(!isset($storages[$name]) || empty($options['class'])) { - throw new \yii\base\InvalidConfigException('Invalid grant types configuration.'); - } - - $class = $options['class']; - unset($options['class']); - - $reflection = new \ReflectionClass($class); - $config = array_merge([0 => $storages[$name]], [$options]); - - $instance = $reflection->newInstanceArgs($config); - $server->addGrantType($instance); - } - - $this->_server = $server; - } - return $this->_server; + return Yii::t('modules/oauth2/' . $category, $message, $params, $language); } - /** - * Get oauth2 request instance from global variables - * @return \OAuth2\Request - */ - public function getRequest($force = false) + protected function registerComponents() { - if ($this->_request === null || $force) { - $this->_request = \OAuth2\Request::createFromGlobals(); - }; - return $this->_request; + $this->setComponents([ + 'server' => $this->createServer(), + 'request' => Request::createFromGlobals(), + 'response' => new Response() + ]); } - /** - * Get oauth2 response instance - * @return \OAuth2\Response - */ - public function getResponse() - { - return new \OAuth2\Response(); - } - - - - - - /** * Register translations for this module + * * @return array */ - public function registerTranslations() + protected function registerTranslations() { if(!isset(Yii::$app->get('i18n')->translations['modules/oauth2/*'])) { Yii::$app->get('i18n')->translations['modules/oauth2/*'] = [ @@ -142,8 +102,36 @@ public function registerTranslations() } } - public static function t($category, $message, $params = [], $language = null) + protected function createServer() { - return Yii::t('modules/oauth2/' . $category, $message, $params, $language); + $storages = []; + foreach(array_keys($this->storageMap) as $name) { + $storages[$name] = \Yii::$container->get($name); + } + $server = \Yii::$container->get(Server::className(), [ + $storages, + [ + 'token_param_name' => $this->tokenParamName, + 'access_lifetime' => $this->tokenAccessLifetime, + /** add more ... */ + ] + ]); + + foreach($this->grantTypes as $name => $options) { + if(!isset($storages[$name]) || empty($options['class'])) { + throw new \yii\base\InvalidConfigException('Invalid grant types configuration.'); + } + + $class = $options['class']; + unset($options['class']); + + $reflection = new \ReflectionClass($class); + $config = array_merge([0 => $storages[$name]], [$options]); + + $instance = $reflection->newInstanceArgs($config); + $server->addGrantType($instance); + } + + return $server; } } diff --git a/Request.php b/Request.php new file mode 100644 index 0000000..b8c03df --- /dev/null +++ b/Request.php @@ -0,0 +1,8 @@ +module = $module; + parent::__construct($storage, $config, $grantTypes, $responseTypes, $tokenType, $scopeUtil, $clientAssertionType); + } + + public function handleTokenRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null) + { + if($request === null) { + $request = $this->module->get('request'); + } + return parent::handleTokenRequest($request, $response); + } + + public function verifyResourceRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null, $scope = null) + { + if($request === null) { + $request = $this->module->get('request'); + } + parent::verifyResourceRequest($request, $response, $scope); + } +} diff --git a/composer.json b/composer.json index e8432ff..7052c37 100755 --- a/composer.json +++ b/composer.json @@ -17,7 +17,7 @@ ], "require": { "yiisoft/yii2": "*", - "bshaffer/oauth2-server-php": "~1.7.1" + "bshaffer/oauth2-server-php": "~1.7" }, "autoload": { "psr-4": { diff --git a/controllers/DefaultController.php b/controllers/DefaultController.php index 255850d..1fb6201 100755 --- a/controllers/DefaultController.php +++ b/controllers/DefaultController.php @@ -22,10 +22,7 @@ public function behaviors() public function actionToken() { - $server = $this->module->getServer(); - $request = $this->module->getRequest(); - $response = $server->handleTokenRequest($request); - + $response = $this->module->get('server')->handleTokenRequest(); return $response->getParameters(); } } \ No newline at end of file diff --git a/filters/ErrorToExceptionFilter.php b/filters/ErrorToExceptionFilter.php index 2c38d8b..f64838e 100755 --- a/filters/ErrorToExceptionFilter.php +++ b/filters/ErrorToExceptionFilter.php @@ -20,7 +20,7 @@ public function events() */ public function afterAction($event) { - $response = Yii::$app->getModule('oauth2')->getServer()->getResponse(); + $response = Yii::$app->getModule('oauth2')->get('response'); $isValid = true; if($response !== null) { diff --git a/filters/auth/CompositeAuth.php b/filters/auth/CompositeAuth.php index 38ad308..3363d59 100755 --- a/filters/auth/CompositeAuth.php +++ b/filters/auth/CompositeAuth.php @@ -11,9 +11,8 @@ class CompositeAuth extends \yii\filters\auth\CompositeAuth */ public function beforeAction($action) { - $oauthServer = Yii::$app->getModule('oauth2')->getServer(); - $oauthRequest = Yii::$app->getModule('oauth2')->getRequest(); - $oauthServer->verifyResourceRequest($oauthRequest); + $server = Yii::$app->getModule('oauth2')->getServer(); + $server->verifyResourceRequest(); return parent::beforeAction($action); } diff --git a/traits/ClassNamespace.php b/traits/ClassNamespace.php new file mode 100644 index 0000000..fa5b8e0 --- /dev/null +++ b/traits/ClassNamespace.php @@ -0,0 +1,11 @@ + Date: Fri, 19 Jun 2015 08:12:03 +0300 Subject: [PATCH 17/67] Oauth module v2.0 --- Module.php | 114 +++++++++++++++++------------ Server.php | 12 +-- controllers/DefaultController.php | 2 +- exceptions/HttpException.php | 25 +++++++ filters/ErrorToExceptionFilter.php | 23 ++++-- grants/UserAuthCredentials.php | 65 ---------------- 6 files changed, 115 insertions(+), 126 deletions(-) create mode 100644 exceptions/HttpException.php delete mode 100755 grants/UserAuthCredentials.php diff --git a/Module.php b/Module.php index 8ac7ff5..87cfb3d 100755 --- a/Module.php +++ b/Module.php @@ -48,6 +48,9 @@ class Module extends \yii\base\Module */ public $storageMap = []; + /** + * @var array GrantTypes map + */ public $grantTypes = []; public $tokenParamName; @@ -60,39 +63,77 @@ class Module extends \yii\base\Module public function init() { parent::init(); - $this->registerComponents(); $this->registerTranslations(); } /** - * Translate module message + * Gets Oauth2 Server * - * @param string $category - * @param string $message - * @param array $params - * @param string $language - * @return string + * @return \filsh\yii2\oauth2server\Server + * @throws \yii\base\InvalidConfigException */ - public static function t($category, $message, $params = [], $language = null) + public function getServer() { - return Yii::t('modules/oauth2/' . $category, $message, $params, $language); + if(!$this->has('server')) { + $storages = []; + foreach(array_keys($this->storageMap) as $name) { + $storages[$name] = \Yii::$container->get($name); + } + + $grantTypes = []; + foreach($this->grantTypes as $name => $options) { + if(!isset($storages[$name]) || empty($options['class'])) { + throw new \yii\base\InvalidConfigException('Invalid grant types configuration.'); + } + + $class = $options['class']; + unset($options['class']); + + $reflection = new \ReflectionClass($class); + $config = array_merge([0 => $storages[$name]], [$options]); + + $instance = $reflection->newInstanceArgs($config); + $grantTypes[$name] = $instance; + } + + $server = \Yii::$container->get(Server::className(), [ + $this, + $storages, + [ + 'token_param_name' => $this->tokenParamName, + 'access_lifetime' => $this->tokenAccessLifetime, + /** add more ... */ + ], + $grantTypes + ]); + + $this->set('server', $server); + } + return $this->get('server'); } - protected function registerComponents() + public function getRequest() { - $this->setComponents([ - 'server' => $this->createServer(), - 'request' => Request::createFromGlobals(), - 'response' => new Response() - ]); + if(!$this->has('request')) { + $this->set('request', Request::createFromGlobals()); + } + return $this->get('request'); } + public function getResponse() + { + if(!$this->has('response')) { + $this->set('response', new Response()); + } + return $this->get('response'); + } + /** * Register translations for this module * * @return array */ - protected function registerTranslations() + public function registerTranslations() { if(!isset(Yii::$app->get('i18n')->translations['modules/oauth2/*'])) { Yii::$app->get('i18n')->translations['modules/oauth2/*'] = [ @@ -102,36 +143,17 @@ protected function registerTranslations() } } - protected function createServer() + /** + * Translate module message + * + * @param string $category + * @param string $message + * @param array $params + * @param string $language + * @return string + */ + public static function t($category, $message, $params = [], $language = null) { - $storages = []; - foreach(array_keys($this->storageMap) as $name) { - $storages[$name] = \Yii::$container->get($name); - } - $server = \Yii::$container->get(Server::className(), [ - $storages, - [ - 'token_param_name' => $this->tokenParamName, - 'access_lifetime' => $this->tokenAccessLifetime, - /** add more ... */ - ] - ]); - - foreach($this->grantTypes as $name => $options) { - if(!isset($storages[$name]) || empty($options['class'])) { - throw new \yii\base\InvalidConfigException('Invalid grant types configuration.'); - } - - $class = $options['class']; - unset($options['class']); - - $reflection = new \ReflectionClass($class); - $config = array_merge([0 => $storages[$name]], [$options]); - - $instance = $reflection->newInstanceArgs($config); - $server->addGrantType($instance); - } - - return $server; + return Yii::t('modules/oauth2/' . $category, $message, $params, $language); } } diff --git a/Server.php b/Server.php index f85ee20..669d341 100644 --- a/Server.php +++ b/Server.php @@ -17,19 +17,19 @@ public function __construct(Module $module, $storage = array(), array $config = parent::__construct($storage, $config, $grantTypes, $responseTypes, $tokenType, $scopeUtil, $clientAssertionType); } - public function handleTokenRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null) + public function verifyResourceRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null, $scope = null) { if($request === null) { - $request = $this->module->get('request'); + $request = $this->module->getRequest(); } - return parent::handleTokenRequest($request, $response); + parent::verifyResourceRequest($request, $response, $scope); } - public function verifyResourceRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null, $scope = null) + public function handleTokenRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null) { if($request === null) { - $request = $this->module->get('request'); + $request = $this->module->getRequest(); } - parent::verifyResourceRequest($request, $response, $scope); + return parent::handleTokenRequest($request, $response); } } diff --git a/controllers/DefaultController.php b/controllers/DefaultController.php index 1fb6201..34bab9b 100755 --- a/controllers/DefaultController.php +++ b/controllers/DefaultController.php @@ -22,7 +22,7 @@ public function behaviors() public function actionToken() { - $response = $this->module->get('server')->handleTokenRequest(); + $response = $this->module->getServer()->handleTokenRequest(); return $response->getParameters(); } } \ No newline at end of file diff --git a/exceptions/HttpException.php b/exceptions/HttpException.php new file mode 100644 index 0000000..a5cda38 --- /dev/null +++ b/exceptions/HttpException.php @@ -0,0 +1,25 @@ +errorUri = $errorUri; + parent::__construct($status, $message, $code, $previous); + } +} \ No newline at end of file diff --git a/filters/ErrorToExceptionFilter.php b/filters/ErrorToExceptionFilter.php index f64838e..7b13e44 100755 --- a/filters/ErrorToExceptionFilter.php +++ b/filters/ErrorToExceptionFilter.php @@ -5,9 +5,13 @@ use Yii; use yii\base\Controller; use filsh\yii2\oauth2server\Module; +use filsh\yii2\oauth2server\exceptions\HttpException; class ErrorToExceptionFilter extends \yii\base\Behavior { + /** + * @inheritdoc + */ public function events() { return [Controller::EVENT_AFTER_ACTION => 'afterAction']; @@ -20,20 +24,23 @@ public function events() */ public function afterAction($event) { - $response = Yii::$app->getModule('oauth2')->get('response'); + $response = Yii::$app->getModule('oauth2')->getServer()->getResponse(); $isValid = true; if($response !== null) { $isValid = $response->isInformational() || $response->isSuccessful() || $response->isRedirection(); } if(!$isValid) { - $status = $response->getStatusCode(); - // TODO: необходимо также пробрасывать error_uri - $message = Module::t('common', $response->getParameter('error_description')); - if($message === null) { - $message = Module::t('common', 'An internal server error occurred.'); - } - throw new \yii\web\HttpException($status, $message); + throw new HttpException($response->getStatusCode(), $this->getErrorMessage($response), $response->getParameter('error_uri')); + } + } + + protected function getErrorMessage(\OAuth2\Response $response) + { + $message = Module::t('common', $response->getParameter('error_description')); + if($message === null) { + $message = Module::t('common', 'An internal server error occurred.'); } + return $message; } } diff --git a/grants/UserAuthCredentials.php b/grants/UserAuthCredentials.php deleted file mode 100755 index efac5e4..0000000 --- a/grants/UserAuthCredentials.php +++ /dev/null @@ -1,65 +0,0 @@ -userStorage = $userStorage; - parent::__construct($storage, $config); - } - - public function getQuerystringIdentifier() - { - return 'user_authkey_credentials'; - } - - public function createAccessToken(\OAuth2\ResponseType\AccessTokenInterface $accessToken, $client_id, $user_id, $scope) - { - return $accessToken->createAccessToken($client_id, $user_id, $scope); - } - - public function getUserId() - { - return $this->userInfo['user_id']; - } - - public function getScope() - { - return isset($this->userInfo['scope']) ? $this->userInfo['scope'] : null; - } - - public function validateRequest(\OAuth2\RequestInterface $request, \OAuth2\ResponseInterface $response) - { - if (!$request->request('authkey') || !$request->request('username')) { - $response->setError(400, 'invalid_request', 'Missing parameters: "authkey" and "username" required'); - return null; - } - - if (!$this->userStorage->findIdentityByAccessToken($request->request('authkey'))) { - $response->setError(401, 'invalid_grant', 'Invalid user authkey'); - return null; - } - - $userInfo = $this->userStorage->getUserDetails($request->request('username')); - - if (empty($userInfo)) { - $response->setError(400, 'invalid_grant', 'Unable to retrieve user information'); - return null; - } - - if (!isset($userInfo['user_id'])) { - throw new \LogicException('you must set the user_id on the array returned by getUserDetails'); - } - - $this->userInfo = $userInfo; - - return parent::validateRequest($request, $response); - } -} \ No newline at end of file From a3d59182e2c9ce12b952017eb3e52b67556a3f51 Mon Sep 17 00:00:00 2001 From: Maliy Igor Date: Fri, 19 Jun 2015 15:30:06 +0300 Subject: [PATCH 18/67] v2.0.0 --- Bootstrap.php | 2 ++ Module.php | 28 +++++++++---------- Server.php | 6 ++++ ...faultController.php => RestController.php} | 2 +- 4 files changed, 23 insertions(+), 15 deletions(-) rename controllers/{DefaultController.php => RestController.php} (91%) diff --git a/Bootstrap.php b/Bootstrap.php index bd65763..b9b15db 100644 --- a/Bootstrap.php +++ b/Bootstrap.php @@ -2,6 +2,8 @@ namespace filsh\yii2\oauth2server; +use yii\web\GroupUrlRule; + class Bootstrap implements \yii\base\BootstrapInterface { /** diff --git a/Module.php b/Module.php index 87cfb3d..108ccb2 100755 --- a/Module.php +++ b/Module.php @@ -11,26 +11,20 @@ * ```php * 'oauth2' => [ * 'class' => 'filsh\yii2\oauth2server\Module', - * 'options' => [ - * 'token_param_name' => 'accessToken', - * 'access_lifetime' => 3600 - * ], + * 'tokenParamName' => 'accessToken', + * 'tokenAccessLifetime' => 3600 * 24, * 'storageMap' => [ - * 'user_credentials' => 'common\models\User' + * 'user_credentials' => 'common\models\User', * ], * 'grantTypes' => [ - * 'client_credentials' => [ - * 'class' => '\OAuth2\GrantType\ClientCredentials', - * 'allow_public_clients' => false - * ], * 'user_credentials' => [ - * 'class' => '\OAuth2\GrantType\UserCredentials' + * 'class' => 'OAuth2\GrantType\UserCredentials', * ], * 'refresh_token' => [ - * 'class' => '\OAuth2\GrantType\RefreshToken', + * 'class' => 'OAuth2\GrantType\RefreshToken', * 'always_issue_new_refresh_token' => true * ] - * ], + * ] * ] * ``` */ @@ -49,12 +43,18 @@ class Module extends \yii\base\Module public $storageMap = []; /** - * @var array GrantTypes map + * @var array GrantTypes collection */ public $grantTypes = []; + /** + * @var string name of access token parameter + */ public $tokenParamName; + /** + * @var type max access lifetime + */ public $tokenAccessLifetime; /** @@ -95,7 +95,7 @@ public function getServer() $instance = $reflection->newInstanceArgs($config); $grantTypes[$name] = $instance; } - + $server = \Yii::$container->get(Server::className(), [ $this, $storages, diff --git a/Server.php b/Server.php index 669d341..78e78ac 100644 --- a/Server.php +++ b/Server.php @@ -17,6 +17,12 @@ public function __construct(Module $module, $storage = array(), array $config = parent::__construct($storage, $config, $grantTypes, $responseTypes, $tokenType, $scopeUtil, $clientAssertionType); } + public function createAccessToken($clientId, $userId, $scope = null, $includeRefreshToken = true) + { + $accessToken = $this->getAccessTokenResponseType(); + return $accessToken->createAccessToken($clientId, $userId, $scope, $includeRefreshToken); + } + public function verifyResourceRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null, $scope = null) { if($request === null) { diff --git a/controllers/DefaultController.php b/controllers/RestController.php similarity index 91% rename from controllers/DefaultController.php rename to controllers/RestController.php index 34bab9b..c9978b3 100755 --- a/controllers/DefaultController.php +++ b/controllers/RestController.php @@ -6,7 +6,7 @@ use yii\helpers\ArrayHelper; use filsh\yii2\oauth2server\filters\ErrorToExceptionFilter; -class DefaultController extends \yii\rest\Controller +class RestController extends \yii\rest\Controller { /** * @inheritdoc From b8af7cf344ab79ee0a735a164bd10314c147479f Mon Sep 17 00:00:00 2001 From: Dmitri Savustjan Date: Fri, 3 Jul 2015 15:44:48 +0300 Subject: [PATCH 19/67] Update Server.php fixed verifyResourceRequest. It prevented function from return result of parent check. Always returned null (false). --- Server.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Server.php b/Server.php index 78e78ac..5535573 100644 --- a/Server.php +++ b/Server.php @@ -28,7 +28,7 @@ public function verifyResourceRequest(\OAuth2\RequestInterface $request = null, if($request === null) { $request = $this->module->getRequest(); } - parent::verifyResourceRequest($request, $response, $scope); + return parent::verifyResourceRequest($request, $response, $scope); } public function handleTokenRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null) From 5ae72fa434850242ba7374ee911fbfcbb1e6c593 Mon Sep 17 00:00:00 2001 From: freezy Date: Mon, 6 Jul 2015 10:30:53 +0200 Subject: [PATCH 20/67] Updated Module params phpDocs --- Module.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Module.php b/Module.php index 108ccb2..cf9b792 100755 --- a/Module.php +++ b/Module.php @@ -48,12 +48,12 @@ class Module extends \yii\base\Module public $grantTypes = []; /** - * @var string name of access token parameter + * @var string Name of access token parameter */ public $tokenParamName; /** - * @var type max access lifetime + * @var integer Max access token lifetime in seconds */ public $tokenAccessLifetime; From f609415be7085a198de412f46c65c754e19fab50 Mon Sep 17 00:00:00 2001 From: freezy Date: Mon, 6 Jul 2015 10:35:34 +0200 Subject: [PATCH 21/67] Added option to set custom ResponseTypes --- Module.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Module.php b/Module.php index cf9b792..eb68adc 100755 --- a/Module.php +++ b/Module.php @@ -46,6 +46,11 @@ class Module extends \yii\base\Module * @var array GrantTypes collection */ public $grantTypes = []; + + /** + * @var array ResponseTypes collection + */ + public $responseTypes = []; /** * @var string Name of access token parameter @@ -104,7 +109,8 @@ public function getServer() 'access_lifetime' => $this->tokenAccessLifetime, /** add more ... */ ], - $grantTypes + $grantTypes, + $this->responseTypes ]); $this->set('server', $server); From 276b1058279972bdc4d4126084ca7c061d1087d3 Mon Sep 17 00:00:00 2001 From: Maliy Igor Date: Tue, 14 Jul 2015 11:48:20 +0300 Subject: [PATCH 22/67] Added support refresh_token_lifetime option --- Module.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Module.php b/Module.php index eb68adc..838a7ec 100755 --- a/Module.php +++ b/Module.php @@ -62,6 +62,11 @@ class Module extends \yii\base\Module */ public $tokenAccessLifetime; + /** + * @var integer Max refresh token lifetime in seconds + */ + public $tokenRefreshLifetime; + /** * @inheritdoc */ @@ -107,6 +112,7 @@ public function getServer() [ 'token_param_name' => $this->tokenParamName, 'access_lifetime' => $this->tokenAccessLifetime, + 'refresh_token_lifetime' => $this->tokenRefreshLifetime, /** add more ... */ ], $grantTypes, From 50231c62f15e2dbc3f418dc8794b93e37a4a67e5 Mon Sep 17 00:00:00 2001 From: Maliy Igor Date: Tue, 14 Jul 2015 13:18:05 +0300 Subject: [PATCH 23/67] Remove a fixed module ID --- Bootstrap.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Bootstrap.php b/Bootstrap.php index 72f6529..094fe38 100644 --- a/Bootstrap.php +++ b/Bootstrap.php @@ -4,7 +4,7 @@ /** * Instead use bootstrap module - * must be removed in v2.1 + * should be removed in v2.1 version * * @deprecated v2.0.1 */ From a7c95fdcce0d9fa8d10608cbbcf0367dbc39b2bf Mon Sep 17 00:00:00 2001 From: Igor Maliy Date: Tue, 14 Jul 2015 13:29:57 +0300 Subject: [PATCH 24/67] Update README.md --- README.md | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index d186ca2..6c0b10e 100755 --- a/README.md +++ b/README.md @@ -25,20 +25,23 @@ to the require section of your composer.json. To use this extension, simply add the following code in your application configuration: ```php -'oauth2' => [ - 'class' => 'filsh\yii2\oauth2server\Module', - 'tokenParamName' => 'accessToken', - 'tokenAccessLifetime' => 3600 * 24, - 'storageMap' => [ - 'user_credentials' => 'common\models\User', - ], - 'grantTypes' => [ - 'user_credentials' => [ - 'class' => 'OAuth2\GrantType\UserCredentials', +'bootstrap' => ['oauth2'], +'modules' => [ + 'oauth2' => [ + 'class' => 'filsh\yii2\oauth2server\Module', + 'tokenParamName' => 'accessToken', + 'tokenAccessLifetime' => 3600 * 24, + 'storageMap' => [ + 'user_credentials' => 'common\models\User', ], - 'refresh_token' => [ - 'class' => 'OAuth2\GrantType\RefreshToken', - 'always_issue_new_refresh_token' => true + 'grantTypes' => [ + 'user_credentials' => [ + 'class' => 'OAuth2\GrantType\UserCredentials', + ], + 'refresh_token' => [ + 'class' => 'OAuth2\GrantType\RefreshToken', + 'always_issue_new_refresh_token' => true + ] ] ] ] From c0a892b3533b5e62715e087343ebfbf9a5d0185a Mon Sep 17 00:00:00 2001 From: Aleksandr Date: Wed, 26 Aug 2015 15:19:55 +0300 Subject: [PATCH 25/67] Update README.md Config example updated --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d186ca2..01f3b17 100644 --- a/README.md +++ b/README.md @@ -27,8 +27,10 @@ To use this extension, simply add the following code in your application config ```php 'oauth2' => [ 'class' => 'filsh\yii2\oauth2server\Module', - 'tokenParamName' => 'accessToken', - 'tokenAccessLifetime' => 3600 * 24, + 'options' => [ + 'token_param_name' => 'accessToken', + 'access_lifetime' => 3600 * 24, + ], 'storageMap' => [ 'user_credentials' => 'common\models\User', ], From 30170af968a4bce928e9644fcc1701f6a1a57542 Mon Sep 17 00:00:00 2001 From: Aleksandr Date: Wed, 26 Aug 2015 15:32:54 +0300 Subject: [PATCH 26/67] Update README.md Add "get access token" example. --- README.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/README.md b/README.md index 01f3b17..003d0bc 100644 --- a/README.md +++ b/README.md @@ -102,4 +102,19 @@ class Controller extends \yii\rest\Controller } ``` +To get access token (js example): + +```js +var url = window.location.host + "/oauth2/token"; +var data = { + 'grant_type':'password', + 'username':'', + 'password':'', + 'client_id':'testclient', + 'client_secret':'testpass' +}; +//ajax POST `data` to `url` here +// +``` + For more, see https://github.com/bshaffer/oauth2-server-php From 4a98bc0ee3d99c1c994b8d59d5a673cb939fe911 Mon Sep 17 00:00:00 2001 From: femike Date: Sun, 20 Sep 2015 13:45:58 +0500 Subject: [PATCH 27/67] Created helpers for Authorization Code and update README.md --- Module.php | 31 ++++++++++++++++++++++++++++ README.md | 35 +++++++++++++++++++++++++++++++- Server.php | 11 ++++++++++ controllers/RestController.php | 37 ++++++++++++++++++---------------- 4 files changed, 96 insertions(+), 18 deletions(-) diff --git a/Module.php b/Module.php index 317247d..f3e911c 100755 --- a/Module.php +++ b/Module.php @@ -154,6 +154,37 @@ public function getResponse() return $this->get('response'); } + /** + * @param $response + */ + public function setResponse($response) + { + Yii::$app->response->setStatusCode($response->getStatusCode()); + $headers = Yii::$app->response->getHeaders(); + + foreach ($response->getHttpHeaders() as $name => $value) + $headers->set($name, $value); + } + + /** + * @param $is_authorized + * @param $user_id + * @return \OAuth2\ResponseInterface + * @throws \yii\base\InvalidConfigException + */ + public function handleAuthorizeRequest($is_authorized, $user_id) + { + $response = $this->getServer()->handleAuthorizeRequest( + $this->getRequest(), + $this->getResponse(), + $is_authorized, + $user_id + ); + $this->setResponse($response); + + return $response; + } + /** * Register translations for this module * diff --git a/README.md b/README.md index 6c0b10e..de96fb0 100755 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ add url rule to urlManager ```php 'urlManager' => [ 'rules' => [ - 'POST oauth2/' => 'oauth2/default/', + 'POST oauth2/' => 'oauth2/rest/', ... ] ] @@ -103,4 +103,37 @@ class Controller extends \yii\rest\Controller } ``` +Create action authorize in site controller for Authorization Code + +`https://api.mysite.com/authorize?response_type=code&client_id=TestClient&redirect_uri=https://fake/` + +[see more](http://bshaffer.github.io/oauth2-server-php-docs/grant-types/authorization-code/) + +```php +/** + * SiteController + */ +class SiteController extends Controller +{ + /** + * @return mixed + */ + public function actionAuthorize() + { + if (Yii::$app->getUser()->getIsGuest()) + return $this->redirect('login'); + + /** @var $module \filsh\yii2\oauth2server\Module */ + $module = Yii::$app->getModule('oauth2'); + $response = $module->handleAuthorizeRequest(!Yii::$app->getUser()->getIsGuest(), Yii::$app->getUser()->getId()); + + /** @var object $response \OAuth2\Response */ + Yii::$app->getResponse()->format = \yii\web\Response::FORMAT_JSON; + + return $response->getParameters(); + } +} +``` + + For more, see https://github.com/bshaffer/oauth2-server-php diff --git a/Server.php b/Server.php index 5535573..a7be272 100644 --- a/Server.php +++ b/Server.php @@ -38,4 +38,15 @@ public function handleTokenRequest(\OAuth2\RequestInterface $request = null, \OA } return parent::handleTokenRequest($request, $response); } + + public function handleAuthorizeRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null, $is_authorized = false, $user_id = null) + { + if($request === null) + $request = $this->module->getRequest(); + + if($response === null) + $response = $this->module->getResponse(); + + return parent::handleAuthorizeRequest($request, $response, $is_authorized, $user_id); + } } diff --git a/controllers/RestController.php b/controllers/RestController.php index c9978b3..32bb884 100755 --- a/controllers/RestController.php +++ b/controllers/RestController.php @@ -8,21 +8,24 @@ class RestController extends \yii\rest\Controller { - /** - * @inheritdoc - */ - public function behaviors() - { - return ArrayHelper::merge(parent::behaviors(), [ - 'exceptionFilter' => [ - 'class' => ErrorToExceptionFilter::className() - ], - ]); - } - - public function actionToken() - { - $response = $this->module->getServer()->handleTokenRequest(); - return $response->getParameters(); - } + /** + * @inheritdoc + */ + public function behaviors() + { + return ArrayHelper::merge(parent::behaviors(), [ + 'exceptionFilter' => [ + 'class' => ErrorToExceptionFilter::className() + ], + ]); + } + + public function actionToken() + { + $response = $this->module->getServer()->handleTokenRequest(); + + /** @var $response \OAuth2\Response */ + + return $response->getParameters(); + } } \ No newline at end of file From dfd349660bfbaf31c55511abb1b1df2d8d3a5480 Mon Sep 17 00:00:00 2001 From: Maliy Igor Date: Tue, 22 Sep 2015 10:17:02 +0300 Subject: [PATCH 28/67] Update codestyle --- Module.php | 13 ++++++------ Server.php | 13 ++++++------ controllers/RestController.php | 38 ++++++++++++++++------------------ 3 files changed, 32 insertions(+), 32 deletions(-) diff --git a/Module.php b/Module.php index f3e911c..2de8d95 100755 --- a/Module.php +++ b/Module.php @@ -162,23 +162,24 @@ public function setResponse($response) Yii::$app->response->setStatusCode($response->getStatusCode()); $headers = Yii::$app->response->getHeaders(); - foreach ($response->getHttpHeaders() as $name => $value) + foreach ($response->getHttpHeaders() as $name => $value) { $headers->set($name, $value); + } } /** - * @param $is_authorized - * @param $user_id + * @param $isAuthorized + * @param $userId * @return \OAuth2\ResponseInterface * @throws \yii\base\InvalidConfigException */ - public function handleAuthorizeRequest($is_authorized, $user_id) + public function handleAuthorizeRequest($isAuthorized, $userId) { $response = $this->getServer()->handleAuthorizeRequest( $this->getRequest(), $this->getResponse(), - $is_authorized, - $user_id + $isAuthorized, + $userId ); $this->setResponse($response); diff --git a/Server.php b/Server.php index a7be272..df41d4a 100644 --- a/Server.php +++ b/Server.php @@ -39,14 +39,15 @@ public function handleTokenRequest(\OAuth2\RequestInterface $request = null, \OA return parent::handleTokenRequest($request, $response); } - public function handleAuthorizeRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null, $is_authorized = false, $user_id = null) + public function handleAuthorizeRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null, $isAuthorized = false, $userId = null) { - if($request === null) + if($request === null) { $request = $this->module->getRequest(); - - if($response === null) + } + if($response === null) { $response = $this->module->getResponse(); - - return parent::handleAuthorizeRequest($request, $response, $is_authorized, $user_id); + } + + return parent::handleAuthorizeRequest($request, $response, $isAuthorized, $userId); } } diff --git a/controllers/RestController.php b/controllers/RestController.php index 32bb884..a2d6770 100755 --- a/controllers/RestController.php +++ b/controllers/RestController.php @@ -8,24 +8,22 @@ class RestController extends \yii\rest\Controller { - /** - * @inheritdoc - */ - public function behaviors() - { - return ArrayHelper::merge(parent::behaviors(), [ - 'exceptionFilter' => [ - 'class' => ErrorToExceptionFilter::className() - ], - ]); - } + /** + * @inheritdoc + */ + public function behaviors() + { + return ArrayHelper::merge(parent::behaviors(), [ + 'exceptionFilter' => [ + 'class' => ErrorToExceptionFilter::className() + ], + ]); + } - public function actionToken() - { - $response = $this->module->getServer()->handleTokenRequest(); - - /** @var $response \OAuth2\Response */ - - return $response->getParameters(); - } -} \ No newline at end of file + public function actionToken() + { + /** @var $response \OAuth2\Response */ + $response = $this->module->getServer()->handleTokenRequest(); + return $response->getParameters(); + } +} From c444445c156ddd2d575b310bd046404841bb0ce6 Mon Sep 17 00:00:00 2001 From: pdanzinger Date: Fri, 23 Oct 2015 13:31:53 +0200 Subject: [PATCH 29/67] Fix migration for yii 2.0.6 Since yii 2.0.6 the Migration class implements the \yii\db\SchemaBuilderTrait, which has a function called primaryKey($length = null) that causes an exception to be thrown when migrating. I renamed the primaryKey() function in this migration class to buildPrimaryKey(), as well as foreignKey() to buildForeignKey() to preserve consistancy. --- .../m140501_075311_add_oauth2_server.php | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/migrations/m140501_075311_add_oauth2_server.php b/migrations/m140501_075311_add_oauth2_server.php index a34fccb..4f699bf 100644 --- a/migrations/m140501_075311_add_oauth2_server.php +++ b/migrations/m140501_075311_add_oauth2_server.php @@ -9,11 +9,11 @@ public function mysql($yes,$no='') { return $this->db->driverName === 'mysql' ? $yes : $no; } - public function primaryKey($columns) { + public function buildPrimaryKey($columns) { return 'PRIMARY KEY (' . $this->db->getQueryBuilder()->buildColumns($columns) . ')'; } - public function foreignKey($columns,$refTable,$refColumns,$onDelete = null,$onUpdate = null) { + public function buildForeignKey($columns,$refTable,$refColumns,$onDelete = null,$onUpdate = null) { $builder = $this->db->getQueryBuilder(); $sql = ' FOREIGN KEY (' . $builder->buildColumns($columns) . ')' . ' REFERENCES ' . $this->db->quoteTableName($refTable) @@ -46,7 +46,7 @@ public function up() 'grant_types' => Schema::TYPE_STRING . '(100) NOT NULL', 'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', 'user_id' => Schema::TYPE_INTEGER . ' DEFAULT NULL', - $this->primaryKey('client_id'), + $this->buildPrimaryKey('client_id'), ], $tableOptions); $this->createTable('{{%oauth_access_tokens}}', [ @@ -55,8 +55,8 @@ public function up() 'user_id' => Schema::TYPE_INTEGER . ' DEFAULT NULL', 'expires' => Schema::TYPE_TIMESTAMP . " NOT NULL DEFAULT $now $on_update_now", 'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', - $this->primaryKey('access_token'), - $this->foreignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), + $this->buildPrimaryKey('access_token'), + $this->buildForeignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), ], $tableOptions); $this->createTable('{{%oauth_refresh_tokens}}', [ @@ -65,8 +65,8 @@ public function up() 'user_id' => Schema::TYPE_INTEGER . ' DEFAULT NULL', 'expires' => Schema::TYPE_TIMESTAMP . " NOT NULL DEFAULT $now $on_update_now", 'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', - $this->primaryKey('refresh_token'), - $this->foreignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), + $this->buildPrimaryKey('refresh_token'), + $this->buildForeignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), ], $tableOptions); $this->createTable('{{%oauth_authorization_codes}}', [ @@ -76,8 +76,8 @@ public function up() 'redirect_uri' => Schema::TYPE_STRING . '(1000) NOT NULL', 'expires' => Schema::TYPE_TIMESTAMP . " NOT NULL DEFAULT $now $on_update_now", 'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', - $this->primaryKey('authorization_code'), - $this->foreignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), + $this->buildPrimaryKey('authorization_code'), + $this->buildForeignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), ], $tableOptions); $this->createTable('{{%oauth_scopes}}', [ @@ -89,7 +89,7 @@ public function up() 'client_id' => Schema::TYPE_STRING . '(32) NOT NULL', 'subject' => Schema::TYPE_STRING . '(80) DEFAULT NULL', 'public_key' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', - $this->primaryKey('client_id'), + $this->buildPrimaryKey('client_id'), ], $tableOptions); $this->createTable('{{%oauth_users}}', [ @@ -97,7 +97,7 @@ public function up() 'password' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', 'first_name' => Schema::TYPE_STRING . '(255) DEFAULT NULL', 'last_name' => Schema::TYPE_STRING . '(255) DEFAULT NULL', - $this->primaryKey('username'), + $this->buildPrimaryKey('username'), ], $tableOptions); $this->createTable('{{%oauth_public_keys}}', [ From 1b7aebc6610c6a231c55c022650a72f001546de8 Mon Sep 17 00:00:00 2001 From: dmtux Date: Mon, 26 Oct 2015 18:17:33 +0200 Subject: [PATCH 30/67] Enforce State and Implicit Grant Type --- Module.php | 12 ++++++++++++ README.md | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/Module.php b/Module.php index 2de8d95..2a66070 100755 --- a/Module.php +++ b/Module.php @@ -68,6 +68,16 @@ class Module extends \yii\base\Module implements \yii\base\BootstrapInterface * @var integer Max refresh token lifetime in seconds */ public $tokenRefreshLifetime; + + /** + * @var bool enforce state flag + */ + public $enforceState; + + /** + * @var bool allow_implicit flag + */ + public $allowImplicit; /** * @inheritdoc @@ -127,6 +137,8 @@ public function getServer() 'token_param_name' => $this->tokenParamName, 'access_lifetime' => $this->tokenAccessLifetime, 'refresh_token_lifetime' => $this->tokenRefreshLifetime, + 'enforce_state' => $this->enforceState, + 'allow_implicit' => $this->allowImplicit /** add more ... */ ], $grantTypes, diff --git a/README.md b/README.md index de96fb0..17413f4 100755 --- a/README.md +++ b/README.md @@ -49,6 +49,12 @@ To use this extension, simply add the following code in your application config ```common\models\User``` - user model implementing an interface ```\OAuth2\Storage\UserCredentialsInterface```, so the oauth2 credentials data stored in user table +Additional OAuth2 Flags: + +```enforceState``` - Flag that switch that state controller should allow to use "state" param in the "Authorization Code" Grant Type + +```allowImplicit``` - Flag that switch that controller should allow the "implicit" grant type + The next step your shold run migration ```php @@ -135,5 +141,18 @@ class SiteController extends Controller } ``` +Also if you set ```allowImplicit => true``` you can use Implicit Grant Type - [see more](http://bshaffer.github.io/oauth2-server-php-docs/grant-types/implicit/) + +Request example: + +`https://api.mysite.com/authorize?response_type=token&client_id=TestClient&redirect_uri=https://fake/cb` + +With redirect response: + +`https://fake/cb#access_token=2YotnFZFEjr1zCsicMWpAA&state=xyz&token_type=bearer&expires_in=3600` + + + + For more, see https://github.com/bshaffer/oauth2-server-php From 71866ae209e173270d42d5cd01e48dfe96dd2072 Mon Sep 17 00:00:00 2001 From: Denis Melskiy Date: Mon, 26 Oct 2015 18:19:45 +0200 Subject: [PATCH 31/67] Update README.md --- README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/README.md b/README.md index 17413f4..c731ee1 100755 --- a/README.md +++ b/README.md @@ -152,7 +152,4 @@ With redirect response: `https://fake/cb#access_token=2YotnFZFEjr1zCsicMWpAA&state=xyz&token_type=bearer&expires_in=3600` - - - For more, see https://github.com/bshaffer/oauth2-server-php From 3ceb1ea037f08d55a2b842c7a1715a9caab27a58 Mon Sep 17 00:00:00 2001 From: Hector del Rio Date: Thu, 29 Oct 2015 09:47:50 +0200 Subject: [PATCH 32/67] Update m140501_075311_add_oauth2_server.php MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I was getting the following exception: ´´´ PHP Strict Warning 'yii\base\ErrorException' with message 'Declaration of m140501_075311_add_oauth2_server::primaryKey() should be compatible with yii\db\Migration::primaryKey($length = NULL)' ´´´ --- migrations/m140501_075311_add_oauth2_server.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/migrations/m140501_075311_add_oauth2_server.php b/migrations/m140501_075311_add_oauth2_server.php index 4f699bf..a589ba6 100644 --- a/migrations/m140501_075311_add_oauth2_server.php +++ b/migrations/m140501_075311_add_oauth2_server.php @@ -9,7 +9,7 @@ public function mysql($yes,$no='') { return $this->db->driverName === 'mysql' ? $yes : $no; } - public function buildPrimaryKey($columns) { + public function buildPrimaryKey($columns = null) { return 'PRIMARY KEY (' . $this->db->getQueryBuilder()->buildColumns($columns) . ')'; } From 649608a85f230a6ec80610d1762dafb77a6448e7 Mon Sep 17 00:00:00 2001 From: Paolo Date: Wed, 16 Dec 2015 02:41:59 +0100 Subject: [PATCH 33/67] Update README.md There's no default controller, so the path in rules was oauth2/rest/ --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 003d0bc..b2af582 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ add url rule to urlManager ```php 'urlManager' => [ 'rules' => [ - 'POST oauth2/' => 'oauth2/default/', + 'POST oauth2/' => 'oauth2/rest/', ... ] ] From 18e8805f0fc3015e777b98df4037a22724cfce2e Mon Sep 17 00:00:00 2001 From: "Stefano D. Mtangoo" Date: Sat, 26 Dec 2015 21:31:23 +0300 Subject: [PATCH 34/67] Update README.md --- README.md | 39 +++++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index b2af582..879c1b5 100644 --- a/README.md +++ b/README.md @@ -25,27 +25,29 @@ to the require section of your composer.json. To use this extension, simply add the following code in your application configuration: ```php -'oauth2' => [ - 'class' => 'filsh\yii2\oauth2server\Module', - 'options' => [ - 'token_param_name' => 'accessToken', - 'access_lifetime' => 3600 * 24, - ], - 'storageMap' => [ - 'user_credentials' => 'common\models\User', - ], - 'grantTypes' => [ - 'user_credentials' => [ - 'class' => 'OAuth2\GrantType\UserCredentials', - ], - 'refresh_token' => [ - 'class' => 'OAuth2\GrantType\RefreshToken', - 'always_issue_new_refresh_token' => true +'modules'=>[ + //other modules ..... + 'oauth2' => [ + 'class' => 'filsh\yii2\oauth2server\Module', + 'tokenParamName' => 'access_token', + 'tokenAccessLifetime' => 3600 * 24, + 'storageMap' => [ + 'user_credentials' => 'app\models\User', + ], + 'grantTypes' => [ + 'user_credentials' => [ + 'class' => 'OAuth2\GrantType\UserCredentials', + ], + 'refresh_token' => [ + 'class' => 'OAuth2\GrantType\RefreshToken', + 'always_issue_new_refresh_token' => true + ] + ] ] - ] -] + ], ``` + ```common\models\User``` - user model implementing an interface ```\OAuth2\Storage\UserCredentialsInterface```, so the oauth2 credentials data stored in user table The next step your shold run migration @@ -60,6 +62,7 @@ add url rule to urlManager ```php 'urlManager' => [ + 'enablePrettyUrl' => true, //only if you want to use petty URLs 'rules' => [ 'POST oauth2/' => 'oauth2/rest/', ... From b0557dd50851b68163f3b5fb613f588d47c11cd1 Mon Sep 17 00:00:00 2001 From: Igor Maliy Date: Wed, 30 Dec 2015 10:04:05 +0200 Subject: [PATCH 35/67] merge pull request #64 --- README.md | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 879c1b5..b98d7a0 100644 --- a/README.md +++ b/README.md @@ -22,14 +22,14 @@ or add to the require section of your composer.json. -To use this extension, simply add the following code in your application configuration: +To use this extension, simply add the following code in your application configuration as a new module: ```php 'modules'=>[ //other modules ..... 'oauth2' => [ 'class' => 'filsh\yii2\oauth2server\Module', - 'tokenParamName' => 'access_token', + 'tokenParamName' => 'accessToken', 'tokenAccessLifetime' => 3600 * 24, 'storageMap' => [ 'user_credentials' => 'app\models\User', @@ -48,7 +48,54 @@ To use this extension, simply add the following code in your application config ``` -```common\models\User``` - user model implementing an interface ```\OAuth2\Storage\UserCredentialsInterface```, so the oauth2 credentials data stored in user table +Also, extend ```common\models\User``` - user model - implementing the interface ```\OAuth2\Storage\UserCredentialsInterface```, so the oauth2 credentials data stored in user table. +You should implement: +- findIdentityByAccessToken() +- checkUserCredentials() +- getUserDetails() + +You can extend the model if you prefer it (please, remember to update the config files) : +``` +use Yii; + +class User extends common\models\User implements \OAuth2\Storage\UserCredentialsInterface +{ + + /** + * Implemented for Oauth2 Interface + */ + public static function findIdentityByAccessToken($token, $type = null) + { + /** @var \filsh\yii2\oauth2server\Module $module */ + $module = Yii::$app->getModule('oauth2'); + $token = $module->getServer()->getResourceController()->getToken(); + return !empty($token['user_id']) + ? static::findIdentity($token['user_id']) + : null; + } + + /** + * Implemented for Oauth2 Interface + */ + public function checkUserCredentials($username, $password) + { + $user = static::findByUsername($username); + if (empty($user)) { + return false; + } + return $user->validatePassword($password); + } + + /** + * Implemented for Oauth2 Interface + */ + public function getUserDetails($username) + { + $user = static::findByUsername($username); + return ['user_id' => $user->getId()]; + } +} +``` The next step your shold run migration From db390f057c3986c30dd27e662b743697625faad3 Mon Sep 17 00:00:00 2001 From: "Stefano D. Mtangoo" Date: Sat, 2 Jan 2016 19:27:08 +0300 Subject: [PATCH 36/67] Support for JWT tokens --- Module.php | 216 ++++++++++++++++++++++++----------------------------- 1 file changed, 98 insertions(+), 118 deletions(-) diff --git a/Module.php b/Module.php index 496b276..a12f83f 100644 --- a/Module.php +++ b/Module.php @@ -3,6 +3,7 @@ namespace filsh\yii2\oauth2server; use \Yii; +use yii\i18n\PhpMessageSource; /** * For example, @@ -10,48 +11,55 @@ * ```php * 'oauth2' => [ * 'class' => 'filsh\yii2\oauth2server\Module', - * 'options' => [ - * 'token_param_name' => 'accessToken', - * 'access_lifetime' => 3600 - * ], + * 'tokenParamName' => 'accessToken', + * 'tokenAccessLifetime' => 3600 * 24, * 'storageMap' => [ - * 'user_credentials' => 'common\models\User' + * 'user_credentials' => 'common\models\User', * ], * 'grantTypes' => [ - * 'client_credentials' => [ - * 'class' => '\OAuth2\GrantType\ClientCredentials', - * 'allow_public_clients' => false - * ], * 'user_credentials' => [ - * 'class' => '\OAuth2\GrantType\UserCredentials' + * 'class' => 'OAuth2\GrantType\UserCredentials', * ], * 'refresh_token' => [ - * 'class' => '\OAuth2\GrantType\RefreshToken', + * 'class' => 'OAuth2\GrantType\RefreshToken', * 'always_issue_new_refresh_token' => true * ] - * ], + * ] * ] * ``` */ class Module extends \yii\base\Module { - public $options = []; + const VERSION = '2.0.0'; - public $storageMap = []; + /** + * @var array Model's map + */ + public $modelMap = []; - public $storageDefault = 'filsh\yii2\oauth2server\storage\Pdo'; + /** + * @var array Storage's map + */ + public $storageMap = []; + /** + * @var array GrantTypes collection + */ public $grantTypes = []; - public $modelClasses = []; - - public $i18n; - - private $_server; - - private $_request; + /** + * @var string name of access token parameter + */ + public $tokenParamName; - private $_models = []; + /** + * @var type max access lifetime + */ + public $tokenAccessLifetime; + /** + * @var whether to use JWT tokens + */ + public $useJwtToken = false;//ADDED /** * @inheritdoc @@ -59,141 +67,113 @@ class Module extends \yii\base\Module public function init() { parent::init(); - $this->modelClasses = array_merge($this->getDefaultModelClasses(), $this->modelClasses); $this->registerTranslations(); } /** - * Get oauth2 server instance - * @param type $force - * @return \OAuth2\Server + * Gets Oauth2 Server + * + * @return \filsh\yii2\oauth2server\Server + * @throws \yii\base\InvalidConfigException */ - public function getServer($force = false) + public function getServer() { - if($this->_server === null || $force === true) { - $storages = $this->createStorages(); - $server = new \OAuth2\Server($storages, $this->options); + if(!$this->has('server')) { + $storages = []; + if($this->useJwtToken) + { + if(!isset(storageMap['access_token']) || storageMap['public_key']) { + throw new \yii\base\InvalidConfigException('access_token and public_key must be set or set useJwtToken to false'); + } + //define dependencies when JWT is used instead of normal token + \Yii::$container->clear('public_key'); //remove old definition + \Yii::$container->set('public_key', $this->storageMap['public_key']); + \Yii::$container->set('OAuth2\Storage\PublicKeyInterface', $this->storageMap['public_key']); + + \Yii::$container->clear('access_token'); //remove old definition + \Yii::$container->set('access_token', $this->storageMap['access_token']); + } + + foreach(array_keys($this->storageMap) as $name) { + $storages[$name] = \Yii::$container->get($name); + } + + $grantTypes = []; foreach($this->grantTypes as $name => $options) { if(!isset($storages[$name]) || empty($options['class'])) { throw new \yii\base\InvalidConfigException('Invalid grant types configuration.'); } - + $class = $options['class']; unset($options['class']); - + $reflection = new \ReflectionClass($class); $config = array_merge([0 => $storages[$name]], [$options]); $instance = $reflection->newInstanceArgs($config); - $server->addGrantType($instance); + $grantTypes[$name] = $instance; } - $this->_server = $server; + $server = \Yii::$container->get(Server::className(), [ + $this, + $storages, + [ + 'use_jwt_access_tokens' => $this->useJwtToken,//ADDED + 'token_param_name' => $this->tokenParamName, + 'access_lifetime' => $this->tokenAccessLifetime, + /** add more ... */ + ], + $grantTypes + ]); + + $this->set('server', $server); } - return $this->_server; - } - - /** - * Get oauth2 request instance from global variables - * @return \OAuth2\Request - */ - public function getRequest($force = false) - { - if ($this->_request === null || $force) { - $this->_request = \OAuth2\Request::createFromGlobals(); - }; - return $this->_request; + return $this->get('server'); } - /** - * Get oauth2 response instance - * @return \OAuth2\Response - */ - public function getResponse() - { - return new \OAuth2\Response(); - } - - /** - * Create storages - * @return type - */ - public function createStorages() + public function getRequest() { - $connection = Yii::$app->getDb(); - if(!$connection->getIsActive()) { - $connection->open(); + if(!$this->has('request')) { + $this->set('request', Request::createFromGlobals()); } - - $storages = []; - foreach($this->storageMap as $name => $storage) { - $storages[$name] = Yii::createObject($storage); - } - - $defaults = [ - 'access_token', - 'authorization_code', - 'client_credentials', - 'client', - 'refresh_token', - 'user_credentials', - 'public_key', - 'jwt_bearer', - 'scope', - ]; - foreach($defaults as $name) { - if(!isset($storages[$name])) { - $storages[$name] = Yii::createObject($this->storageDefault); - } - } - - return $storages; + return $this->get('request'); } - /** - * Get object instance of model - * @param string $name - * @param array $config - * @return ActiveRecord - */ - public function model($name, $config = []) + public function getResponse() { - if(!isset($this->_models[$name])) { - $className = $this->modelClasses[ucfirst($name)]; - $this->_models[$name] = Yii::createObject(array_merge(['class' => $className], $config)); + if(!$this->has('response')) { + $this->set('response', new Response()); } - return $this->_models[$name]; + return $this->get('response'); } - + /** * Register translations for this module + * * @return array */ public function registerTranslations() { - Yii::setAlias('@oauth2server', dirname(__FILE__)); - if (empty($this->i18n)) { - $this->i18n = [ - 'class' => 'yii\i18n\PhpMessageSource', - 'basePath' => '@oauth2server/messages', + if(!isset(Yii::$app->get('i18n')->translations['modules/oauth2/*'])) { + Yii::$app->get('i18n')->translations['modules/oauth2/*'] = [ + 'class' => PhpMessageSource::className(), + 'basePath' => __DIR__ . '/messages', ]; } - Yii::$app->i18n->translations['oauth2server'] = $this->i18n; } - + /** - * Get default model classes - * @return array + * Translate module message + * + * @param string $category + * @param string $message + * @param array $params + * @param string $language + * @return string */ - protected function getDefaultModelClasses() + public static function t($category, $message, $params = [], $language = null) { - return [ - 'Clients' => 'filsh\yii2\oauth2server\models\OauthClients', - 'AccessTokens' => 'filsh\yii2\oauth2server\models\OauthAccessTokens', - 'AuthorizationCodes' => 'filsh\yii2\oauth2server\models\OauthAuthorizationCodes', - 'RefreshTokens' => 'filsh\yii2\oauth2server\models\OauthRefreshTokens', - 'Scopes' => 'filsh\yii2\oauth2server\models\OauthScopes', - ]; + return Yii::t('modules/oauth2/' . $category, $message, $params, $language); } } From 8227705b5db7fc8b233e9fabaf12e4f29e481605 Mon Sep 17 00:00:00 2001 From: "Stefano D. Mtangoo" Date: Sat, 2 Jan 2016 19:46:36 +0300 Subject: [PATCH 37/67] Update to cover JWT --- README.md | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/README.md b/README.md index b98d7a0..cbc064f 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,80 @@ To use this extension, simply add the following code in your application config ] ], ``` +If you want to get Json Web Token (JWT) instead of convetional token, you will need to set `'useJwtToken' => true` in module and then define two more configurations: +`'public_key' => 'app\storage\PublicKeyStorage'` which is the class that implements [PublickKeyInterface](https://github.com/bshaffer/oauth2-server-php/blob/develop/src/OAuth2/Storage/PublicKeyInterface.php) and `'access_token' => 'app\storage\JwtAccessToken'` which implements [JwtAccessTokenInterface.php](https://github.com/bshaffer/oauth2-server-php/blob/develop/src/OAuth2/Storage/JwtAccessTokenInterface.php) +For Oauth2 base library provides the default [access_token](https://github.com/bshaffer/oauth2-server-php/blob/develop/src/OAuth2/Storage/JwtAccessToken.php) which works great except that it tries to save the token in the database. So I decided to inherit from it and override the part that tries to save (token size is too big and crashes with VARCHAR(40) in the database. + +TL;DR, here are the sample classes +**access_token** +```php + + */ +class JwtAccessToken extends \OAuth2\Storage\JwtAccessToken +{ + public function setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope = null) + { + + } + + public function unsetAccessToken($access_token) + { + + } +} + +``` + +and **public_key** + +```php +pbk = file_get_contents('privkey.pem', true); + $this->pvk = file_get_contents('pubkey.pem', true); + } + + public function getPublicKey($client_id = null){ + return $this->pbk; + } + + public function getPrivateKey($client_id = null){ + return $this->pvk; + } + + public function getEncryptionAlgorithm($client_id = null){ + return 'HS256'; + } + +} + +``` +**NOTE:** You will need [this](https://github.com/bshaffer/oauth2-server-php/pull/690) PR applied or you can patch it yourself by checking changes in [this diff](https://github.com/hosannahighertech/oauth2-server-php/commit/ec79732663547065c041e279109137a423eac0cb). The other part of PR is only if you want to use firebase JWT library (which is not mandatory anyway). Also, extend ```common\models\User``` - user model - implementing the interface ```\OAuth2\Storage\UserCredentialsInterface```, so the oauth2 credentials data stored in user table. You should implement: From 33d950b50bbd89b53134320e9ee2648fc3950311 Mon Sep 17 00:00:00 2001 From: "Stefano D. Mtangoo" Date: Tue, 5 Jan 2016 10:48:45 +0300 Subject: [PATCH 38/67] Fix Bugs I introduced with support for JWT token Being tired I used wrong logic (and abused therof the use of isset). This fixes that and is tested and works fine --- Module.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Module.php b/Module.php index a12f83f..375a36d 100644 --- a/Module.php +++ b/Module.php @@ -4,6 +4,7 @@ use \Yii; use yii\i18n\PhpMessageSource; +use \array_key_exists; /** * For example, @@ -83,7 +84,7 @@ public function getServer() if($this->useJwtToken) { - if(!isset(storageMap['access_token']) || storageMap['public_key']) { + if(!array_key_exists('access_token', $this->storageMap) || !array_key_exists('public_key', $this->storageMap)) { throw new \yii\base\InvalidConfigException('access_token and public_key must be set or set useJwtToken to false'); } //define dependencies when JWT is used instead of normal token From 40ef97f649ddb43c1942e95d854c8f57f65850c6 Mon Sep 17 00:00:00 2001 From: Tibor Balogh Date: Tue, 5 Jan 2016 17:44:01 +0100 Subject: [PATCH 39/67] Hungarian translation of oauth2server.php --- messages/hu/oauth2server.php | 54 ++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 messages/hu/oauth2server.php diff --git a/messages/hu/oauth2server.php b/messages/hu/oauth2server.php new file mode 100644 index 0000000..86a391f --- /dev/null +++ b/messages/hu/oauth2server.php @@ -0,0 +1,54 @@ + 'Átirányítási URI megadása kötelező, ha több van belőle regisztrálva', + 'An unsupported scope was requested' => 'Nem támogatott \'scope\' került kérésre', + 'Authorization code doesn\'t exist or is invalid for the client' => 'A megadott azonosítási kód nem létezik, vagy a klienshez nem megfelelő.', + 'client credentials are required' => 'kliensazonosítók megadása kötelező', + 'Expiration (exp) time must be a unix time stamp' => 'A lejárati időnek (exp) unix időbélyegnek kell lennie', + 'Expiration (exp) time must be present' => 'A lejárati időt (exp) meg kell adni', + 'Invalid audience (aud)' => 'Nem megfelelő közönség (audience, aud)', + 'Invalid issuer (iss) or subject (sub) provided' => 'Nem megfelelő kiállító (issuer, iss) vagy tárgy (subject, sub) lett megadva', + 'Invalid issuer (iss) provided' => 'Nem megfelelő kiállító (issuer, iss) lett megadva', + 'Invalid refresh token' => 'Nem megfelelő \'refresh token\'', + 'Invalid subject (sub) provided' => 'Nem megfelelő tárgy (subject, sub) lett megadva', + 'Invalid user authkey' => 'Nem megfelelő felhasználói azonosító kulcs (user authkey)', + 'Invalid username and password combination' => 'Nem megfelelő felhasználónév vagy jelszó', + 'JSON Token Identifier (jti) has already been used' => 'A SON tokenazonosító (jti) már korábban felhasználva', + 'JWT cannot be used before the Not Before (nbf) time' => 'JWT nem használható fel a \'Not Before\' (nbf) idő előtt', + 'JWT failed signature verification' => 'A JWT megbukott a digitális aláírás-ellenőrzésen', + 'JWT has expired' => 'A JWT lejárt', + 'JWT is malformed' => 'A JWT nem megfelelő formátumú', + 'Malformed auth header' => 'Nem megfelelő formátumú azonosító fejléc (auth header)', + 'Malformed token (missing "expires" or "client_id")' => 'Nem megfelelő formátumú token (hiányzó lejárati idő (expires) vagy kliens-azonosító (client_id))', + 'Missing parameter: "code" is required' => 'Hiányzó paraméter: "code"', + 'Missing parameter: "refresh_token" is required' => 'Hiányzó paraméter: "refresh_token"', + 'Missing parameters: "assertion" required' => 'Hiányzó paraméter: ""assertion"', + 'Missing parameters: "authkey" and "username" required' => 'Hiányzó paraméterek: "authkey" és "username"', + 'Missing parameters: "username" and "password" required' => 'Hiányzó paraméterek: "username" és "password"', + 'No client id supplied' => 'Nincs megadva kliens-azonosító (client_id)', + 'No redirect URI was supplied or stored' => 'Nincs megadva vagy korábban regisztrálva átirányítási URI', + 'Not Before (nbf) time must be a unix time stamp' => 'A \'Not Before\' (nbf) időnek unix időbélyegnek kell lennie', + 'Only one method may be used to authenticate at a time (Auth header, GET or POST)' => 'Egyidejűleg egy azonosítási mód használható (Azonosító fejléc, GET vagy POST)', + 'Refresh token has expired' => 'A \'refresh token\' lejárt', + 'The access token provided has expired' => 'Az \'access token\' lejárt', + 'The access token provided is invalid' => 'A megadott \'access token\' érvénytelen', + 'The authorization code has expired' => 'Az azonosító kód (authorization code) lejárt', + 'The client credentials are invalid' => 'A megadott kliens-azonosító adatok érvénytelenek', + 'The client id supplied is invalid' => 'A megadott kliens-azonosító (client id) érvénytelen', + 'The content type for POST requests must be "application/x-www-form-urlencoded"' => 'A POST kérés "Content-Type" fejléce "application/x-www-form-urlencoded" kell, hogy legyen', + 'The grant type is unauthorized for this client_id' => 'A megadott klienshez (client id) nem engedélyezett \'grant type\'', + 'The grant type was not specified in the request' => 'A kérés nem tartalmaz engedélykérési típust (grant type)', + 'The redirect URI is mandatory and was not supplied' => 'Az átirányítási URI kötelező, de nem lett megadva', + 'The redirect URI is missing or do not match' => 'Az átirányítási URI nem lett megadva, vagy nem egyezik a regisztrálttal', + 'The redirect URI must not contain a fragment' => 'Az átirányítási URI nem tartalmazhat rész-azonosítót (fragment)', + 'The redirect URI provided is missing or does not match' => 'Az átirányítási URI nem lett megadva, vagy nem egyezik a regisztrálttal', + 'The request method must be POST when requesting an access token' => 'A HTTP kérésnek \'access token\' kérésekor POST-nak kell lennie', + 'The request requires higher privileges than provided by the access token' => 'A kérés kiszolgálására nem jogosít a megadott \'access token\'', + 'The scope requested is invalid for this client' => 'A megadott \'scope\' nem engedélyezett ehhez a klienshez', + 'The scope requested is invalid for this request' => 'A megadott \'scope\' nem engedélyezett ehhez a kéréshez', + 'This application requires you specify a scope parameter' => 'Az alkalmazás megköveteli a \'scope\' paraméter megadását', + 'This client is invalid or must authenticate using a client secret' => 'A megadott kliens nem megfelelő, vagy azonosítani kell \'client secret\' megadásával', + 'Unable to retrieve user information' => 'A felhasználói adatok lekérése nem sikerült', + 'When putting the token in the body, the method must be POST' => 'A HTTP kérésnek POST típusúnak kell lennie, ha a token a törzsében szerepel', + 'you must set the user_id on the array returned by getUserDetails' => 'A \'getUserDetails\' által visszaadott tömbben kell megadni a \'user_id\'-t', +]; From d8c3aba65510f24945c5a984c8cfe2a670f7790b Mon Sep 17 00:00:00 2001 From: "Stefano D. Mtangoo" Date: Wed, 6 Jan 2016 01:46:54 +0300 Subject: [PATCH 40/67] Add Support for JWT Tokens --- Module.php | 95 +++++++++++++----------------------------------------- 1 file changed, 23 insertions(+), 72 deletions(-) diff --git a/Module.php b/Module.php index 2a66070..375a36d 100755 --- a/Module.php +++ b/Module.php @@ -4,6 +4,7 @@ use \Yii; use yii\i18n\PhpMessageSource; +use \array_key_exists; /** * For example, @@ -28,10 +29,8 @@ * ] * ``` */ -class Module extends \yii\base\Module implements \yii\base\BootstrapInterface +class Module extends \yii\base\Module { - use BootstrapTrait; - const VERSION = '2.0.0'; /** @@ -48,48 +47,20 @@ class Module extends \yii\base\Module implements \yii\base\BootstrapInterface * @var array GrantTypes collection */ public $grantTypes = []; - - /** - * @var array ResponseTypes collection - */ - public $responseTypes = []; /** - * @var string Name of access token parameter + * @var string name of access token parameter */ public $tokenParamName; /** - * @var integer Max access token lifetime in seconds + * @var type max access lifetime */ public $tokenAccessLifetime; - /** - * @var integer Max refresh token lifetime in seconds + * @var whether to use JWT tokens */ - public $tokenRefreshLifetime; - - /** - * @var bool enforce state flag - */ - public $enforceState; - - /** - * @var bool allow_implicit flag - */ - public $allowImplicit; - - /** - * @inheritdoc - */ - public function bootstrap($app) - { - $this->initModule($this); - - if ($app instanceof \yii\console\Application) { - $this->controllerNamespace = 'filsh\yii2\oauth2server\commands'; - } - } + public $useJwtToken = false;//ADDED /** * @inheritdoc @@ -110,6 +81,21 @@ public function getServer() { if(!$this->has('server')) { $storages = []; + + if($this->useJwtToken) + { + if(!array_key_exists('access_token', $this->storageMap) || !array_key_exists('public_key', $this->storageMap)) { + throw new \yii\base\InvalidConfigException('access_token and public_key must be set or set useJwtToken to false'); + } + //define dependencies when JWT is used instead of normal token + \Yii::$container->clear('public_key'); //remove old definition + \Yii::$container->set('public_key', $this->storageMap['public_key']); + \Yii::$container->set('OAuth2\Storage\PublicKeyInterface', $this->storageMap['public_key']); + + \Yii::$container->clear('access_token'); //remove old definition + \Yii::$container->set('access_token', $this->storageMap['access_token']); + } + foreach(array_keys($this->storageMap) as $name) { $storages[$name] = \Yii::$container->get($name); } @@ -134,15 +120,12 @@ public function getServer() $this, $storages, [ + 'use_jwt_access_tokens' => $this->useJwtToken,//ADDED 'token_param_name' => $this->tokenParamName, 'access_lifetime' => $this->tokenAccessLifetime, - 'refresh_token_lifetime' => $this->tokenRefreshLifetime, - 'enforce_state' => $this->enforceState, - 'allow_implicit' => $this->allowImplicit /** add more ... */ ], - $grantTypes, - $this->responseTypes + $grantTypes ]); $this->set('server', $server); @@ -166,38 +149,6 @@ public function getResponse() return $this->get('response'); } - /** - * @param $response - */ - public function setResponse($response) - { - Yii::$app->response->setStatusCode($response->getStatusCode()); - $headers = Yii::$app->response->getHeaders(); - - foreach ($response->getHttpHeaders() as $name => $value) { - $headers->set($name, $value); - } - } - - /** - * @param $isAuthorized - * @param $userId - * @return \OAuth2\ResponseInterface - * @throws \yii\base\InvalidConfigException - */ - public function handleAuthorizeRequest($isAuthorized, $userId) - { - $response = $this->getServer()->handleAuthorizeRequest( - $this->getRequest(), - $this->getResponse(), - $isAuthorized, - $userId - ); - $this->setResponse($response); - - return $response; - } - /** * Register translations for this module * From d8c921321f1d192930d185f34ae4f089596c457d Mon Sep 17 00:00:00 2001 From: "Stefano D. Mtangoo" Date: Wed, 6 Jan 2016 01:52:47 +0300 Subject: [PATCH 41/67] Explaining how to use JWT --- README.md | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/README.md b/README.md index c731ee1..64e1263 100755 --- a/README.md +++ b/README.md @@ -151,5 +151,79 @@ With redirect response: `https://fake/cb#access_token=2YotnFZFEjr1zCsicMWpAA&state=xyz&token_type=bearer&expires_in=3600` +If you want to get Json Web Token (JWT) instead of convetional token, you will need to set `'useJwtToken' => true` in module and then define two more configurations: +`'public_key' => 'app\storage\PublicKeyStorage'` which is the class that implements [PublickKeyInterface](https://github.com/bshaffer/oauth2-server-php/blob/develop/src/OAuth2/Storage/PublicKeyInterface.php) and `'access_token' => 'app\storage\JwtAccessToken'` which implements [JwtAccessTokenInterface.php](https://github.com/bshaffer/oauth2-server-php/blob/develop/src/OAuth2/Storage/JwtAccessTokenInterface.php) + +For Oauth2 base library provides the default [access_token](https://github.com/bshaffer/oauth2-server-php/blob/develop/src/OAuth2/Storage/JwtAccessToken.php) which works great except that it tries to save the token in the database. So I decided to inherit from it and override the part that tries to save (token size is too big and crashes with VARCHAR(40) in the database. + +TL;DR, here are the sample classes +**access_token** +```php + + */ +class JwtAccessToken extends \OAuth2\Storage\JwtAccessToken +{ + public function setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope = null) + { + + } + + public function unsetAccessToken($access_token) + { + + } +} + +``` + +and **public_key** + +```php +pbk = file_get_contents('privkey.pem', true); + $this->pvk = file_get_contents('pubkey.pem', true); + } + + public function getPublicKey($client_id = null){ + return $this->pbk; + } + + public function getPrivateKey($client_id = null){ + return $this->pvk; + } + + public function getEncryptionAlgorithm($client_id = null){ + return 'HS256'; + } + +} + +``` + For more, see https://github.com/bshaffer/oauth2-server-php From 05e4d25710be68bc9d21e81a2a470b34fa05a002 Mon Sep 17 00:00:00 2001 From: Wilberto Dzul Date: Wed, 6 Jan 2016 10:57:44 -0600 Subject: [PATCH 42/67] Spanish translation of oauth2server.php --- messages/es/oauth2server.php | 54 ++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 messages/es/oauth2server.php diff --git a/messages/es/oauth2server.php b/messages/es/oauth2server.php new file mode 100644 index 0000000..0693fac --- /dev/null +++ b/messages/es/oauth2server.php @@ -0,0 +1,54 @@ + 'Una redirección URI debe ser suministrada cuando varios URI de redirección están registrados', + 'An unsupported scope was requested' => 'Se solicitó un ámbito no soportado', + 'Authorization code doesn\'t exist or is invalid for the client' => 'Código de autorización no existe o no es válido para el cliente', + 'client credentials are required' => 'credenciales del cliente son requeridas', + 'Expiration (exp) time must be a unix time stamp' => 'Tiempo de expiración (exp) debe ser una marca de tiempo Unix', + 'Expiration (exp) time must be present' => 'Tiempo de expiración (exp) debe estar presente', + 'Invalid audience (aud)' => 'Audiencia no válido (aud)', + 'Invalid issuer (iss) or subject (sub) provided' => 'No válido emisor (iss) o asunto (sub) proporcionado', + 'Invalid issuer (iss) provided' => 'Emisor (iss) no válido proporcionado', + 'Invalid refresh token' => 'Token de actualización no válido', + 'Invalid subject (sub) provided' => 'Asunto (sub) no válido proporcionado', + 'Invalid user authkey' => 'Clave de autenticación de usuario no válido', + 'Invalid username and password combination' => 'Combinación de usuario y contraseña no válido', + 'JSON Token Identifier (jti) has already been used' => 'JSON Token Identifier (jti) ya se ha utilizado', + 'JWT cannot be used before the Not Before (nbf) time' => 'JWT no se puede utilizar antes de tiempo Not Before (nbf)', + 'JWT failed signature verification' => 'JWT falló verificación de firmas', + 'JWT has expired' => 'JWT ha expirado', + 'JWT is malformed' => 'JWT tiene formato incorrecto', + 'Malformed auth header' => 'Cabecera de autenticación con formato incorrecto', + 'Malformed token (missing "expires" or "client_id")' => 'Token con formato incorrecto (falta "expires" ó "client_id")', + 'Missing parameter: "code" is required' => 'Parámetro ausente: "code" es requerido', + 'Missing parameter: "refresh_token" is required' => 'Parámetro ausente: "refresh_token" es requerido', + 'Missing parameters: "assertion" required' => 'Parámetros ausentes: "assertion" requeridos', + 'Missing parameters: "authkey" and "username" required' => 'Parámetros ausentes: "authkey" y "username" requeridos', + 'Missing parameters: "username" and "password" required' => 'Parámetros ausentes: "username" y "password" requeridos', + 'No client id supplied' => 'ID de cliente no proporcionado', + 'No redirect URI was supplied or stored' => 'URI de redirección no fue proporcionada o almacenada', + 'Not Before (nbf) time must be a unix time stamp' => 'Tiempo Not Before (nbf) debe ser una marca de tiempo Unix', + 'Only one method may be used to authenticate at a time (Auth header, GET or POST)' => 'Sólo un método se puede utilizar para autenticar a la vez (Auth header, GET ó POST)', + 'Refresh token has expired' => 'Token de actualización ha expirado', + 'The access token provided has expired' => 'El token de acceso proporcionado ha expirado', + 'The access token provided is invalid' => 'El token de acceso proporcionado no es válido', + 'The authorization code has expired' => 'El código de autorización ha expirado', + 'The client credentials are invalid' => 'Las credenciales del cliente no son válidos', + 'The client id supplied is invalid' => 'El ID de cliente proporcionado no es válida', + 'The content type for POST requests must be "application/x-www-form-urlencoded"' => 'El content type para peticiones POST debe ser "application/x-www-form-urlencoded"', + 'The grant type is unauthorized for this client_id' => 'El tipo de privilegio no está autorizado para este client_id', + 'The grant type was not specified in the request' => 'El tipo de privilegio no se especificó en la solicitud', + 'The redirect URI is mandatory and was not supplied' => 'El URI de redireccionamiento es obligatorio y no se proporcionó', + 'The redirect URI is missing or do not match' => 'El URI de redireccionamiento no se encuentró o no coincide', + 'The redirect URI must not contain a fragment' => 'El URI de redireccionamiento no debe contener una parte', + 'The redirect URI provided is missing or does not match' => 'El URI de redireccionamiento proporcionado no se encuentró o no coincide', + 'The request method must be POST when requesting an access token' => 'El método de la petición debe ser POST al solicitar un token de acceso', + 'The request requires higher privileges than provided by the access token' => 'La solicitud requiere privilegios mayores que las contempladas en el token de acceso', + 'The scope requested is invalid for this client' => 'El alcance solicitado no es válido para este cliente', + 'The scope requested is invalid for this request' => 'El alcance solicitado no es válido para esta solicitud', + 'This application requires you specify a scope parameter' => 'Esta aplicación requiere que se especifique un parámetro de alcance', + 'This client is invalid or must authenticate using a client secret' => 'Este cliente no es válido o debe autenticarse usando un client secret', + 'Unable to retrieve user information' => 'No se puede recuperar la información de usuario', + 'When putting the token in the body, the method must be POST' => 'Al poner el token en el body, el método debe ser POST', + 'you must set the user_id on the array returned by getUserDetails' => 'debe establecer el user_id en el arreglo devuelto por getUserDetails', +]; From 78051ecbe29ca99475436d4aa3886cdbd00ebda3 Mon Sep 17 00:00:00 2001 From: Aleksandr Date: Tue, 12 Jan 2016 11:20:58 +0300 Subject: [PATCH 43/67] Add 'refresh_token' to oauth_clients.grant_types --- migrations/m140501_075311_add_oauth2_server.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/migrations/m140501_075311_add_oauth2_server.php b/migrations/m140501_075311_add_oauth2_server.php index a589ba6..3f28a8b 100644 --- a/migrations/m140501_075311_add_oauth2_server.php +++ b/migrations/m140501_075311_add_oauth2_server.php @@ -109,7 +109,7 @@ public function up() // insert client data $this->batchInsert('{{%oauth_clients}}', ['client_id', 'client_secret', 'redirect_uri', 'grant_types'], [ - ['testclient', 'testpass', 'http://fake/', 'client_credentials authorization_code password implicit'], + ['testclient', 'testpass', 'http://fake/', 'client_credentials authorization_code password implicit refresh_token'], ]); $transaction->commit(); From d4c6cf49277d0dcdd0d195d599ed95430e896988 Mon Sep 17 00:00:00 2001 From: "Stefano D. Mtangoo" Date: Sun, 7 Feb 2016 21:50:46 +0300 Subject: [PATCH 44/67] Fix documentation to simplify things in JWT things - Fixed code bug in PublicKeyStorage class - The Other class is really option --- README.md | 56 ++++++++++++++----------------------------------------- 1 file changed, 14 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 64e1263..bfacdfe 100755 --- a/README.md +++ b/README.md @@ -22,6 +22,13 @@ or add to the require section of your composer.json. +To use the latest features (Like JWT tokens), you need to use 2.0.1 branch. +Edit your compose.json and add + +```json +"filsh/yii2-oauth2-server": "2.0.1.x-dev" +``` + To use this extension, simply add the following code in your application configuration: ```php @@ -150,37 +157,11 @@ Request example: With redirect response: `https://fake/cb#access_token=2YotnFZFEjr1zCsicMWpAA&state=xyz&token_type=bearer&expires_in=3600` - +### JWT Tokens (2.0.1 branch only) If you want to get Json Web Token (JWT) instead of convetional token, you will need to set `'useJwtToken' => true` in module and then define two more configurations: -`'public_key' => 'app\storage\PublicKeyStorage'` which is the class that implements [PublickKeyInterface](https://github.com/bshaffer/oauth2-server-php/blob/develop/src/OAuth2/Storage/PublicKeyInterface.php) and `'access_token' => 'app\storage\JwtAccessToken'` which implements [JwtAccessTokenInterface.php](https://github.com/bshaffer/oauth2-server-php/blob/develop/src/OAuth2/Storage/JwtAccessTokenInterface.php) +`'public_key' => 'app\storage\PublicKeyStorage'` which is the class that implements [PublickKeyInterface](https://github.com/bshaffer/oauth2-server-php/blob/develop/src/OAuth2/Storage/PublicKeyInterface.php) and `'access_token' => 'OAuth2\Storage\JwtAccessToken'` which implements [JwtAccessTokenInterface.php](https://github.com/bshaffer/oauth2-server-php/blob/develop/src/OAuth2/Storage/JwtAccessTokenInterface.php) -For Oauth2 base library provides the default [access_token](https://github.com/bshaffer/oauth2-server-php/blob/develop/src/OAuth2/Storage/JwtAccessToken.php) which works great except that it tries to save the token in the database. So I decided to inherit from it and override the part that tries to save (token size is too big and crashes with VARCHAR(40) in the database. - -TL;DR, here are the sample classes -**access_token** -```php - - */ -class JwtAccessToken extends \OAuth2\Storage\JwtAccessToken -{ - public function setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope = null) - { - - } - - public function unsetAccessToken($access_token) - { - - } -} - -``` +For Oauth2 base library provides the default [access_token](https://github.com/bshaffer/oauth2-server-php/blob/develop/src/OAuth2/Storage/JwtAccessToken.php) which works great except. Just use it and everything will be fine. and **public_key** @@ -196,17 +177,8 @@ class PublicKeyStorage implements \OAuth2\Storage\PublicKeyInterface{ public function __construct() { - //files should be in same directory as this file - //keys can be generated using OpenSSL tool with command: - /* - private key: - openssl genrsa -out privkey.pem 2048 - - public key: - openssl rsa -in privkey.pem -pubout -out pubkey.pem - */ - $this->pbk = file_get_contents('privkey.pem', true); - $this->pvk = file_get_contents('pubkey.pem', true); + $this->pvk = file_get_contents('privkey.pem', true); + $this->pbk = file_get_contents('pubkey.pem', true); } public function getPublicKey($client_id = null){ @@ -218,12 +190,12 @@ class PublicKeyStorage implements \OAuth2\Storage\PublicKeyInterface{ } public function getEncryptionAlgorithm($client_id = null){ - return 'HS256'; + return 'RS256'; } } -``` +``` For more, see https://github.com/bshaffer/oauth2-server-php From 0cb8034eb65d6bafb55f4fd988948097f77f56a7 Mon Sep 17 00:00:00 2001 From: Andrii Vasyliev Date: Wed, 17 Feb 2016 12:44:29 +0000 Subject: [PATCH 45/67] added `Module::$options` in a compatible fashion --- Module.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Module.php b/Module.php index 375a36d..2573aab 100755 --- a/Module.php +++ b/Module.php @@ -48,6 +48,11 @@ class Module extends \yii\base\Module */ public $grantTypes = []; + /** + * @var array server options + */ + public $options = []; + /** * @var string name of access token parameter */ @@ -119,12 +124,12 @@ public function getServer() $server = \Yii::$container->get(Server::className(), [ $this, $storages, - [ + array_merge(array_filter([ 'use_jwt_access_tokens' => $this->useJwtToken,//ADDED 'token_param_name' => $this->tokenParamName, 'access_lifetime' => $this->tokenAccessLifetime, /** add more ... */ - ], + ]), $this->options), $grantTypes ]); From d74fac470775f864b9b8e838cfbcfdd9ee5507cb Mon Sep 17 00:00:00 2001 From: lisps Date: Mon, 4 Apr 2016 15:48:11 +0200 Subject: [PATCH 46/67] add revoke request --- controllers/DefaultController.php | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/controllers/DefaultController.php b/controllers/DefaultController.php index 255850d..c8581b4 100644 --- a/controllers/DefaultController.php +++ b/controllers/DefaultController.php @@ -28,4 +28,13 @@ public function actionToken() return $response->getParameters(); } -} \ No newline at end of file + + public function actionRevoke() + { + $server = $this->module->getServer(); + $request = $this->module->getRequest(); + $response = $server->handleRevokeRequest($request); + + return $response->getParameters(); + } +} From 60a555b6ef9bd193c7ee210ad51f53f41c62f78f Mon Sep 17 00:00:00 2001 From: lisps Date: Thu, 7 Apr 2016 17:20:18 +0200 Subject: [PATCH 47/67] add revoke request action --- controllers/RestController.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/controllers/RestController.php b/controllers/RestController.php index a2d6770..d953ae7 100755 --- a/controllers/RestController.php +++ b/controllers/RestController.php @@ -26,4 +26,11 @@ public function actionToken() $response = $this->module->getServer()->handleTokenRequest(); return $response->getParameters(); } + + public function actionRevoke() + { + /** @var $response \OAuth2\Response */ + $response = $this->module->getServer()->handleRevokeRequest(); + return $response->getParameters(); + } } From 6af49834dea3767d638a4d646b8864fc8267e794 Mon Sep 17 00:00:00 2001 From: lisps Date: Thu, 7 Apr 2016 17:22:14 +0200 Subject: [PATCH 48/67] add revoke request to Server.php --- Server.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Server.php b/Server.php index df41d4a..718b0eb 100644 --- a/Server.php +++ b/Server.php @@ -38,6 +38,14 @@ public function handleTokenRequest(\OAuth2\RequestInterface $request = null, \OA } return parent::handleTokenRequest($request, $response); } + + public function handleRevokeRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null) + { + if($request === null) { + $request = $this->module->getRequest(); + } + return parent::handleRevokeRequest($request, $response); + } public function handleAuthorizeRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null, $isAuthorized = false, $userId = null) { From 594a87bcc2ca86d065501263bced6bc53e951b10 Mon Sep 17 00:00:00 2001 From: Damian Dennis Date: Mon, 13 Jun 2016 10:20:56 +1000 Subject: [PATCH 49/67] added fix for optional oauth. --- filters/ErrorToExceptionFilter.php | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/filters/ErrorToExceptionFilter.php b/filters/ErrorToExceptionFilter.php index 9f6f4c7..e5781cc 100644 --- a/filters/ErrorToExceptionFilter.php +++ b/filters/ErrorToExceptionFilter.php @@ -20,19 +20,17 @@ public function events() public function afterAction($event) { $response = Yii::$app->getModule('oauth2')->getServer()->getResponse(); - + $optional = $event->action->controller->getBehavior('authenticator')->optional; + $currentAction = $event->action->id; $isValid = true; - if($response !== null) { - $isValid = $response->isInformational() || $response->isSuccessful() || $response->isRedirection(); - } - if(!$isValid) { - $status = $response->getStatusCode(); - // TODO: необходимо также пробрасывать error_uri - $message = Yii::t('oauth2server', $response->getParameter('error_description')); - if($message === null) { - $message = Yii::t('yii', 'An internal server error occurred.'); + if (!in_array($currentAction, $optional)) { + if ($response !== null) { + $isValid = $response->isInformational() || $response->isSuccessful() || $response->isRedirection(); + } + if (!$isValid) { + throw new HttpException($response->getStatusCode(), $this->getErrorMessage($response), + $response->getParameter('error_uri')); } - throw new \yii\web\HttpException($status, $message); } } } From 54a1d41a66b42d23a9ea941c9f946baf97a27b26 Mon Sep 17 00:00:00 2001 From: Ruslan Bes Date: Tue, 12 Jul 2016 11:53:25 +0200 Subject: [PATCH 50/67] Fix for migration error [Issue 45] https://github.com/Filsh/yii2-oauth2-server/issues/45 Renamed primaryKey() -> primaryKeyDefinition() to avoid naming collision with \yii\db\SchemaBuilderTrait::primaryKey() also renamed foreignKey() -> foreignkeyDefinition() for consistency --- .../m140501_075311_add_oauth2_server.php | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/migrations/m140501_075311_add_oauth2_server.php b/migrations/m140501_075311_add_oauth2_server.php index a34fccb..3f1fd1d 100755 --- a/migrations/m140501_075311_add_oauth2_server.php +++ b/migrations/m140501_075311_add_oauth2_server.php @@ -9,11 +9,11 @@ public function mysql($yes,$no='') { return $this->db->driverName === 'mysql' ? $yes : $no; } - public function primaryKey($columns) { + public function primaryKeyDefinition($columns) { return 'PRIMARY KEY (' . $this->db->getQueryBuilder()->buildColumns($columns) . ')'; } - public function foreignKey($columns,$refTable,$refColumns,$onDelete = null,$onUpdate = null) { + public function foreignKeyDefinition($columns,$refTable,$refColumns,$onDelete = null,$onUpdate = null) { $builder = $this->db->getQueryBuilder(); $sql = ' FOREIGN KEY (' . $builder->buildColumns($columns) . ')' . ' REFERENCES ' . $this->db->quoteTableName($refTable) @@ -46,7 +46,7 @@ public function up() 'grant_types' => Schema::TYPE_STRING . '(100) NOT NULL', 'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', 'user_id' => Schema::TYPE_INTEGER . ' DEFAULT NULL', - $this->primaryKey('client_id'), + $this->primaryKeyDefinition('client_id'), ], $tableOptions); $this->createTable('{{%oauth_access_tokens}}', [ @@ -55,8 +55,8 @@ public function up() 'user_id' => Schema::TYPE_INTEGER . ' DEFAULT NULL', 'expires' => Schema::TYPE_TIMESTAMP . " NOT NULL DEFAULT $now $on_update_now", 'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', - $this->primaryKey('access_token'), - $this->foreignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), + $this->primaryKeyDefinition('access_token'), + $this->foreignKeyDefinition('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), ], $tableOptions); $this->createTable('{{%oauth_refresh_tokens}}', [ @@ -65,8 +65,8 @@ public function up() 'user_id' => Schema::TYPE_INTEGER . ' DEFAULT NULL', 'expires' => Schema::TYPE_TIMESTAMP . " NOT NULL DEFAULT $now $on_update_now", 'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', - $this->primaryKey('refresh_token'), - $this->foreignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), + $this->primaryKeyDefinition('refresh_token'), + $this->foreignKeyDefinition('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), ], $tableOptions); $this->createTable('{{%oauth_authorization_codes}}', [ @@ -76,8 +76,8 @@ public function up() 'redirect_uri' => Schema::TYPE_STRING . '(1000) NOT NULL', 'expires' => Schema::TYPE_TIMESTAMP . " NOT NULL DEFAULT $now $on_update_now", 'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', - $this->primaryKey('authorization_code'), - $this->foreignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), + $this->primaryKeyDefinition('authorization_code'), + $this->foreignKeyDefinition('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), ], $tableOptions); $this->createTable('{{%oauth_scopes}}', [ @@ -89,7 +89,7 @@ public function up() 'client_id' => Schema::TYPE_STRING . '(32) NOT NULL', 'subject' => Schema::TYPE_STRING . '(80) DEFAULT NULL', 'public_key' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', - $this->primaryKey('client_id'), + $this->primaryKeyDefinition('client_id'), ], $tableOptions); $this->createTable('{{%oauth_users}}', [ @@ -97,7 +97,7 @@ public function up() 'password' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', 'first_name' => Schema::TYPE_STRING . '(255) DEFAULT NULL', 'last_name' => Schema::TYPE_STRING . '(255) DEFAULT NULL', - $this->primaryKey('username'), + $this->primaryKeyDefinition('username'), ], $tableOptions); $this->createTable('{{%oauth_public_keys}}', [ From 12544567b9247cc6e01800ca9462aae91a91647d Mon Sep 17 00:00:00 2001 From: Anton Karakulov Date: Fri, 14 Oct 2016 14:06:09 +0300 Subject: [PATCH 51/67] Fix #109 issue Since yii2 2.0.6 appear method name conflict. Tested on 2.0.9. To fix just rename method in migration --- .../m140501_075311_add_oauth2_server.php | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/migrations/m140501_075311_add_oauth2_server.php b/migrations/m140501_075311_add_oauth2_server.php index 3f28a8b..fb259bf 100644 --- a/migrations/m140501_075311_add_oauth2_server.php +++ b/migrations/m140501_075311_add_oauth2_server.php @@ -9,11 +9,11 @@ public function mysql($yes,$no='') { return $this->db->driverName === 'mysql' ? $yes : $no; } - public function buildPrimaryKey($columns = null) { + public function setPrimaryKey($columns) { return 'PRIMARY KEY (' . $this->db->getQueryBuilder()->buildColumns($columns) . ')'; } - public function buildForeignKey($columns,$refTable,$refColumns,$onDelete = null,$onUpdate = null) { + public function foreignKey($columns,$refTable,$refColumns,$onDelete = null,$onUpdate = null) { $builder = $this->db->getQueryBuilder(); $sql = ' FOREIGN KEY (' . $builder->buildColumns($columns) . ')' . ' REFERENCES ' . $this->db->quoteTableName($refTable) @@ -46,7 +46,7 @@ public function up() 'grant_types' => Schema::TYPE_STRING . '(100) NOT NULL', 'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', 'user_id' => Schema::TYPE_INTEGER . ' DEFAULT NULL', - $this->buildPrimaryKey('client_id'), + $this->setPrimaryKey('client_id'), ], $tableOptions); $this->createTable('{{%oauth_access_tokens}}', [ @@ -55,8 +55,8 @@ public function up() 'user_id' => Schema::TYPE_INTEGER . ' DEFAULT NULL', 'expires' => Schema::TYPE_TIMESTAMP . " NOT NULL DEFAULT $now $on_update_now", 'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', - $this->buildPrimaryKey('access_token'), - $this->buildForeignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), + $this->setPrimaryKey('access_token'), + $this->foreignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), ], $tableOptions); $this->createTable('{{%oauth_refresh_tokens}}', [ @@ -65,8 +65,8 @@ public function up() 'user_id' => Schema::TYPE_INTEGER . ' DEFAULT NULL', 'expires' => Schema::TYPE_TIMESTAMP . " NOT NULL DEFAULT $now $on_update_now", 'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', - $this->buildPrimaryKey('refresh_token'), - $this->buildForeignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), + $this->setPrimaryKey('refresh_token'), + $this->foreignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), ], $tableOptions); $this->createTable('{{%oauth_authorization_codes}}', [ @@ -76,8 +76,8 @@ public function up() 'redirect_uri' => Schema::TYPE_STRING . '(1000) NOT NULL', 'expires' => Schema::TYPE_TIMESTAMP . " NOT NULL DEFAULT $now $on_update_now", 'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', - $this->buildPrimaryKey('authorization_code'), - $this->buildForeignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), + $this->setPrimaryKey('authorization_code'), + $this->foreignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), ], $tableOptions); $this->createTable('{{%oauth_scopes}}', [ @@ -89,7 +89,7 @@ public function up() 'client_id' => Schema::TYPE_STRING . '(32) NOT NULL', 'subject' => Schema::TYPE_STRING . '(80) DEFAULT NULL', 'public_key' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', - $this->buildPrimaryKey('client_id'), + $this->setPrimaryKey('client_id'), ], $tableOptions); $this->createTable('{{%oauth_users}}', [ @@ -97,7 +97,7 @@ public function up() 'password' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', 'first_name' => Schema::TYPE_STRING . '(255) DEFAULT NULL', 'last_name' => Schema::TYPE_STRING . '(255) DEFAULT NULL', - $this->buildPrimaryKey('username'), + $this->setPrimaryKey('username'), ], $tableOptions); $this->createTable('{{%oauth_public_keys}}', [ @@ -109,7 +109,7 @@ public function up() // insert client data $this->batchInsert('{{%oauth_clients}}', ['client_id', 'client_secret', 'redirect_uri', 'grant_types'], [ - ['testclient', 'testpass', 'http://fake/', 'client_credentials authorization_code password implicit refresh_token'], + ['testclient', 'testpass', 'http://fake/', 'client_credentials authorization_code password implicit'], ]); $transaction->commit(); From ba7c7f0bf622114d1842db5a80103486cb976925 Mon Sep 17 00:00:00 2001 From: Justin Cherniak Date: Mon, 7 Nov 2016 19:54:06 -0800 Subject: [PATCH 52/67] Add OpenID Connect UserInfo end-point to REST controller --- Server.php | 9 +++++++++ controllers/RestController.php | 6 ++++++ 2 files changed, 15 insertions(+) diff --git a/Server.php b/Server.php index 718b0eb..fbd158b 100644 --- a/Server.php +++ b/Server.php @@ -58,4 +58,13 @@ public function handleAuthorizeRequest(\OAuth2\RequestInterface $request = null, return parent::handleAuthorizeRequest($request, $response, $isAuthorized, $userId); } + + public function handleUserInfoRequest(\OAuth2\RequestInterface $request = null, \OAuth2\ResponseInterface $response = null) + { + if($request === null) { + $request = $this->module->getRequest(); + } + return parent::handleUserInfoRequest($request, $response); + } + } diff --git a/controllers/RestController.php b/controllers/RestController.php index d953ae7..8e88eda 100755 --- a/controllers/RestController.php +++ b/controllers/RestController.php @@ -33,4 +33,10 @@ public function actionRevoke() $response = $this->module->getServer()->handleRevokeRequest(); return $response->getParameters(); } + + public function actionUserInfo() + { + $response = $this->module->getServer()->handleUserInfoRequest(); + return $response->getParameters(); + } } From a7b736524756fa7b7628757cebb9cfcab24536da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E4=BF=8A=E4=BC=9F?= Date: Wed, 23 Nov 2016 14:11:38 +0800 Subject: [PATCH 53/67] Chinese language support --- messages/zh-CN/oauth2server.php | 54 +++++++++++++++++++++++++++++++++ messages/zh-TW/oauth2server.php | 54 +++++++++++++++++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100644 messages/zh-CN/oauth2server.php create mode 100644 messages/zh-TW/oauth2server.php diff --git a/messages/zh-CN/oauth2server.php b/messages/zh-CN/oauth2server.php new file mode 100644 index 0000000..b1e3622 --- /dev/null +++ b/messages/zh-CN/oauth2server.php @@ -0,0 +1,54 @@ + '当注册多个重定向URI时,必须提供重定向URI', + 'An unsupported scope was requested' => '所请求的权限范围不支持', + 'Authorization code doesn\'t exist or is invalid for the client' => '授权代码不存在或对客户端无效', + 'client credentials are required' => '缺少客户端凭据', + 'Expiration (exp) time must be a unix time stamp' => '过期时间(exp)必须是unix时间戳', + 'Expiration (exp) time must be present' => '过期时间(exp)必须存在', + 'Invalid audience (aud)' => '无效观众(aud)', + 'Invalid issuer (iss) or subject (sub) provided' => '所提供的签发者(iss)或接收者(sub)无效', + 'Invalid issuer (iss) provided' => '所提供的签发者(iss)无效', + 'Invalid refresh token' => '刷新令牌无效', + 'Invalid subject (sub) provided' => '所提供的接收者(sub)无效', + 'Invalid user authkey' => '用户验证密钥无效', + 'Invalid username and password combination' => '用户名或密码无效', + 'JSON Token Identifier (jti) has already been used' => 'JSON令牌标识符(jti)已被使用', + 'JWT cannot be used before the Not Before (nbf) time' => 'JWT不能在不早于(nbf)时间之前使用', + 'JWT failed signature verification' => 'JWT无法进行签名验证', + 'JWT has expired' => 'JWT已过期', + 'JWT is malformed' => 'JWT格式错误', + 'Malformed auth header' => '验证标题格式错误', + 'Malformed token (missing "expires" or "client_id")' => '格式错误的令牌(缺少“expires”或“client_id”)', + 'Missing parameter: "code" is required' => '缺少参数:“code”必须', + 'Missing parameter: "refresh_token" is required' => '缺少参数:“refresh_token”必须', + 'Missing parameters: "assertion" required' => '缺少参数:“assertion”必须', + 'Missing parameters: "authkey" and "username" required' => '缺少参数:"authkey" 和 "username"必须', + 'Missing parameters: "username" and "password" required' => '缺少参数:"username" 和 "password" 必须', + 'No client id supplied' => '未提供客户端ID', + 'No redirect URI was supplied or stored' => '未提供或存储重定向URI', + 'Not Before (nbf) time must be a unix time stamp' => '不早于(nbf)时间必须是unix时间戳', + 'Only one method may be used to authenticate at a time (Auth header, GET or POST)' => '一次只能使用一种方法进行身份验证(Auth标头,GET或POST)', + 'Refresh token has expired' => '刷新令牌已过期', + 'The access token provided has expired' => '所提供的访问令牌已过期', + 'The access token provided is invalid' => '所提供的访问令牌无效', + 'The authorization code has expired' => '授权码已过期', + 'The client credentials are invalid' => '客户端凭据无效', + 'The client id supplied is invalid' => '所提供的客户端ID无效', + 'The content type for POST requests must be "application/x-www-form-urlencoded"' => 'POST请求的内容类型必须为“application / x-www-form-urlencoded”', + 'The grant type is unauthorized for this client_id' => '授权类型未授权此client_id', + 'The grant type was not specified in the request' => '请求中未指定授权类型', + 'The redirect URI is mandatory and was not supplied' => '重定向URI是必需的,未提供', + 'The redirect URI is missing or do not match' => '重定向URI丢失或不匹配', + 'The redirect URI must not contain a fragment' => '重定向URI不能包含片段', + 'The redirect URI provided is missing or does not match' => '提供的重定向URI丢失或不匹配', + 'The request method must be POST when requesting an access token' => '请求方法必须在POST时请求访问令牌', + 'The request requires higher privileges than provided by the access token' => '该请求所需要的权限高于访问令牌提供的权限', + 'The scope requested is invalid for this client' => '请求的权限范围对此客户端无效', + 'The scope requested is invalid for this request' => '请求的权限范围对此请求无效', + 'This application requires you specify a scope parameter' => '此应用程序需要您指定范围参数', + 'This client is invalid or must authenticate using a client secret' => '此客户端无效或必须使用客户端密钥进行身份验证', + 'Unable to retrieve user information' => '无法检索用户信息', + 'When putting the token in the body, the method must be POST' => '将令牌放在正文中时,方法必须是POST', + 'you must set the user_id on the array returned by getUserDetails' => '您必须在getUserDetails返回的数组上设置user_id', +]; diff --git a/messages/zh-TW/oauth2server.php b/messages/zh-TW/oauth2server.php new file mode 100644 index 0000000..20d3c3b --- /dev/null +++ b/messages/zh-TW/oauth2server.php @@ -0,0 +1,54 @@ + '當註冊多個重定向URI時,必須提供重定向URI', + 'An unsupported scope was requested' => '所請求的權限範圍不支持', + 'Authorization code doesn\'t exist or is invalid for the client' => '授權代碼不存在或對客戶端無效', + 'client credentials are required' => '缺少客戶端憑據', + 'Expiration (exp) time must be a unix time stamp' => '過期時間(exp)必須是unix時間戳', + 'Expiration (exp) time must be present' => '過期時間(exp)必須存在', + 'Invalid audience (aud)' => '無效觀眾(aud)', + 'Invalid issuer (iss) or subject (sub) provided' => '所提供的簽發者(iss)或接收人(sub)無效', + 'Invalid issuer (iss) provided' => '所提供的簽發者(iss)無效', + 'Invalid refresh token' => '刷新令牌無效', + 'Invalid subject (sub) provided' => '所提供的接收人(sub)無效', + 'Invalid user authkey' => '用戶驗證密鑰無效', + 'Invalid username and password combination' => '用戶名或密碼無效', + 'JSON Token Identifier (jti) has already been used' => 'JSON令牌標識符(jti)已被使用', + 'JWT cannot be used before the Not Before (nbf) time' => 'JWT不能在不早於(nbf)時間之前使用', + 'JWT failed signature verification' => 'JWT無法進行簽名驗證', + 'JWT has expired' => 'JWT已過期', + 'JWT is malformed' => 'JWT格式錯誤', + 'Malformed auth header' => '驗證標題格式錯誤', + 'Malformed token (missing "expires" or "client_id")' => '格式错误的令牌(缺少“expires”或“client_id”)', + 'Missing parameter: "code" is required' => '缺少參數:“code”必須', + 'Missing parameter: "refresh_token" is required' => '缺少參數:“refresh_token”必須', + 'Missing parameters: "assertion" required' => '缺少參數:“assertion”必須', + 'Missing parameters: "authkey" and "username" required' => '缺少參數: "authkey" 和 "username" 必須', + 'Missing parameters: "username" and "password" required' => '缺少參數: "username" 和 "password" 必須', + 'No client id supplied' => '未提供客戶端ID', + 'No redirect URI was supplied or stored' => '未提供或存儲重定向URI', + 'Not Before (nbf) time must be a unix time stamp' => '不早於(nbf)時間必須是unix時間戳', + 'Only one method may be used to authenticate at a time (Auth header, GET or POST)' => '一次只能使用一種方法進行身份驗證(Auth標頭,GET或POST)', + 'Refresh token has expired' => '刷新令牌已過期', + 'The access token provided has expired' => '所提供的訪問令牌已過期', + 'The access token provided is invalid' => '授權碼已過期', + 'The authorization code has expired' => '客戶端憑據無效', + 'The client credentials are invalid' => '客戶端憑據無效', + 'The client id supplied is invalid' => '提供的客戶端ID無效', + 'The content type for POST requests must be "application/x-www-form-urlencoded"' => 'POST請求的內容類型必須為“application / x-www-form-urlencoded”', + 'The grant type is unauthorized for this client_id' => '授權類型未授權此client_id', + 'The grant type was not specified in the request' => '請求中未指定授權類型', + 'The redirect URI is mandatory and was not supplied' => '重定向URI是必需的,未提供', + 'The redirect URI is missing or do not match' => '重定向URI丟失或不匹配', + 'The redirect URI must not contain a fragment' => '重定向URI不能包含片段', + 'The redirect URI provided is missing or does not match' => '提供的重定向URI丟失或不匹配', + 'The request method must be POST when requesting an access token' => '請求方法必須在POST時請求訪問令牌', + 'The request requires higher privileges than provided by the access token' => '該請求所需要的權限高於訪問令牌提供的權限', + 'The scope requested is invalid for this client' => '請求的權限範圍對此客戶端無效', + 'The scope requested is invalid for this request' => '請求的權限範圍對此請求無效', + 'This application requires you specify a scope parameter' => '此應用程序需要您指定範圍參數', + 'This client is invalid or must authenticate using a client secret' => '此客戶端無效或必須使用客戶端密鑰進行身份驗證', + 'Unable to retrieve user information' => '無法檢索用戶信息', + 'When putting the token in the body, the method must be POST' => '將令牌放在正文中時,方法必須是POST', + 'you must set the user_id on the array returned by getUserDetails' => '您必須在getUserDetails返回的數組上設置user_id', +]; From 21d7b1bd28ba75728b5e6cce3ede0a01ca7a72af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E4=BF=8A=E4=BC=9F?= Date: Wed, 23 Nov 2016 14:19:42 +0800 Subject: [PATCH 54/67] =?UTF-8?q?update:=E6=A0=BC=E5=BC=8F=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- messages/zh-CN/oauth2server.php | 2 +- messages/zh-TW/oauth2server.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/messages/zh-CN/oauth2server.php b/messages/zh-CN/oauth2server.php index b1e3622..9cb4763 100644 --- a/messages/zh-CN/oauth2server.php +++ b/messages/zh-CN/oauth2server.php @@ -35,7 +35,7 @@ 'The authorization code has expired' => '授权码已过期', 'The client credentials are invalid' => '客户端凭据无效', 'The client id supplied is invalid' => '所提供的客户端ID无效', - 'The content type for POST requests must be "application/x-www-form-urlencoded"' => 'POST请求的内容类型必须为“application / x-www-form-urlencoded”', + 'The content type for POST requests must be "application/x-www-form-urlencoded"' => 'POST请求的内容类型必须为“application/x-www-form-urlencoded”', 'The grant type is unauthorized for this client_id' => '授权类型未授权此client_id', 'The grant type was not specified in the request' => '请求中未指定授权类型', 'The redirect URI is mandatory and was not supplied' => '重定向URI是必需的,未提供', diff --git a/messages/zh-TW/oauth2server.php b/messages/zh-TW/oauth2server.php index 20d3c3b..a0d6b23 100644 --- a/messages/zh-TW/oauth2server.php +++ b/messages/zh-TW/oauth2server.php @@ -35,7 +35,7 @@ 'The authorization code has expired' => '客戶端憑據無效', 'The client credentials are invalid' => '客戶端憑據無效', 'The client id supplied is invalid' => '提供的客戶端ID無效', - 'The content type for POST requests must be "application/x-www-form-urlencoded"' => 'POST請求的內容類型必須為“application / x-www-form-urlencoded”', + 'The content type for POST requests must be "application/x-www-form-urlencoded"' => 'POST請求的內容類型必須為“application/x-www-form-urlencoded”', 'The grant type is unauthorized for this client_id' => '授權類型未授權此client_id', 'The grant type was not specified in the request' => '請求中未指定授權類型', 'The redirect URI is mandatory and was not supplied' => '重定向URI是必需的,未提供', From a6a092b0571d7cac284bd3f3652f822f0f7d8f2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E4=BF=8A=E4=BC=9F?= Date: Wed, 23 Nov 2016 14:21:48 +0800 Subject: [PATCH 55/67] remove duplicate rows --- messages/en/oauth2server.php | 1 - 1 file changed, 1 deletion(-) diff --git a/messages/en/oauth2server.php b/messages/en/oauth2server.php index 2786aa6..11aab5e 100644 --- a/messages/en/oauth2server.php +++ b/messages/en/oauth2server.php @@ -49,7 +49,6 @@ 'This application requires you specify a scope parameter' => 'This application requires you specify a scope parameter', 'This client is invalid or must authenticate using a client secret' => 'This client is invalid or must authenticate using a client secret', 'Unable to retrieve user information' => 'Unable to retrieve user information', - 'Unable to retrieve user information' => 'Unable to retrieve user information', 'When putting the token in the body, the method must be POST' => 'When putting the token in the body, the method must be POST', 'you must set the user_id on the array returned by getUserDetails' => 'you must set the user_id on the array returned by getUserDetails', ]; From 061894f6000d6b9fa5cfa8c8f2bf255d17c9268d Mon Sep 17 00:00:00 2001 From: Exsertin Date: Tue, 9 Oct 2018 10:53:56 +0300 Subject: [PATCH 56/67] PHP 7 Compatibility: renamed method 'primaryKey' on 'primaryKeys' --- migrations/m140501_075311_add_oauth2_server.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/migrations/m140501_075311_add_oauth2_server.php b/migrations/m140501_075311_add_oauth2_server.php index fb259bf..68548fe 100644 --- a/migrations/m140501_075311_add_oauth2_server.php +++ b/migrations/m140501_075311_add_oauth2_server.php @@ -9,7 +9,7 @@ public function mysql($yes,$no='') { return $this->db->driverName === 'mysql' ? $yes : $no; } - public function setPrimaryKey($columns) { + public function primaryKeys($columns) { return 'PRIMARY KEY (' . $this->db->getQueryBuilder()->buildColumns($columns) . ')'; } @@ -46,7 +46,7 @@ public function up() 'grant_types' => Schema::TYPE_STRING . '(100) NOT NULL', 'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', 'user_id' => Schema::TYPE_INTEGER . ' DEFAULT NULL', - $this->setPrimaryKey('client_id'), + $this->primaryKeys('client_id'), ], $tableOptions); $this->createTable('{{%oauth_access_tokens}}', [ @@ -55,7 +55,7 @@ public function up() 'user_id' => Schema::TYPE_INTEGER . ' DEFAULT NULL', 'expires' => Schema::TYPE_TIMESTAMP . " NOT NULL DEFAULT $now $on_update_now", 'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', - $this->setPrimaryKey('access_token'), + $this->primaryKeys('access_token'), $this->foreignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), ], $tableOptions); @@ -65,7 +65,7 @@ public function up() 'user_id' => Schema::TYPE_INTEGER . ' DEFAULT NULL', 'expires' => Schema::TYPE_TIMESTAMP . " NOT NULL DEFAULT $now $on_update_now", 'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', - $this->setPrimaryKey('refresh_token'), + $this->primaryKeys('refresh_token'), $this->foreignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), ], $tableOptions); @@ -76,7 +76,7 @@ public function up() 'redirect_uri' => Schema::TYPE_STRING . '(1000) NOT NULL', 'expires' => Schema::TYPE_TIMESTAMP . " NOT NULL DEFAULT $now $on_update_now", 'scope' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', - $this->setPrimaryKey('authorization_code'), + $this->primaryKeys('authorization_code'), $this->foreignKey('client_id','{{%oauth_clients}}','client_id','CASCADE','CASCADE'), ], $tableOptions); @@ -89,7 +89,7 @@ public function up() 'client_id' => Schema::TYPE_STRING . '(32) NOT NULL', 'subject' => Schema::TYPE_STRING . '(80) DEFAULT NULL', 'public_key' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', - $this->setPrimaryKey('client_id'), + $this->primaryKeys('client_id'), ], $tableOptions); $this->createTable('{{%oauth_users}}', [ @@ -97,7 +97,7 @@ public function up() 'password' => Schema::TYPE_STRING . '(2000) DEFAULT NULL', 'first_name' => Schema::TYPE_STRING . '(255) DEFAULT NULL', 'last_name' => Schema::TYPE_STRING . '(255) DEFAULT NULL', - $this->setPrimaryKey('username'), + $this->primaryKeys('username'), ], $tableOptions); $this->createTable('{{%oauth_public_keys}}', [ From 1a2db88f99d8ae4c49e0682c9315b3312ce22302 Mon Sep 17 00:00:00 2001 From: Vardan Pogosian Date: Mon, 3 Aug 2020 09:16:56 +0300 Subject: [PATCH 57/67] fix: updated README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bfacdfe..77d17e7 100755 --- a/README.md +++ b/README.md @@ -157,8 +157,8 @@ Request example: With redirect response: `https://fake/cb#access_token=2YotnFZFEjr1zCsicMWpAA&state=xyz&token_type=bearer&expires_in=3600` -### JWT Tokens (2.0.1 branch only) -If you want to get Json Web Token (JWT) instead of convetional token, you will need to set `'useJwtToken' => true` in module and then define two more configurations: +### JWT Tokens +If you want to get Json Web Token (JWT) instead of conventional token, you will need to set `'useJwtToken' => true` in module and then define two more configurations: `'public_key' => 'app\storage\PublicKeyStorage'` which is the class that implements [PublickKeyInterface](https://github.com/bshaffer/oauth2-server-php/blob/develop/src/OAuth2/Storage/PublicKeyInterface.php) and `'access_token' => 'OAuth2\Storage\JwtAccessToken'` which implements [JwtAccessTokenInterface.php](https://github.com/bshaffer/oauth2-server-php/blob/develop/src/OAuth2/Storage/JwtAccessTokenInterface.php) For Oauth2 base library provides the default [access_token](https://github.com/bshaffer/oauth2-server-php/blob/develop/src/OAuth2/Storage/JwtAccessToken.php) which works great except. Just use it and everything will be fine. From 51d1db97b05d672be51f7dbd9a0608a99eb9ad3e Mon Sep 17 00:00:00 2001 From: Vardan Pogosian Date: Mon, 3 Aug 2020 14:21:23 +0300 Subject: [PATCH 58/67] feat: added MacOS ignores --- .gitignore | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/.gitignore b/.gitignore index 3542b8e..420f071 100755 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,35 @@ + +### macOS.gitignore + +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + + # Folders to ignore vendor From 6723afd3b394691a49af20703700cfa8ac8cb3e4 Mon Sep 17 00:00:00 2001 From: Vardan Pogosian Date: Mon, 3 Aug 2020 14:22:18 +0300 Subject: [PATCH 59/67] feat: added Docker configs for development env --- Dockerfile.dev | 7 +++++++ commands/empty | 0 docker-compose.yml | 12 ++++++++++++ 3 files changed, 19 insertions(+) create mode 100644 Dockerfile.dev delete mode 100644 commands/empty create mode 100644 docker-compose.yml diff --git a/Dockerfile.dev b/Dockerfile.dev new file mode 100644 index 0000000..d52ad9e --- /dev/null +++ b/Dockerfile.dev @@ -0,0 +1,7 @@ +FROM vardan/ubuntu:php-7.2 + +ENV PHP_DOCUMENT_ROOT /app + +ENV WORK_DIR ${PHP_DOCUMENT_ROOT} + +WORKDIR ${WORK_DIR} \ No newline at end of file diff --git a/commands/empty b/commands/empty deleted file mode 100644 index e69de29..0000000 diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..775f20f --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,12 @@ +version: "3" +services: + php: + image: filsh/yii2-oauth2-server + build: + dockerfile: Dockerfile.dev + context: . + volumes: + - ".:/app" + +networks: + default: \ No newline at end of file From 013c21e03fe427b27c298cc3a21dc4a5276d2737 Mon Sep 17 00:00:00 2001 From: Vardan Pogosian Date: Mon, 3 Aug 2020 14:22:47 +0300 Subject: [PATCH 60/67] fix: updated composer.json --- composer.json | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index 7052c37..995e522 100755 --- a/composer.json +++ b/composer.json @@ -13,21 +13,25 @@ { "name": "Igor Maliy", "email": "imaliy.filsh@gmail.com" + }, + { + "name": "Vardan Pogosian", + "email": "vardan.pogosyan@gmail.com" } ], "require": { "yiisoft/yii2": "*", - "bshaffer/oauth2-server-php": "~1.7" + "bshaffer/oauth2-server-php": "^1.7" }, "autoload": { "psr-4": { - "filsh\\yii2\\oauth2server\\": "" + "filsh\\yii2\\oauth2server\\": "src/" } }, "extra": { "bootstrap": "filsh\\yii2\\oauth2server\\Bootstrap", "branch-alias": { - "dev-master": "1.0.x-dev" + "dev-master": "2.1.x-dev" } } } From bfab338b162de161037ecf63db45ffbaece4d164 Mon Sep 17 00:00:00 2001 From: Vardan Pogosian Date: Mon, 3 Aug 2020 14:23:39 +0300 Subject: [PATCH 61/67] feat: added YiiRequestAdapter for Yii2 >= 2.0.13 --- Bootstrap.php => src/Bootstrap.php | 0 BootstrapTrait.php => src/BootstrapTrait.php | 0 Module.php => src/Module.php | 20 +++++---- Request.php => src/Request.php | 0 Response.php => src/Response.php | 0 Server.php => src/Server.php | 0 src/YiiRequestAdapter.php | 42 +++++++++++++++++++ src/commands/.gitkeep | 0 .../controllers}/RestController.php | 3 +- .../exceptions}/HttpException.php | 0 .../filters}/ErrorToExceptionFilter.php | 5 +-- .../filters}/auth/CompositeAuth.php | 0 {messages => src/messages}/en/common.php | 0 .../messages}/es/oauth2server.php | 0 .../messages}/hu/oauth2server.php | 0 .../messages}/zh-CN/oauth2server.php | 0 .../messages}/zh-TW/oauth2server.php | 0 .../m140501_075311_add_oauth2_server.php | 0 {models => src/models}/OauthAccessTokens.php | 2 - .../models}/OauthAuthorizationCodes.php | 2 - {models => src/models}/OauthClients.php | 2 - {models => src/models}/OauthRefreshTokens.php | 2 - {models => src/models}/OauthScopes.php | 2 - {storage => src/storage}/Pdo.php | 0 {traits => src/traits}/ClassNamespace.php | 0 25 files changed, 57 insertions(+), 23 deletions(-) rename Bootstrap.php => src/Bootstrap.php (100%) rename BootstrapTrait.php => src/BootstrapTrait.php (100%) rename Module.php => src/Module.php (93%) rename Request.php => src/Request.php (100%) rename Response.php => src/Response.php (100%) rename Server.php => src/Server.php (100%) create mode 100644 src/YiiRequestAdapter.php create mode 100644 src/commands/.gitkeep rename {controllers => src/controllers}/RestController.php (99%) rename {exceptions => src/exceptions}/HttpException.php (100%) rename {filters => src/filters}/ErrorToExceptionFilter.php (99%) rename {filters => src/filters}/auth/CompositeAuth.php (100%) rename {messages => src/messages}/en/common.php (100%) rename {messages => src/messages}/es/oauth2server.php (100%) rename {messages => src/messages}/hu/oauth2server.php (100%) rename {messages => src/messages}/zh-CN/oauth2server.php (100%) rename {messages => src/messages}/zh-TW/oauth2server.php (100%) rename {migrations => src/migrations}/m140501_075311_add_oauth2_server.php (100%) rename {models => src/models}/OauthAccessTokens.php (99%) rename {models => src/models}/OauthAuthorizationCodes.php (99%) rename {models => src/models}/OauthClients.php (99%) rename {models => src/models}/OauthRefreshTokens.php (99%) rename {models => src/models}/OauthScopes.php (98%) rename {storage => src/storage}/Pdo.php (100%) rename {traits => src/traits}/ClassNamespace.php (100%) diff --git a/Bootstrap.php b/src/Bootstrap.php similarity index 100% rename from Bootstrap.php rename to src/Bootstrap.php diff --git a/BootstrapTrait.php b/src/BootstrapTrait.php similarity index 100% rename from BootstrapTrait.php rename to src/BootstrapTrait.php diff --git a/Module.php b/src/Module.php similarity index 93% rename from Module.php rename to src/Module.php index 2573aab..ca3813e 100755 --- a/Module.php +++ b/src/Module.php @@ -2,13 +2,14 @@ namespace filsh\yii2\oauth2server; -use \Yii; +use Yii; use yii\i18n\PhpMessageSource; -use \array_key_exists; + +use function array_key_exists; /** * For example, - * + * * ```php * 'oauth2' => [ * 'class' => 'filsh\yii2\oauth2server\Module', @@ -31,7 +32,7 @@ */ class Module extends \yii\base\Module { - const VERSION = '2.0.0'; + const VERSION = '2.1.0'; /** * @var array Model's map @@ -140,10 +141,13 @@ public function getServer() public function getRequest() { - if(!$this->has('request')) { + if (!$this->has('request')) { $this->set('request', Request::createFromGlobals()); } - return $this->get('request'); + + $request = $this->get('request'); + + return $request instanceof \yii\web\Request ? new YiiRequestAdapter($request) : $request; } public function getResponse() @@ -163,8 +167,8 @@ public function registerTranslations() { if(!isset(Yii::$app->get('i18n')->translations['modules/oauth2/*'])) { Yii::$app->get('i18n')->translations['modules/oauth2/*'] = [ - 'class' => PhpMessageSource::className(), - 'basePath' => __DIR__ . '/messages', + 'class' => PhpMessageSource::className(), + 'basePath' => __DIR__.'/messages', ]; } } diff --git a/Request.php b/src/Request.php similarity index 100% rename from Request.php rename to src/Request.php diff --git a/Response.php b/src/Response.php similarity index 100% rename from Response.php rename to src/Response.php diff --git a/Server.php b/src/Server.php similarity index 100% rename from Server.php rename to src/Server.php diff --git a/src/YiiRequestAdapter.php b/src/YiiRequestAdapter.php new file mode 100644 index 0000000..d0966b5 --- /dev/null +++ b/src/YiiRequestAdapter.php @@ -0,0 +1,42 @@ +request = $request; + } + + public function query($name, $default = null) + { + return $this->request->get($name, $default); + } + + public function request($name, $default = null) + { + return $this->request->post($name, $default); + } + + public function server($name, $default = null) + { + return isset($_SERVER[$name]) ? $_SERVER[$name] : $default; + } + + public function headers($name, $default = null) + { + return $this->request->headers->get($name, $default); + } + + public function getAllQueryParameters() + { + return $this->request->queryParams; + } +} \ No newline at end of file diff --git a/src/commands/.gitkeep b/src/commands/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/controllers/RestController.php b/src/controllers/RestController.php similarity index 99% rename from controllers/RestController.php rename to src/controllers/RestController.php index 8e88eda..68a95fa 100755 --- a/controllers/RestController.php +++ b/src/controllers/RestController.php @@ -2,9 +2,8 @@ namespace filsh\yii2\oauth2server\controllers; -use Yii; -use yii\helpers\ArrayHelper; use filsh\yii2\oauth2server\filters\ErrorToExceptionFilter; +use yii\helpers\ArrayHelper; class RestController extends \yii\rest\Controller { diff --git a/exceptions/HttpException.php b/src/exceptions/HttpException.php similarity index 100% rename from exceptions/HttpException.php rename to src/exceptions/HttpException.php diff --git a/filters/ErrorToExceptionFilter.php b/src/filters/ErrorToExceptionFilter.php similarity index 99% rename from filters/ErrorToExceptionFilter.php rename to src/filters/ErrorToExceptionFilter.php index 2b6967d..72eae2c 100755 --- a/filters/ErrorToExceptionFilter.php +++ b/src/filters/ErrorToExceptionFilter.php @@ -2,10 +2,9 @@ namespace filsh\yii2\oauth2server\filters; -use Yii; -use yii\base\Controller; -use filsh\yii2\oauth2server\Module; use filsh\yii2\oauth2server\exceptions\HttpException; +use filsh\yii2\oauth2server\Module; +use yii\base\Controller; class ErrorToExceptionFilter extends \yii\base\Behavior { diff --git a/filters/auth/CompositeAuth.php b/src/filters/auth/CompositeAuth.php similarity index 100% rename from filters/auth/CompositeAuth.php rename to src/filters/auth/CompositeAuth.php diff --git a/messages/en/common.php b/src/messages/en/common.php similarity index 100% rename from messages/en/common.php rename to src/messages/en/common.php diff --git a/messages/es/oauth2server.php b/src/messages/es/oauth2server.php similarity index 100% rename from messages/es/oauth2server.php rename to src/messages/es/oauth2server.php diff --git a/messages/hu/oauth2server.php b/src/messages/hu/oauth2server.php similarity index 100% rename from messages/hu/oauth2server.php rename to src/messages/hu/oauth2server.php diff --git a/messages/zh-CN/oauth2server.php b/src/messages/zh-CN/oauth2server.php similarity index 100% rename from messages/zh-CN/oauth2server.php rename to src/messages/zh-CN/oauth2server.php diff --git a/messages/zh-TW/oauth2server.php b/src/messages/zh-TW/oauth2server.php similarity index 100% rename from messages/zh-TW/oauth2server.php rename to src/messages/zh-TW/oauth2server.php diff --git a/migrations/m140501_075311_add_oauth2_server.php b/src/migrations/m140501_075311_add_oauth2_server.php similarity index 100% rename from migrations/m140501_075311_add_oauth2_server.php rename to src/migrations/m140501_075311_add_oauth2_server.php diff --git a/models/OauthAccessTokens.php b/src/models/OauthAccessTokens.php similarity index 99% rename from models/OauthAccessTokens.php rename to src/models/OauthAccessTokens.php index 6edb901..d7d6c84 100755 --- a/models/OauthAccessTokens.php +++ b/src/models/OauthAccessTokens.php @@ -2,8 +2,6 @@ namespace filsh\yii2\oauth2server\models; -use Yii; - /** * This is the model class for table "oauth_access_tokens". * diff --git a/models/OauthAuthorizationCodes.php b/src/models/OauthAuthorizationCodes.php similarity index 99% rename from models/OauthAuthorizationCodes.php rename to src/models/OauthAuthorizationCodes.php index 3c613e6..6128ec7 100755 --- a/models/OauthAuthorizationCodes.php +++ b/src/models/OauthAuthorizationCodes.php @@ -2,8 +2,6 @@ namespace filsh\yii2\oauth2server\models; -use Yii; - /** * This is the model class for table "oauth_authorization_codes". * diff --git a/models/OauthClients.php b/src/models/OauthClients.php similarity index 99% rename from models/OauthClients.php rename to src/models/OauthClients.php index 77c1999..620a555 100755 --- a/models/OauthClients.php +++ b/src/models/OauthClients.php @@ -2,8 +2,6 @@ namespace filsh\yii2\oauth2server\models; -use Yii; - /** * This is the model class for table "oauth_clients". * diff --git a/models/OauthRefreshTokens.php b/src/models/OauthRefreshTokens.php similarity index 99% rename from models/OauthRefreshTokens.php rename to src/models/OauthRefreshTokens.php index 6fb5714..9e2b740 100755 --- a/models/OauthRefreshTokens.php +++ b/src/models/OauthRefreshTokens.php @@ -2,8 +2,6 @@ namespace filsh\yii2\oauth2server\models; -use Yii; - /** * This is the model class for table "oauth_refresh_tokens". * diff --git a/models/OauthScopes.php b/src/models/OauthScopes.php similarity index 98% rename from models/OauthScopes.php rename to src/models/OauthScopes.php index d1a24a9..31cf604 100755 --- a/models/OauthScopes.php +++ b/src/models/OauthScopes.php @@ -2,8 +2,6 @@ namespace filsh\yii2\oauth2server\models; -use Yii; - /** * This is the model class for table "oauth_scopes". * diff --git a/storage/Pdo.php b/src/storage/Pdo.php similarity index 100% rename from storage/Pdo.php rename to src/storage/Pdo.php diff --git a/traits/ClassNamespace.php b/src/traits/ClassNamespace.php similarity index 100% rename from traits/ClassNamespace.php rename to src/traits/ClassNamespace.php From 155cd7eb5e6ab3e9bb37bee1e706191919c1bc46 Mon Sep 17 00:00:00 2001 From: Vardan Pogosian Date: Mon, 3 Aug 2020 15:12:40 +0300 Subject: [PATCH 62/67] fix: updated README.md --- README.md | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 77d17e7..113fc0b 100755 --- a/README.md +++ b/README.md @@ -10,24 +10,18 @@ The preferred way to install this extension is through [composer](http://getcomp Either run -``` +```shell script php composer.phar require --prefer-dist filsh/yii2-oauth2-server "*" ``` or add ```json -"filsh/yii2-oauth2-server": "~2.0" +"filsh/yii2-oauth2-server": "^2.0" ``` to the require section of your composer.json. -To use the latest features (Like JWT tokens), you need to use 2.0.1 branch. -Edit your compose.json and add - -```json -"filsh/yii2-oauth2-server": "2.0.1.x-dev" -``` To use this extension, simply add the following code in your application configuration: @@ -148,7 +142,7 @@ class SiteController extends Controller } ``` -Also if you set ```allowImplicit => true``` you can use Implicit Grant Type - [see more](http://bshaffer.github.io/oauth2-server-php-docs/grant-types/implicit/) +Also, if you set ```allowImplicit => true``` you can use Implicit Grant Type - [see more](http://bshaffer.github.io/oauth2-server-php-docs/grant-types/implicit/) Request example: @@ -199,3 +193,6 @@ class PublicKeyStorage implements \OAuth2\Storage\PublicKeyInterface{ For more, see https://github.com/bshaffer/oauth2-server-php + +# Authors & Contributors +The original author of this package [Igor Maliy](https://github.com/filsh) . At the time the project maintainer is [Vardan Pogosian](https://vardan.dev). \ No newline at end of file From 4573d9978fabc68b344681c98f0761af5c233de7 Mon Sep 17 00:00:00 2001 From: Vardan Pogosian Date: Mon, 3 Aug 2020 17:16:15 +0300 Subject: [PATCH 63/67] fix: updated README.md --- README.md | 10 ++++------ src/Module.php | 8 ++++---- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 113fc0b..534973a 100755 --- a/README.md +++ b/README.md @@ -50,19 +50,17 @@ To use this extension, simply add the following code in your application config ```common\models\User``` - user model implementing an interface ```\OAuth2\Storage\UserCredentialsInterface```, so the oauth2 credentials data stored in user table -Additional OAuth2 Flags: +You can pass additional OAuth2 Server Options by setting `options` property on the module. Some of them are implemented as standalone properties on the module: `tokenParamName`, `tokenAccessLifetime`, `useJwtToken`. For a full list of the supported options go to the - [source code](https://github.com/bshaffer/oauth2-server-php/blob/5a0c8000d4763b276919e2106f54eddda6bc50fa/src/OAuth2/Server.php#L162). -```enforceState``` - Flag that switch that state controller should allow to use "state" param in the "Authorization Code" Grant Type -```allowImplicit``` - Flag that switch that controller should allow the "implicit" grant type -The next step your shold run migration +The next step you should run migration ```php yii migrate --migrationPath=@vendor/filsh/yii2-oauth2-server/migrations ``` -this migration create the oauth2 database scheme and insert test user credentials ```testclient:testpass``` for ```http://fake/``` +this migration creates the oauth2 database scheme and insert test user credentials ```testclient:testpass``` for ```http://fake/``` add url rule to urlManager @@ -142,7 +140,7 @@ class SiteController extends Controller } ``` -Also, if you set ```allowImplicit => true``` you can use Implicit Grant Type - [see more](http://bshaffer.github.io/oauth2-server-php-docs/grant-types/implicit/) +Also, if you set ```allow_implicit => true``` in the ```options``` property of the module, you can use Implicit Grant Type - [see more](http://bshaffer.github.io/oauth2-server-php-docs/grant-types/implicit/) Request example: diff --git a/src/Module.php b/src/Module.php index ca3813e..f9ade32 100755 --- a/src/Module.php +++ b/src/Module.php @@ -58,7 +58,6 @@ class Module extends \yii\base\Module * @var string name of access token parameter */ public $tokenParamName; - /** * @var type max access lifetime */ @@ -66,8 +65,9 @@ class Module extends \yii\base\Module /** * @var whether to use JWT tokens */ - public $useJwtToken = false;//ADDED - + public $useJwtToken = false; + + /** * @inheritdoc */ @@ -126,7 +126,7 @@ public function getServer() $this, $storages, array_merge(array_filter([ - 'use_jwt_access_tokens' => $this->useJwtToken,//ADDED + 'use_jwt_access_tokens' => $this->useJwtToken, 'token_param_name' => $this->tokenParamName, 'access_lifetime' => $this->tokenAccessLifetime, /** add more ... */ From 441732cb42db3fa3992135dc5951e2a593968dca Mon Sep 17 00:00:00 2001 From: Vardan Pogosian Date: Wed, 5 Aug 2020 10:26:20 +0300 Subject: [PATCH 64/67] feat: added asset-packagist.org repository to the composer.json --- composer.json | 78 +++++++++++++++++++++++++++++---------------------- 1 file changed, 45 insertions(+), 33 deletions(-) diff --git a/composer.json b/composer.json index 995e522..7de9766 100755 --- a/composer.json +++ b/composer.json @@ -1,37 +1,49 @@ { - "name": "filsh/yii2-oauth2-server", - "description": "OAuth2 Server for PHP", - "keywords": ["yii", "extension", "module", "oauth", "oauth2"], - "homepage": "https://github.com/filsh/yii2-oauth2-server", - "type": "yii2-extension", - "license": "MIT", - "support": { - "email": "imaliy.filsh@gmail.com", - "source": "https://github.com/filsh/yii2-oauth2-server" + "name": "filsh/yii2-oauth2-server", + "description": "OAuth2 Server for PHP", + "keywords": [ + "yii", + "extension", + "module", + "oauth", + "oauth2" + ], + "homepage": "https://github.com/filsh/yii2-oauth2-server", + "type": "yii2-extension", + "license": "MIT", + "support": { + "email": "imaliy.filsh@gmail.com", + "source": "https://github.com/filsh/yii2-oauth2-server" + }, + "authors": [ + { + "name": "Igor Maliy", + "email": "imaliy.filsh@gmail.com" }, - "authors": [ - { - "name": "Igor Maliy", - "email": "imaliy.filsh@gmail.com" - }, - { - "name": "Vardan Pogosian", - "email": "vardan.pogosyan@gmail.com" - } - ], - "require": { - "yiisoft/yii2": "*", - "bshaffer/oauth2-server-php": "^1.7" - }, - "autoload": { - "psr-4": { - "filsh\\yii2\\oauth2server\\": "src/" - } - }, - "extra": { - "bootstrap": "filsh\\yii2\\oauth2server\\Bootstrap", - "branch-alias": { - "dev-master": "2.1.x-dev" - } + { + "name": "Vardan Pogosian", + "email": "vardan.pogosyan@gmail.com" + } + ], + "require": { + "yiisoft/yii2": "*", + "bshaffer/oauth2-server-php": "^1.7" + }, + "autoload": { + "psr-4": { + "filsh\\yii2\\oauth2server\\": "src/" + } + }, + "repositories": [ + { + "type": "composer", + "url": "https://asset-packagist.org" + } + ], + "extra": { + "bootstrap": "filsh\\yii2\\oauth2server\\Bootstrap", + "branch-alias": { + "dev-master": "2.1.x-dev" } + } } From a9b50a2343827802600cbbc9b88222214d69cbb1 Mon Sep 17 00:00:00 2001 From: Vardan Pogosian Date: Wed, 7 Oct 2020 11:10:22 +0300 Subject: [PATCH 65/67] Updated migrations path. Closes #148 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 534973a..d3dd544 100755 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ You can pass additional OAuth2 Server Options by setting `options` property on t The next step you should run migration ```php -yii migrate --migrationPath=@vendor/filsh/yii2-oauth2-server/migrations +yii migrate --migrationPath=@vendor/filsh/yii2-oauth2-server/src/migrations ``` this migration creates the oauth2 database scheme and insert test user credentials ```testclient:testpass``` for ```http://fake/``` @@ -193,4 +193,4 @@ class PublicKeyStorage implements \OAuth2\Storage\PublicKeyInterface{ For more, see https://github.com/bshaffer/oauth2-server-php # Authors & Contributors -The original author of this package [Igor Maliy](https://github.com/filsh) . At the time the project maintainer is [Vardan Pogosian](https://vardan.dev). \ No newline at end of file +The original author of this package [Igor Maliy](https://github.com/filsh) . At the time the project maintainer is [Vardan Pogosian](https://vardan.dev). From 7ade85ce70c63005896bead54aa8d2da6f31f7fb Mon Sep 17 00:00:00 2001 From: Vardan Pogosian Date: Mon, 19 Oct 2020 13:35:23 +0300 Subject: [PATCH 66/67] fix(docs): updated README.md; closes #149 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 534973a..76041d6 100755 --- a/README.md +++ b/README.md @@ -130,7 +130,7 @@ class SiteController extends Controller /** @var $module \filsh\yii2\oauth2server\Module */ $module = Yii::$app->getModule('oauth2'); - $response = $module->handleAuthorizeRequest(!Yii::$app->getUser()->getIsGuest(), Yii::$app->getUser()->getId()); + $response = $module->getServer()->handleAuthorizeRequest(null, null, !Yii::$app->getUser()->getIsGuest(), Yii::$app->getUser()->getId()); /** @var object $response \OAuth2\Response */ Yii::$app->getResponse()->format = \yii\web\Response::FORMAT_JSON; From 9d3ebee96db084b8c1cd5ae596591518db461d3b Mon Sep 17 00:00:00 2001 From: Vardan Pogosian Date: Mon, 19 Oct 2020 15:31:09 +0300 Subject: [PATCH 67/67] feat(docs): add Configuration section to README.md; closes #144 --- README.md | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 9de13c0..04e2452 100755 --- a/README.md +++ b/README.md @@ -1,10 +1,8 @@ -yii2-oauth2-server -================== +# yii2-oauth2-server A wrapper for implementing an OAuth2 Server(https://github.com/bshaffer/oauth2-server-php) -Installation ------------- +## Installation The preferred way to install this extension is through [composer](http://getcomposer.org/download/). @@ -20,7 +18,7 @@ or add "filsh/yii2-oauth2-server": "^2.0" ``` -to the require section of your composer.json. +to the `require` section of your composer.json. To use this extension, simply add the following code in your application configuration: @@ -50,10 +48,6 @@ To use this extension, simply add the following code in your application config ```common\models\User``` - user model implementing an interface ```\OAuth2\Storage\UserCredentialsInterface```, so the oauth2 credentials data stored in user table -You can pass additional OAuth2 Server Options by setting `options` property on the module. Some of them are implemented as standalone properties on the module: `tokenParamName`, `tokenAccessLifetime`, `useJwtToken`. For a full list of the supported options go to the - [source code](https://github.com/bshaffer/oauth2-server-php/blob/5a0c8000d4763b276919e2106f54eddda6bc50fa/src/OAuth2/Server.php#L162). - - - The next step you should run migration ```php @@ -73,8 +67,18 @@ add url rule to urlManager ] ``` -Usage ------ + +## Configuration + +You can pass additional OAuth2 Server options by setting `options` property on the module. These options configure as the underlying OAuth2 Server also as various parts/components of [bshaffer/oauth2-server-php](https://github.com/bshaffer/oauth2-server-php). +As an example, you can configure authorization code lifetime in a response by setting `auth_code_lifetime` option. +Some of them are implemented as standalone properties on the module: `tokenParamName` => `use_jwt_access_tokens`, `tokenAccessLifetime` => `token_param_name`, `useJwtToken` => `access_lifetime`. +Full list of options are supported by the underlying OAuth2 Server main component - [source code](https://github.com/bshaffer/oauth2-server-php/blob/5a0c8000d4763b276919e2106f54eddda6bc50fa/src/OAuth2/Server.php#L162). Options for various components spread across [bshaffer/oauth2-server-php](https://github.com/bshaffer/oauth2-server-php) source code. + + + + +# Usage To use this extension, simply add the behaviors for your base controller: