diff --git a/app/config/app.php b/app/config/app.php index 76e57fe0..3cbd0834 100644 --- a/app/config/app.php +++ b/app/config/app.php @@ -106,8 +106,8 @@ return array( 'Illuminate\Workbench\WorkbenchServiceProvider', 'Illuminate\Redis\RedisServiceProvider', 'services\utils\UtilsProvider', + 'services\oauth2\OAuth2ServiceProvider', 'services\openid\OpenIdProvider', - 'services\oauth2\OAuth2ServiceProvider', 'auth\AuthenticationServiceProvider', 'services\ServicesProvider', 'strategies\StrategyProvider', diff --git a/app/config/local/app.php b/app/config/local/app.php index d235717a..27cc3333 100644 --- a/app/config/local/app.php +++ b/app/config/local/app.php @@ -106,8 +106,8 @@ return array( 'Illuminate\Workbench\WorkbenchServiceProvider', 'Illuminate\Redis\RedisServiceProvider', 'services\utils\UtilsProvider', + 'services\oauth2\OAuth2ServiceProvider', 'services\openid\OpenIdProvider', - 'services\oauth2\OAuth2ServiceProvider', 'auth\AuthenticationServiceProvider', 'services\ServicesProvider', 'strategies\StrategyProvider', diff --git a/app/controllers/UserController.php b/app/controllers/UserController.php index 2284be82..9cb04a74 100644 --- a/app/controllers/UserController.php +++ b/app/controllers/UserController.php @@ -5,21 +5,18 @@ use oauth2\services\IClientService; use oauth2\services\IMementoOAuth2AuthenticationRequestService; use oauth2\services\ITokenService; use oauth2\services\IResourceServerService; -use openid\requests\OpenIdAuthenticationRequest; use openid\services\IMementoOpenIdRequestService; -use openid\services\IServerConfigurationService; use openid\services\ITrustedSitesService; use openid\services\IUserService; +use openid\services\IServerConfigurationService; use openid\XRDS\XRDSDocumentBuilder; use utils\IPHelper; use services\IUserActionService; use strategies\DefaultLoginStrategy; use strategies\OAuth2ConsentStrategy; use strategies\OAuth2LoginStrategy; -use strategies\OpenIdConsentStrategy; -use strategies\OpenIdLoginStrategy; use utils\services\IAuthService; - +use utils\services\IServerConfigurationService as IUtilsServerConfigurationService; class UserController extends BaseController { @@ -37,6 +34,7 @@ class UserController extends BaseController private $scope_service; private $token_service; private $resource_server_service; + private $utils_configuration_service; public function __construct(IMementoOpenIdRequestService $openid_memento_service, IMementoOAuth2AuthenticationRequestService $oauth2_memento_service, @@ -49,7 +47,9 @@ class UserController extends BaseController IClientService $client_service, IApiScopeService $scope_service, ITokenService $token_service, - IResourceServerService $resource_server_service) + IResourceServerService $resource_server_service, + IUtilsServerConfigurationService $utils_configuration_service + ) { $this->openid_memento_service = $openid_memento_service; $this->oauth2_memento_service = $oauth2_memento_service; @@ -63,6 +63,7 @@ class UserController extends BaseController $this->scope_service = $scope_service; $this->token_service = $token_service; $this->resource_server_service = $resource_server_service; + $this->utils_configuration_service = $utils_configuration_service; //filters $this->beforeFilter('csrf', array('only' => array('postLogin', 'postConsent'))); @@ -183,6 +184,11 @@ class UserController extends BaseController if ($current_user && $current_user->getIdentifier() != $user->getIdentifier()) { $another_user = true; } + + $assets_url = $this->utils_configuration_service->getConfigValue("Assets.Url"); + $pic_url = $user->getPic(); + $pic_url = str_contains($pic_url,'http')?$pic_url:$assets_url.$pic_url; + $params = array( 'show_fullname' => $user->getShowProfileFullName(), 'username' => $user->getFullName(), @@ -190,7 +196,7 @@ class UserController extends BaseController 'email' => $user->getEmail(), 'identifier' => $user->getIdentifier(), 'show_pic' => $user->getShowProfilePic(), - 'pic' => $user->getPic(), + 'pic' => $pic_url, 'another_user' => $another_user, ); return View::make("identity", $params); diff --git a/app/database/seeds/TestSeeder.php b/app/database/seeds/TestSeeder.php index 08f83432..6ac0137e 100644 --- a/app/database/seeds/TestSeeder.php +++ b/app/database/seeds/TestSeeder.php @@ -819,7 +819,7 @@ class TestSeeder extends Seeder { 'name' => 'create-resource-server', 'active' => true, 'api_id' => $resource_server->id, - 'route' => 'api/v1/resource-servers', + 'route' => '/api/v1/resource-servers', 'http_method' => 'POST' ) ); @@ -829,7 +829,7 @@ class TestSeeder extends Seeder { 'name' => 'get-resource-server', 'active' => true, 'api_id' => $resource_server->id, - 'route' => 'api/v1/resource-servers/{id}', + 'route' => '/api/v1/resource-servers/{id}', 'http_method' => 'GET' ) ); @@ -839,7 +839,7 @@ class TestSeeder extends Seeder { 'name' => 'resource-server-regenerate-secret', 'active' => true, 'api_id' => $resource_server->id, - 'route' => 'api/v1/resource-servers/{id}/client-secret', + 'route' => '/api/v1/resource-servers/{id}/client-secret', 'http_method' => 'PUT' ) ); @@ -849,7 +849,7 @@ class TestSeeder extends Seeder { 'name' => 'resource-server-get-page', 'active' => true, 'api_id' => $resource_server->id, - 'route' => 'api/v1/resource-servers', + 'route' => '/api/v1/resource-servers', 'http_method' => 'GET' ) ); @@ -859,7 +859,7 @@ class TestSeeder extends Seeder { 'name' => 'resource-server-delete', 'active' => true, 'api_id' => $resource_server->id, - 'route' => 'api/v1/resource-servers/{id}', + 'route' => '/api/v1/resource-servers/{id}', 'http_method' => 'DELETE' ) ); @@ -869,7 +869,7 @@ class TestSeeder extends Seeder { 'name' => 'resource-server-update', 'active' => true, 'api_id' => $resource_server->id, - 'route' => 'api/v1/resource-servers', + 'route' => '/api/v1/resource-servers', 'http_method' => 'PUT' ) ); @@ -879,7 +879,7 @@ class TestSeeder extends Seeder { 'name' => 'resource-server-update-status', 'active' => true, 'api_id' => $resource_server->id, - 'route' => 'api/v1/resource-servers/{id}/status/{active}', + 'route' => '/api/v1/resource-servers/{id}/status/{active}', 'http_method' => 'PUT' ) ); @@ -941,7 +941,7 @@ class TestSeeder extends Seeder { 'name' => 'get-api', 'active' => true, 'api_id' => $api_api->id, - 'route' => 'api/v1/api/{id}', + 'route' => '/api/v1/api/{id}', 'http_method' => 'GET' ) ); @@ -952,7 +952,7 @@ class TestSeeder extends Seeder { 'name' => 'delete-api', 'active' => true, 'api_id' => $api_api->id, - 'route' => 'api/v1/api/{id}', + 'route' => '/api/v1/api/{id}', 'http_method' => 'DELETE' ) ); @@ -962,7 +962,7 @@ class TestSeeder extends Seeder { 'name' => 'create-api', 'active' => true, 'api_id' => $api_api->id, - 'route' => 'api/v1/api', + 'route' => '/api/v1/api', 'http_method' => 'POST' ) ); @@ -972,7 +972,7 @@ class TestSeeder extends Seeder { 'name' => 'update-api', 'active' => true, 'api_id' => $api_api->id, - 'route' => 'api/v1/api', + 'route' => '/api/v1/api', 'http_method' => 'PUT' ) ); @@ -982,7 +982,7 @@ class TestSeeder extends Seeder { 'name' => 'update-api-status', 'active' => true, 'api_id' => $api_api->id, - 'route' => 'api/v1/api/status/{id}/{active}', + 'route' => '/api/v1/api/status/{id}/{active}', 'http_method' => 'GET' ) ); @@ -992,7 +992,7 @@ class TestSeeder extends Seeder { 'name' => 'api-get-page', 'active' => true, 'api_id' => $api_api->id, - 'route' => 'api/v1/api/{page_nbr}/{page_size}', + 'route' => '/api/v1/api/{page_nbr}/{page_size}', 'http_method' => 'GET' ) ); @@ -1037,7 +1037,7 @@ class TestSeeder extends Seeder { 'name' => 'get-api-endpoint', 'active' => true, 'api_id' => $api_api_endpoint->id, - 'route' => 'api/v1/api-endpoint/{id}', + 'route' => '/api/v1/api-endpoint/{id}', 'http_method' => 'GET' ) ); @@ -1047,7 +1047,7 @@ class TestSeeder extends Seeder { 'name' => 'delete-api-endpoint', 'active' => true, 'api_id' => $api_api_endpoint->id, - 'route' => 'api/v1/api-endpoint/{id}', + 'route' => '/api/v1/api-endpoint/{id}', 'http_method' => 'DELETE' ) ); @@ -1057,7 +1057,7 @@ class TestSeeder extends Seeder { 'name' => 'create-api-endpoint', 'active' => true, 'api_id' => $api_api_endpoint->id, - 'route' => 'api/v1/api-endpoint', + 'route' => '/api/v1/api-endpoint', 'http_method' => 'POST' ) ); @@ -1067,7 +1067,7 @@ class TestSeeder extends Seeder { 'name' => 'update-api-endpoint', 'active' => true, 'api_id' => $api_api_endpoint->id, - 'route' => 'api/v1/api-endpoint', + 'route' => '/api/v1/api-endpoint', 'http_method' => 'PUT' ) ); @@ -1077,7 +1077,7 @@ class TestSeeder extends Seeder { 'name' => 'update-api-endpoint-status', 'active' => true, 'api_id' => $api_api_endpoint->id, - 'route' => 'api/v1/api-endpoint/status/{id}/{active}', + 'route' => '/api/v1/api-endpoint/status/{id}/{active}', 'http_method' => 'GET' ) ); @@ -1087,7 +1087,7 @@ class TestSeeder extends Seeder { 'name' => 'api-endpoint-get-page', 'active' => true, 'api_id' => $api_api_endpoint->id, - 'route' => 'api/v1/api-endpoint/{page_nbr}/{page_size}', + 'route' => '/api/v1/api-endpoint/{page_nbr}/{page_size}', 'http_method' => 'GET' ) ); @@ -1098,7 +1098,7 @@ class TestSeeder extends Seeder { 'name' => 'add-api-endpoint-scope', 'active' => true, 'api_id' => $api_api_endpoint->id, - 'route' => 'api/v1/api-endpoint/scope/add/{id}/{scope_id}', + 'route' => '/api/v1/api-endpoint/scope/add/{id}/{scope_id}', 'http_method' => 'GET' ) ); @@ -1108,7 +1108,7 @@ class TestSeeder extends Seeder { 'name' => 'remove-api-endpoint-scope', 'active' => true, 'api_id' => $api_api_endpoint->id, - 'route' => 'api/v1/api-endpoint/scope/remove/{id}/{scope_id}', + 'route' => '/api/v1/api-endpoint/scope/remove/{id}/{scope_id}', 'http_method' => 'GET' ) ); @@ -1165,7 +1165,7 @@ class TestSeeder extends Seeder { 'name' => 'get-scope', 'active' => true, 'api_id' => $api_scope->id, - 'route' => 'api/v1/api-scope/{id}', + 'route' => '/api/v1/api-scope/{id}', 'http_method' => 'GET' ) ); @@ -1176,7 +1176,7 @@ class TestSeeder extends Seeder { 'name' => 'delete-scope', 'active' => true, 'api_id' => $api_scope->id, - 'route' => 'api/v1/api-scope/{id}', + 'route' => '/api/v1/api-scope/{id}', 'http_method' => 'DELETE' ) ); @@ -1186,7 +1186,7 @@ class TestSeeder extends Seeder { 'name' => 'create-scope', 'active' => true, 'api_id' => $api_scope->id, - 'route' => 'api/v1/api-scope', + 'route' => '/api/v1/api-scope', 'http_method' => 'POST' ) ); @@ -1196,7 +1196,7 @@ class TestSeeder extends Seeder { 'name' => 'update-scope', 'active' => true, 'api_id' => $api_scope->id, - 'route' => 'api/v1/api-scope', + 'route' => '/api/v1/api-scope', 'http_method' => 'PUT' ) ); @@ -1206,7 +1206,7 @@ class TestSeeder extends Seeder { 'name' => 'update-scope-status', 'active' => true, 'api_id' => $api_scope->id, - 'route' => 'api/v1/api-scope/status/{id}/{active}', + 'route' => '/api/v1/api-scope/status/{id}/{active}', 'http_method' => 'GET' ) ); @@ -1216,7 +1216,7 @@ class TestSeeder extends Seeder { 'name' => 'scope-get-page', 'active' => true, 'api_id' => $api_scope->id, - 'route' => 'api/v1/api-scope/{page_nbr}/{page_size}', + 'route' => '/api/v1/api-scope/{page_nbr}/{page_size}', 'http_method' => 'GET' ) ); @@ -1260,7 +1260,7 @@ class TestSeeder extends Seeder { 'name' => 'get-user-info', 'active' => true, 'api_id' => $users->id, - 'route' => 'api/v1/users/me', + 'route' => '/api/v1/users/me', 'http_method' => 'GET' ) ); diff --git a/app/filters/OAuth2RequestAccessTokenValidator.php b/app/filters/OAuth2RequestAccessTokenValidator.php index 5d2c30bc..49b8109a 100644 --- a/app/filters/OAuth2RequestAccessTokenValidator.php +++ b/app/filters/OAuth2RequestAccessTokenValidator.php @@ -19,20 +19,28 @@ use oauth2\IResourceServerContext; class OAuth2BearerAccessTokenRequestValidator { - protected function headers() + protected function getHeaders() { + $headers = array(); + if (function_exists('getallheaders')) { // @codeCoverageIgnoreStart - $headers = getallheaders(); + foreach(getallheaders() as $name => $value){ + $headers[strtolower($name)] = $value; + } } else { // @codeCoverageIgnoreEnd - $headers = array(); - foreach ($this->server() as $name => $value) { + foreach ($_SERVER as $name => $value) { if (substr($name, 0, 5) == 'HTTP_') { $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5))))); - $headers[$name] = $value; + $headers[strtolower($name)] = $value; } } + + foreach(Request::header() as $name => $value){ + if(!array_key_exists($name,$headers)) + $headers[strtolower($name)] = $value[0]; + } } return $headers; } @@ -50,7 +58,7 @@ class OAuth2BearerAccessTokenRequestValidator { $this->log_service = $log_service; $this->checkpoint_service = $checkpoint_service; $this->resource_server_context = $resource_server_context; - $this->headers = $this->headers(); + $this->headers = $this->getHeaders(); } /** @@ -76,7 +84,7 @@ class OAuth2BearerAccessTokenRequestValidator { } //check first http basic auth header - $auth_header = isset($this->headers['Authorization'])?$this->headers['Authorization']:null; + $auth_header = isset($this->headers['authorization'])?$this->headers['authorization']:null; if(!is_null($auth_header) && !empty($auth_header)) $access_token_value = BearerAccessTokenAuthorizationHeaderParser::getInstance()->parse($auth_header); else{ @@ -103,7 +111,7 @@ class OAuth2BearerAccessTokenRequestValidator { $endpoint_scopes = explode(' ',$endpoint->getScope()); $token_scopes = explode(' ',$access_token->getScope()); //check token available scopes vs. endpoint scopes - if (count(array_intersect($endpoint_scopes, $token_scopes)) === 0) + if (count(array_intersect($endpoint_scopes, $token_scopes)) == 0) { $this->log_service->error_msg(sprintf('access token scopes (%s) does not allow to access to api url %s , needed scopes %s',$access_token->getScope(),$url,implode(' OR ',$endpoint_scopes) )); diff --git a/app/libs/auth/AuthHelper.php b/app/libs/auth/AuthHelper.php index 5375c1b4..6ca4d541 100644 --- a/app/libs/auth/AuthHelper.php +++ b/app/libs/auth/AuthHelper.php @@ -35,6 +35,6 @@ class AuthHelper { // Due to flawed base_convert() floating poing precision, // only the first 10 characters are consistently useful for comparisons. - return (substr($hash1, 0, 10) === substr($hash2, 0, 10)); + return (substr($hash1, 0, 10) == substr($hash2, 0, 10)); } } \ No newline at end of file diff --git a/app/libs/auth/User.php b/app/libs/auth/User.php index 68165ccc..f4ea656a 100644 --- a/app/libs/auth/User.php +++ b/app/libs/auth/User.php @@ -6,8 +6,6 @@ use Illuminate\Auth\UserInterface; use Member; use MemberPhoto; use openid\model\IOpenIdUser; -use openid\services\OpenIdServiceCatalog; -use utils\services\ServiceLocator; use oauth2\models\IOAuth2User; use Eloquent; use utils\model\BaseModelEloquent; @@ -214,8 +212,7 @@ class User extends BaseModelEloquent implements UserInterface, IOpenIdUser, IOAu if (!is_null($photoId) && is_numeric($photoId) && $photoId > 0) { $photo = MemberPhoto::where('ID', '=', $photoId)->first(); if(!is_null($photo)){ - $server_configuration_service = ServiceLocator::getInstance()->getService(OpenIdServiceCatalog::ServerConfigurationService); - $url = $server_configuration_service->getConfigValue("Assets.Url").$photo->Filename; + $url = $photo->Filename; } } return $url; diff --git a/app/libs/oauth2/BearerAccessTokenAuthorizationHeaderParser.php b/app/libs/oauth2/BearerAccessTokenAuthorizationHeaderParser.php index a2acedf6..86715867 100644 --- a/app/libs/oauth2/BearerAccessTokenAuthorizationHeaderParser.php +++ b/app/libs/oauth2/BearerAccessTokenAuthorizationHeaderParser.php @@ -22,7 +22,7 @@ class BearerAccessTokenAuthorizationHeaderParser public static function getInstance() { - if (self::$instance === null) { + if (self::$instance == null) { self::$instance = new BearerAccessTokenAuthorizationHeaderParser(); } return self::$instance; @@ -49,7 +49,7 @@ class BearerAccessTokenAuthorizationHeaderParser } else { $accessTokenValue = trim(preg_replace('/^(?:\s+)?Bearer\s/', '', $http_auth_header_value)); } - $accessTokenValue = ($accessTokenValue === 'Bearer') ? '' : $accessTokenValue; + $accessTokenValue = ($accessTokenValue == 'Bearer') ? '' : $accessTokenValue; } if (empty($accessTokenValue)) { diff --git a/app/libs/oauth2/grant_types/AuthorizationCodeGrantType.php b/app/libs/oauth2/grant_types/AuthorizationCodeGrantType.php index be715af9..b9fe4199 100644 --- a/app/libs/oauth2/grant_types/AuthorizationCodeGrantType.php +++ b/app/libs/oauth2/grant_types/AuthorizationCodeGrantType.php @@ -62,8 +62,8 @@ class AuthorizationCodeGrantType extends AbstractGrantType $reflector = new ReflectionClass($request); $class_name = $reflector->getName(); return - ($class_name == 'oauth2\requests\OAuth2AuthorizationRequest' && $request->isValid() && $request->getResponseType() === $this->getResponseType()) || - ($class_name == 'oauth2\requests\OAuth2TokenRequest' && $request->isValid() && $request->getGrantType() === $this->getType()); + ($class_name == 'oauth2\requests\OAuth2AuthorizationRequest' && $request->isValid() && $request->getResponseType() == $this->getResponseType()) || + ($class_name == 'oauth2\requests\OAuth2TokenRequest' && $request->isValid() && $request->getGrantType() == $this->getType()); } /** diff --git a/app/libs/oauth2/grant_types/ClientCredentialsGrantType.php b/app/libs/oauth2/grant_types/ClientCredentialsGrantType.php index 1f77dc1a..b4fd1d46 100644 --- a/app/libs/oauth2/grant_types/ClientCredentialsGrantType.php +++ b/app/libs/oauth2/grant_types/ClientCredentialsGrantType.php @@ -53,7 +53,7 @@ class ClientCredentialsGrantType extends AbstractGrantType $reflector = new ReflectionClass($request); $class_name = $reflector->getName(); return - ($class_name == 'oauth2\requests\OAuth2TokenRequest' && $request->isValid() && $request->getGrantType() === $this->getType()); + ($class_name == 'oauth2\requests\OAuth2TokenRequest' && $request->isValid() && $request->getGrantType() == $this->getType()); } diff --git a/app/libs/oauth2/grant_types/ImplicitGrantType.php b/app/libs/oauth2/grant_types/ImplicitGrantType.php index 0e4137f2..86eefbff 100644 --- a/app/libs/oauth2/grant_types/ImplicitGrantType.php +++ b/app/libs/oauth2/grant_types/ImplicitGrantType.php @@ -76,7 +76,7 @@ class ImplicitGrantType extends AbstractGrantType $reflector = new ReflectionClass($request); $class_name = $reflector->getName(); return - ($class_name == 'oauth2\requests\OAuth2AuthorizationRequest' && $request->isValid() && $request->getResponseType() === $this->getResponseType()); + ($class_name == 'oauth2\requests\OAuth2AuthorizationRequest' && $request->isValid() && $request->getResponseType() == $this->getResponseType()); } /** get grant type response type diff --git a/app/libs/oauth2/grant_types/RefreshBearerTokenGrantType.php b/app/libs/oauth2/grant_types/RefreshBearerTokenGrantType.php index f7fc9e7a..6993fe60 100644 --- a/app/libs/oauth2/grant_types/RefreshBearerTokenGrantType.php +++ b/app/libs/oauth2/grant_types/RefreshBearerTokenGrantType.php @@ -39,7 +39,7 @@ class RefreshBearerTokenGrantType extends AbstractGrantType { { $reflector = new ReflectionClass($request); $class_name = $reflector->getName(); - return $class_name == 'oauth2\requests\OAuth2TokenRequest' && $request->isValid() && $request->getGrantType() === $this->getType(); + return $class_name == 'oauth2\requests\OAuth2TokenRequest' && $request->isValid() && $request->getGrantType() == $this->getType(); } /** Not implemented , there is no first process phase on this grant type diff --git a/app/libs/oauth2/grant_types/RevokeBearerTokenGrantType.php b/app/libs/oauth2/grant_types/RevokeBearerTokenGrantType.php index 44273d0d..6b70d241 100644 --- a/app/libs/oauth2/grant_types/RevokeBearerTokenGrantType.php +++ b/app/libs/oauth2/grant_types/RevokeBearerTokenGrantType.php @@ -82,7 +82,7 @@ class RevokeBearerTokenGrantType extends AbstractGrantType $reflector = new ReflectionClass($request); $class_name = $reflector->getName(); - if ($class_name === 'oauth2\requests\OAuth2TokenRevocationRequest') { + if ($class_name == 'oauth2\requests\OAuth2TokenRevocationRequest') { parent::completeFlow($request); $token_value = $request->getToken(); diff --git a/app/libs/oauth2/models/AccessToken.php b/app/libs/oauth2/models/AccessToken.php index f0748e34..04ee075d 100644 --- a/app/libs/oauth2/models/AccessToken.php +++ b/app/libs/oauth2/models/AccessToken.php @@ -27,7 +27,7 @@ class AccessToken extends Token { $instance->client_id = $auth_code->getClientId(); $instance->auth_code = $auth_code->getValue(); $instance->audience = $auth_code->getAudience(); - $instance->lifetime = $lifetime; + $instance->lifetime = intval($lifetime); $instance->is_hashed = false; return $instance; } @@ -41,7 +41,7 @@ class AccessToken extends Token { $instance->auth_code = null; $instance->audience = $audience; $instance->refresh_token = null; - $instance->lifetime = $lifetime; + $instance->lifetime = intval($lifetime); $instance->is_hashed = false; return $instance; } @@ -56,7 +56,7 @@ class AccessToken extends Token { $instance->auth_code = null; $instance->refresh_token = $refresh_token; $instance->audience = $refresh_token->getAudience(); - $instance->lifetime = $lifetime; + $instance->lifetime = intval($lifetime); $instance->is_hashed = false; return $instance; } @@ -71,7 +71,7 @@ class AccessToken extends Token { $instance->audience = $auth_code->getAudience(); $instance->from_ip = $auth_code->getFromIp(); $instance->issued = $issued; - $instance->lifetime = $lifetime; + $instance->lifetime = intval($lifetime); $instance->is_hashed = $is_hashed; return $instance; } diff --git a/app/libs/oauth2/models/AuthorizationCode.php b/app/libs/oauth2/models/AuthorizationCode.php index e323684c..232cb9fd 100644 --- a/app/libs/oauth2/models/AuthorizationCode.php +++ b/app/libs/oauth2/models/AuthorizationCode.php @@ -38,10 +38,10 @@ class AuthorizationCode extends Token { $instance = new self(); $instance->value = Rand::getString($instance->len, OAuth2Protocol::VsChar, true); $instance->scope = $scope; - $instance->user_id = $user_id; + $instance->user_id = $user_id; $instance->redirect_uri = $redirect_uri; $instance->client_id = $client_id; - $instance->lifetime = $lifetime; + $instance->lifetime = intval($lifetime); $instance->audience = $audience; $instance->is_hashed = false; $instance->from_ip = IPHelper::getUserIp(); @@ -69,17 +69,17 @@ class AuthorizationCode extends Token { */ public static function load($value, $user_id, $client_id, $scope,$audience='', $redirect_uri = null, $issued = null, $lifetime = 600, $from_ip = '127.0.0.1',$access_type = OAuth2Protocol::OAuth2Protocol_AccessType_Online,$approval_prompt = OAuth2Protocol::OAuth2Protocol_Approval_Prompt_Auto,$has_previous_user_consent=false,$is_hashed = false){ $instance = new self(); - $instance->value = $value; - $instance->user_id = $user_id; - $instance->scope = $scope; - $instance->redirect_uri = $redirect_uri; - $instance->client_id = $client_id; - $instance->audience = $audience; - $instance->issued = $issued; - $instance->lifetime = $lifetime; - $instance->from_ip = $from_ip; - $instance->is_hashed = $is_hashed; - $instance->access_type = $access_type; + $instance->value = $value; + $instance->user_id = $user_id; + $instance->scope = $scope; + $instance->redirect_uri = $redirect_uri; + $instance->client_id = $client_id; + $instance->audience = $audience; + $instance->issued = $issued; + $instance->lifetime = intval($lifetime); + $instance->from_ip = $from_ip; + $instance->is_hashed = $is_hashed; + $instance->access_type = $access_type; $instance->approval_prompt = $approval_prompt; $instance->has_previous_user_consent = $has_previous_user_consent; return $instance; diff --git a/app/libs/oauth2/models/RefreshToken.php b/app/libs/oauth2/models/RefreshToken.php index a7089cea..03192d1d 100644 --- a/app/libs/oauth2/models/RefreshToken.php +++ b/app/libs/oauth2/models/RefreshToken.php @@ -41,7 +41,7 @@ class RefreshToken extends Token { $instance->client_id = $access_token->getClientId(); $instance->audience = $access_token->getAudience(); $instance->from_ip = IPHelper::getUserIp(); - $instance->lifetime = $lifetime; + $instance->lifetime = intval($lifetime); $instance->is_hashed = false; return $instance; } @@ -56,7 +56,7 @@ class RefreshToken extends Token { $instance->from_ip = $params['from_ip']; $instance->issued = $params['issued']; $instance->is_hashed = isset($params['is_hashed'])?$params['is_hashed']:false; - $instance->lifetime = $lifetime; + $instance->lifetime = intval($lifetime); return $instance; } diff --git a/app/libs/oauth2/models/Token.php b/app/libs/oauth2/models/Token.php index 4e55487d..0d4a3817 100644 --- a/app/libs/oauth2/models/Token.php +++ b/app/libs/oauth2/models/Token.php @@ -45,7 +45,7 @@ abstract class Token public function getLifetime() { - return $this->lifetime; + return intval($this->lifetime); } public function getScope() @@ -75,9 +75,9 @@ abstract class Token public function getRemainingLifetime() { //check is refresh token is stills alive... (ZERO is infinite lifetime) - if ($this->lifetime === 0) return 0; + if (intval($this->lifetime) == 0) return 0; $created_at = new DateTime($this->issued); - $created_at->add(new DateInterval('PT' . $this->lifetime . 'S')); + $created_at->add(new DateInterval('PT' . intval($this->lifetime) . 'S')); $now = new DateTime(gmdate("Y-m-d H:i:s", time())); //check validity... if ($now > $created_at) diff --git a/app/libs/oauth2/strategies/OAuth2IndirectErrorResponseFactoryMethod.php b/app/libs/oauth2/strategies/OAuth2IndirectErrorResponseFactoryMethod.php index 6449895a..7694ba57 100644 --- a/app/libs/oauth2/strategies/OAuth2IndirectErrorResponseFactoryMethod.php +++ b/app/libs/oauth2/strategies/OAuth2IndirectErrorResponseFactoryMethod.php @@ -22,7 +22,7 @@ class OAuth2IndirectErrorResponseFactoryMethod { $response = null; $reflector = new ReflectionClass($request); $class_name = $reflector->getName(); - if($class_name ==='oauth2\requests\OAuth2AuthorizationRequest'){ + if($class_name =='oauth2\requests\OAuth2AuthorizationRequest'){ $response_type = $request->getResponseType(); switch($response_type){ case OAuth2Protocol::OAuth2Protocol_ResponseType_Token: diff --git a/app/libs/openid/OpenIdProtocol.php b/app/libs/openid/OpenIdProtocol.php index 49e05720..7e9fcdc8 100644 --- a/app/libs/openid/OpenIdProtocol.php +++ b/app/libs/openid/OpenIdProtocol.php @@ -19,6 +19,8 @@ use openid\services\IServerConfigurationService; use openid\services\INonceService; use utils\services\IAuthService; use utils\services\ICheckPointService; +use utils\services\IServerConfigurationService as IUtilsServerConfigurationService; + @@ -139,10 +141,11 @@ class OpenIdProtocol implements IOpenIdProtocol IServerConfigurationService $server_config_service, INonceService $nonce_service, ILogService $log_service, - ICheckPointService $checkpoint_service) + ICheckPointService $checkpoint_service, + IUtilsServerConfigurationService $utils_configuration_service) { //create chain of responsibility - $check_auth = new OpenIdCheckAuthenticationRequestHandler($association_service, $nonce_service, $log_service,$checkpoint_service, null); + $check_auth = new OpenIdCheckAuthenticationRequestHandler($association_service, $nonce_service, $log_service,$checkpoint_service,$utils_configuration_service,$server_config_service, null); $session_assoc = new OpenIdSessionAssociationRequestHandler($log_service,$checkpoint_service, $check_auth); $this->request_handlers = new OpenIdAuthenticationRequestHandler($auth_service, $memento_request_service, $auth_strategy, $server_extension_service, $association_service, $trusted_sites_service, $server_config_service, $nonce_service, $log_service,$checkpoint_service, $session_assoc); $this->server_extension_service = $server_extension_service; diff --git a/app/libs/openid/extensions/OpenIdExtension.php b/app/libs/openid/extensions/OpenIdExtension.php index 6d110906..59cc8e2f 100644 --- a/app/libs/openid/extensions/OpenIdExtension.php +++ b/app/libs/openid/extensions/OpenIdExtension.php @@ -21,19 +21,21 @@ abstract class OpenIdExtension protected $name; protected $description; protected $view; + protected $log_service; - /** - * @param $name - * @param $namespace - * @param $view - * @param $description - */ - public function __construct($name, $namespace, $view, $description, ILogService $log_service) + /** + * @param $name + * @param $namespace + * @param $view_name + * @param $description + * @param ILogService $log_service + */ + public function __construct($name, $namespace, $view_name, $description, ILogService $log_service) { - $this->namespace = $namespace; - $this->name = $name; - $this->view = $view; + $this->namespace = $namespace; + $this->name = $name; + $this->view = $view_name; $this->description = $description; $this->log_service = $log_service; } diff --git a/app/libs/openid/extensions/implementations/OpenIdAXExtension.php b/app/libs/openid/extensions/implementations/OpenIdAXExtension.php index 7c5b38d8..0b49d4b1 100644 --- a/app/libs/openid/extensions/implementations/OpenIdAXExtension.php +++ b/app/libs/openid/extensions/implementations/OpenIdAXExtension.php @@ -10,9 +10,8 @@ use openid\requests\contexts\RequestContext; use openid\requests\OpenIdRequest; use openid\responses\contexts\ResponseContext; use openid\responses\OpenIdResponse; -use utils\services\ServiceLocator; -use utils\services\UtilsServiceCatalog; use utils\services\ILogService; +use utils\services\IAuthService; /** * Class OpenIdAXExtension * Implements @@ -36,9 +35,22 @@ class OpenIdAXExtension extends OpenIdExtension const FetchRequest = "fetch_request"; public static $available_properties; - public function __construct($name, $namespace, $view, $description, ILogService $log_service) + private $auth_service; + + /** + * @param $name + * @param $namespace + * @param $view_name + * @param $description + * @param IAuthService $auth_service + * @param ILogService $log_service + */ + public function __construct($name, $namespace, $view_name, $description, + IAuthService $auth_service, + ILogService $log_service) { - parent::__construct($name, $namespace, $view, $description, $log_service); + parent::__construct($name, $namespace, $view_name, $description, $log_service); + $this->auth_service = $auth_service; self::$available_properties[OpenIdAXExtension::Country] = "http://axschema.org/contact/country/home"; self::$available_properties[OpenIdAXExtension::Email] = "http://axschema.org/contact/email"; self::$available_properties[OpenIdAXExtension::FirstMame] = "http://axschema.org/namePerson/first"; @@ -74,8 +86,7 @@ class OpenIdAXExtension extends OpenIdExtension $context->addSignParam(self::param(self::Mode)); $attributes = $ax_request->getRequiredAttributes(); - $auth_service = ServiceLocator::getInstance()->getService(UtilsServiceCatalog::AuthenticationService); - $user = $auth_service->getCurrentUser(); + $user = $this->auth_service->getCurrentUser(); foreach ($attributes as $attr) { $response->addParam(self::param(self::Type) . "." . $attr, self::$available_properties[$attr]); diff --git a/app/libs/openid/extensions/implementations/OpenIdOAuth2Extension.php b/app/libs/openid/extensions/implementations/OpenIdOAuth2Extension.php index 2521e900..1a0202f8 100644 --- a/app/libs/openid/extensions/implementations/OpenIdOAuth2Extension.php +++ b/app/libs/openid/extensions/implementations/OpenIdOAuth2Extension.php @@ -2,8 +2,10 @@ namespace openid\extensions\implementations; +use oauth2\IOAuth2Protocol; +use oauth2\services\IApiScopeService; +use oauth2\services\IClientService; use openid\requests\contexts\PartialView; -use oauth2\services\OAuth2ServiceCatalog; use openid\extensions\OpenIdExtension; use openid\OpenIdProtocol; use openid\requests\contexts\RequestContext; @@ -12,8 +14,7 @@ use openid\responses\contexts\ResponseContext; use openid\responses\OpenIdResponse; use Exception; -use utils\services\ServiceLocator; -use utils\services\UtilsServiceCatalog; +use utils\services\ICheckPointService; use utils\services\ILogService; use oauth2\requests\OAuth2AuthorizationRequest; @@ -48,20 +49,30 @@ class OpenIdOAuth2Extension extends OpenIdExtension private $client_service; private $scope_service; - /** - * @param $name - * @param $namespace - * @param $view - * @param $description - */ - public function __construct($name, $namespace, $view, $description, ILogService $log_service) + /** + * @param $name + * @param $namespace + * @param $view_name + * @param $description + * @param IOAuth2Protocol $oauth2_protocol + * @param IClientService $client_service + * @param IApiScopeService $scope_service + * @param ICheckPointService $checkpoint_service + * @param ILogService $log_service + */ + public function __construct($name, $namespace, $view_name, $description, + IOAuth2Protocol $oauth2_protocol, + IClientService $client_service, + IApiScopeService $scope_service, + ICheckPointService $checkpoint_service, + ILogService $log_service) { - parent::__construct($name, $namespace, $view, $description,$log_service); + parent::__construct($name, $namespace, $view_name, $description,$log_service); - $this->oauth2_protocol = ServiceLocator::getInstance()->getService('oauth2\IOAuth2Protocol'); - $this->checkpoint_service = ServiceLocator::getInstance()->getService(UtilsServiceCatalog::CheckPointService); - $this->client_service = ServiceLocator::getInstance()->getService(OAuth2ServiceCatalog::ClientService); - $this->scope_service = ServiceLocator::getInstance()->getService(OAuth2ServiceCatalog::ScopeService); + $this->oauth2_protocol = $oauth2_protocol; + $this->client_service = $client_service; + $this->scope_service = $scope_service; + $this->checkpoint_service = $checkpoint_service; } /** diff --git a/app/libs/openid/extensions/implementations/OpenIdSREGExtension.php b/app/libs/openid/extensions/implementations/OpenIdSREGExtension.php index 467096cf..3d9877e5 100644 --- a/app/libs/openid/extensions/implementations/OpenIdSREGExtension.php +++ b/app/libs/openid/extensions/implementations/OpenIdSREGExtension.php @@ -9,11 +9,9 @@ use openid\requests\contexts\RequestContext; use openid\requests\OpenIdRequest; use openid\responses\contexts\ResponseContext; use openid\responses\OpenIdResponse; -use utils\services\ServiceLocator; -use utils\services\UtilsServiceCatalog; -use Exception; +use utils\services\IAuthService; use utils\services\ILogService; - +use Exception; /** * Class OpenIdSREGExtension * Implements http://openid.net/specs/openid-simple-registration-extension-1_0.html @@ -42,9 +40,22 @@ class OpenIdSREGExtension extends OpenIdExtension public static $available_properties; - public function __construct($name, $namespace, $view, $description, ILogService $log_service) + private $auth_service; + + /** + * @param $name + * @param $namespace + * @param $view_name + * @param $description + * @param IAuthService $auth_service + * @param ILogService $log_service + */ + public function __construct($name, $namespace, $view_name , $description, + IAuthService $auth_service, + ILogService $log_service) { - parent::__construct($name, $namespace, $view, $description,$log_service); + parent::__construct($name, $namespace, $view_name, $description,$log_service); + $this->auth_service = $auth_service; self::$available_properties[OpenIdSREGExtension::Nickname] = OpenIdSREGExtension::Nickname; self::$available_properties[OpenIdSREGExtension::Email] = OpenIdSREGExtension::Email; self::$available_properties[OpenIdSREGExtension::FullName] = OpenIdSREGExtension::FullName; @@ -91,8 +102,7 @@ class OpenIdSREGExtension extends OpenIdExtension $opt_attributes = $simple_reg_request->getOptionalAttributes(); $attributes = array_merge($attributes, $opt_attributes); - $auth_service = ServiceLocator::getInstance()->getService(UtilsServiceCatalog::AuthenticationService); - $user = $auth_service->getCurrentUser(); + $user = $this->auth_service->getCurrentUser(); foreach ($attributes as $attr => $value) { $context->addSignParam(self::param($attr)); diff --git a/app/libs/openid/handlers/OpenIdAuthenticationRequestHandler.php b/app/libs/openid/handlers/OpenIdAuthenticationRequestHandler.php index 2ab7f32c..18062d5b 100644 --- a/app/libs/openid/handlers/OpenIdAuthenticationRequestHandler.php +++ b/app/libs/openid/handlers/OpenIdAuthenticationRequestHandler.php @@ -86,7 +86,8 @@ class OpenIdAuthenticationRequestHandler extends OpenIdMessageHandler { $this->current_request = null; try { - $this->current_request = new OpenIdAuthenticationRequest($message); + + $this->current_request = new OpenIdAuthenticationRequest($message,$this->server_configuration_service->getUserIdentityEndpointURL('@identifier')); if (!$this->current_request->isValid()){ throw new InvalidOpenIdMessageException(OpenIdErrorMessages::InvalidOpenIdAuthenticationRequestMessage); @@ -189,7 +190,7 @@ class OpenIdAuthenticationRequestHandler extends OpenIdMessageHandler $requested_data = $this->current_request_context->getTrustedData(); $sites = $this->trusted_sites_service->getTrustedSites($currentUser, $this->current_request->getRealm(), $requested_data); //check trusted sites - if (is_null($sites) || count($sites) === 0) + if (is_null($sites) || count($sites) == 0) return $this->doConsentProcess(); //there are trusted sites ... check the former authorization decision $site = $sites[0]; diff --git a/app/libs/openid/handlers/OpenIdCheckAuthenticationRequestHandler.php b/app/libs/openid/handlers/OpenIdCheckAuthenticationRequestHandler.php index 5d66f255..b560ac71 100644 --- a/app/libs/openid/handlers/OpenIdCheckAuthenticationRequestHandler.php +++ b/app/libs/openid/handlers/OpenIdCheckAuthenticationRequestHandler.php @@ -17,8 +17,10 @@ use openid\responses\OpenIdCheckAuthenticationResponse; use openid\responses\OpenIdDirectGenericErrorResponse; use openid\services\IAssociationService; use openid\services\INonceService; +use openid\services\IServerConfigurationService as IOpenIdServerConfigurationService; use utils\services\ILogService; use utils\services\ICheckPointService; +use utils\services\IServerConfigurationService; /** * Class OpenIdCheckAuthenticationRequestHandler @@ -34,24 +36,40 @@ class OpenIdCheckAuthenticationRequestHandler extends OpenIdMessageHandler private $association_service; private $nonce_service; + private $configuration_service; + private $openid_configuration_service; - public function __construct(IAssociationService $association_service, + /** + * @param IAssociationService $association_service + * @param INonceService $nonce_service + * @param ILogService $log_service + * @param ICheckPointService $checkpoint_service + * @param IServerConfigurationService $configuration_service + * @param IOpenIdServerConfigurationService $openid_configuration_service + * @param $successor + */ + public function __construct(IAssociationService $association_service, INonceService $nonce_service, ILogService $log_service, ICheckPointService $checkpoint_service, + IServerConfigurationService $configuration_service, + IOpenIdServerConfigurationService $openid_configuration_service, $successor) { parent::__construct($successor, $log_service, $checkpoint_service); - $this->association_service = $association_service; - $this->nonce_service = $nonce_service; + + $this->association_service = $association_service; + $this->nonce_service = $nonce_service; + $this->configuration_service = $configuration_service; + $this->openid_configuration_service = $openid_configuration_service; } protected function internalHandle(OpenIdMessage $message) { $this->current_request = null; try { - $this->current_request = new OpenIdCheckAuthenticationRequest($message); + $this->current_request = new OpenIdCheckAuthenticationRequest($message,$this->openid_configuration_service->getOPEndpointURL()); if (!$this->current_request->isValid()) throw new InvalidOpenIdMessageException(OpenIdErrorMessages::InvalidOpenIdCheckAuthenticationRequestMessage); @@ -76,6 +94,9 @@ class OpenIdCheckAuthenticationRequestHandler extends OpenIdMessageHandler $claimed_nonce = new OpenIdNonce($this->current_request->getNonce()); + if(!$claimed_nonce->isValid(intval($this->configuration_service->getConfigValue('Nonce.Lifetime')))) + throw new InvalidNonce(); + $this->nonce_service->lockNonce($claimed_nonce); $claimed_sig = $this->current_request->getSig(); diff --git a/app/libs/openid/handlers/OpenIdSessionAssociationRequestHandler.php b/app/libs/openid/handlers/OpenIdSessionAssociationRequestHandler.php index 53bfd25f..40a1edc8 100644 --- a/app/libs/openid/handlers/OpenIdSessionAssociationRequestHandler.php +++ b/app/libs/openid/handlers/OpenIdSessionAssociationRequestHandler.php @@ -22,7 +22,9 @@ use utils\services\ICheckPointService; class OpenIdSessionAssociationRequestHandler extends OpenIdMessageHandler { - public function __construct(ILogService $log,ICheckPointService $checkpoint_service, $successor) + public function __construct(ILogService $log, + ICheckPointService $checkpoint_service, + $successor) { parent::__construct($successor, $log,$checkpoint_service); } diff --git a/app/libs/openid/handlers/factories/SessionAssociationRequestFactory.php b/app/libs/openid/handlers/factories/SessionAssociationRequestFactory.php index 9e04c44a..260aed95 100644 --- a/app/libs/openid/handlers/factories/SessionAssociationRequestFactory.php +++ b/app/libs/openid/handlers/factories/SessionAssociationRequestFactory.php @@ -8,6 +8,9 @@ use openid\handlers\strategies\ISessionAssociationStrategy; use openid\OpenIdMessage; use openid\requests\OpenIdAssociationSessionRequest; use openid\requests\OpenIdDHAssociationSessionRequest; +use openid\services\OpenIdServiceCatalog; +use utils\services\ServiceLocator; +use utils\services\UtilsServiceCatalog; class SessionAssociationRequestFactory { @@ -25,10 +28,15 @@ class SessionAssociationRequestFactory */ public static function buildSessionAssociationStrategy(OpenIdMessage $message) { + + $association_service = ServiceLocator::getInstance()->getService(OpenIdServiceCatalog::AssociationService); + $configuration_service = ServiceLocator::getInstance()->getService(UtilsServiceCatalog::ServerConfigurationService); + $log_service = ServiceLocator::getInstance()->getService(UtilsServiceCatalog::LogService); + if (OpenIdDHAssociationSessionRequest::IsOpenIdDHAssociationSessionRequest($message)) - return new SessionAssociationDHStrategy(new OpenIdDHAssociationSessionRequest($message)); + return new SessionAssociationDHStrategy(new OpenIdDHAssociationSessionRequest($message),$association_service,$configuration_service,$log_service); if (OpenIdAssociationSessionRequest::IsOpenIdAssociationSessionRequest($message)) - return new SessionAssociationUnencryptedStrategy(new OpenIdAssociationSessionRequest($message)); + return new SessionAssociationUnencryptedStrategy(new OpenIdAssociationSessionRequest($message),$association_service,$configuration_service,$log_service); return null; } } \ No newline at end of file diff --git a/app/libs/openid/handlers/strategies/session_association/implementations/SessionAssociationDHStrategy.php b/app/libs/openid/handlers/strategies/session_association/implementations/SessionAssociationDHStrategy.php index 1c6f3517..b94b629a 100644 --- a/app/libs/openid/handlers/strategies/session_association/implementations/SessionAssociationDHStrategy.php +++ b/app/libs/openid/handlers/strategies/session_association/implementations/SessionAssociationDHStrategy.php @@ -8,10 +8,11 @@ use openid\helpers\OpenIdCryptoHelper; use openid\model\IAssociation; use openid\requests\OpenIdDHAssociationSessionRequest; use openid\responses\OpenIdDiffieHellmanAssociationSessionResponse; -use openid\services\OpenIdServiceCatalog; -use utils\services\ServiceLocator; -use utils\services\UtilsServiceCatalog; use Zend\Crypt\PublicKey\DiffieHellman; +//services +use openid\services\IAssociationService; +use openid\services\IServerConfigurationService; +use utils\services\ILogService; class SessionAssociationDHStrategy implements ISessionAssociationStrategy { @@ -19,17 +20,23 @@ class SessionAssociationDHStrategy implements ISessionAssociationStrategy private $association_service; private $server_configuration_service; private $current_request; - private $log; + private $log_service; - /** - * @param OpenIdDHAssociationSessionRequest $request - */ - public function __construct(OpenIdDHAssociationSessionRequest $request) + /** + * @param OpenIdDHAssociationSessionRequest $request + * @param IAssociationService $association_service + * @param IServerConfigurationService $server_configuration_service + * @param ILogService $log_service + */ + public function __construct(OpenIdDHAssociationSessionRequest $request, + IAssociationService $association_service, + IServerConfigurationService $server_configuration_service, + ILogService $log_service) { - $this->current_request = $request; - $this->association_service = ServiceLocator::getInstance()->getService(OpenIdServiceCatalog::AssociationService); - $this->server_configuration_service = ServiceLocator::getInstance()->getService(OpenIdServiceCatalog:: ServerConfigurationService); - $this->log = ServiceLocator::getInstance()->getService(UtilsServiceCatalog:: LogService); + $this->current_request = $request; + $this->association_service = $association_service; + $this->server_configuration_service = $server_configuration_service; + $this->log_service = $log_service; } /** @@ -64,14 +71,14 @@ class SessionAssociationDHStrategy implements ISessionAssociationStrategy } catch (InvalidDHParam $exDH) { $response = new OpenIdDirectGenericErrorResponse($exDH->getMessage()); - $this->log->error($exDH); + $this->log_service->error($exDH); } catch (InvalidArgumentException $exDH1) { $response = new OpenIdDirectGenericErrorResponse($exDH1->getMessage()); - $this->log->error($exDH1); + $this->log_service->error($exDH1); } catch (RuntimeException $exDH2) { $response = new OpenIdDirectGenericErrorResponse($exDH2->getMessage()); - $this->log->error($exDH2); + $this->log_service->error($exDH2); } return $response; } diff --git a/app/libs/openid/handlers/strategies/session_association/implementations/SessionAssociationUnencryptedStrategy.php b/app/libs/openid/handlers/strategies/session_association/implementations/SessionAssociationUnencryptedStrategy.php index 7bce66d1..b377fb76 100644 --- a/app/libs/openid/handlers/strategies/session_association/implementations/SessionAssociationUnencryptedStrategy.php +++ b/app/libs/openid/handlers/strategies/session_association/implementations/SessionAssociationUnencryptedStrategy.php @@ -10,12 +10,14 @@ use openid\model\IAssociation; use openid\requests\OpenIdAssociationSessionRequest; use openid\responses\OpenIdAssociationSessionResponse; use openid\responses\OpenIdUnencryptedAssociationSessionResponse; -use openid\services\OpenIdServiceCatalog; -use utils\services\ServiceLocator; -use utils\services\UtilsServiceCatalog; use Zend\Crypt\Exception\InvalidArgumentException; use Zend\Crypt\Exception\RuntimeException; +//services +use openid\services\IAssociationService; +use openid\services\IServerConfigurationService; +use utils\services\ILogService; + class SessionAssociationUnencryptedStrategy implements ISessionAssociationStrategy { @@ -24,12 +26,15 @@ class SessionAssociationUnencryptedStrategy implements ISessionAssociationStrate private $current_request; private $log_service; - public function __construct(OpenIdAssociationSessionRequest $request) + public function __construct(OpenIdAssociationSessionRequest $request, + IAssociationService $association_service, + IServerConfigurationService $server_configuration_service, + ILogService $log_service) { $this->current_request = $request; - $this->association_service = ServiceLocator::getInstance()->getService(OpenIdServiceCatalog::AssociationService); - $this->server_configuration_service = ServiceLocator::getInstance()->getService(OpenIdServiceCatalog:: ServerConfigurationService); - $this->log_service = ServiceLocator::getInstance()->getService(UtilsServiceCatalog:: LogService); + $this->association_service = $association_service; + $this->server_configuration_service = $server_configuration_service; + $this->log_service = $log_service; } /** diff --git a/app/libs/openid/helpers/OpenIdCryptoHelper.php b/app/libs/openid/helpers/OpenIdCryptoHelper.php index 136cfd00..1a218116 100644 --- a/app/libs/openid/helpers/OpenIdCryptoHelper.php +++ b/app/libs/openid/helpers/OpenIdCryptoHelper.php @@ -143,9 +143,9 @@ class OpenIdCryptoHelper return openssl_digest($data, $func, true); } else if (function_exists('hash')) { return hash($func, $data, true); - } else if ($func === 'sha1') { + } else if ($func == 'sha1') { return sha1($data, true); - } else if ($func === 'sha256') { + } else if ($func == 'sha256') { if (function_exists('mhash')) { return mhash(MHASH_SHA256, $data); } diff --git a/app/libs/openid/helpers/OpenIdSignatureBuilder.php b/app/libs/openid/helpers/OpenIdSignatureBuilder.php index 902e1b4f..43dab58d 100644 --- a/app/libs/openid/helpers/OpenIdSignatureBuilder.php +++ b/app/libs/openid/helpers/OpenIdSignatureBuilder.php @@ -56,7 +56,7 @@ class OpenIdSignatureBuilder $params = $context->getSignParams(); foreach ($params as $key) { - if (strpos($key, 'openid.') === 0) { + if (strpos($key, 'openid.') == 0) { $val = $response[$key]; $key = substr($key, strlen('openid.')); if (!empty($signed)) { diff --git a/app/libs/openid/model/OpenIdNonce.php b/app/libs/openid/model/OpenIdNonce.php index 494f9a09..8dadc07d 100644 --- a/app/libs/openid/model/OpenIdNonce.php +++ b/app/libs/openid/model/OpenIdNonce.php @@ -4,8 +4,6 @@ namespace openid\model; use openid\exceptions\InvalidNonce; use openid\helpers\OpenIdErrorMessages; -use utils\services\ServiceLocator; -use utils\services\UtilsServiceCatalog; class OpenIdNonce { @@ -39,7 +37,7 @@ class OpenIdNonce $timestamp = @gmmktime($tm_hour, $tm_min, $tm_sec, $tm_mon, $tm_mday, $tm_year); - if ($timestamp === false || $timestamp < 0) { + if ($timestamp == false || $timestamp < 0) { throw new InvalidNonce(sprintf(OpenIdErrorMessages::InvalidNonceTimestampMessage, $nonce_str)); } @@ -63,18 +61,18 @@ class OpenIdNonce return $this->$unique_id; } - /** - * The time-stamp MAY be used to reject responses that are too far away from the current time, - * limiting the amount of time that nonces must be stored to prevent attacks. - * The acceptable range is out of the scope of this specification. - * A larger range requires storing more nonces for a longer time. - * A shorter range increases the chance that clock-skew and transaction time will cause - * a spurious rejection. - */ - public function isValid() + /** + * The time-stamp MAY be used to reject responses that are too far away from the current time, + * limiting the amount of time that nonces must be stored to prevent attacks. + * The acceptable range is out of the scope of this specification. + * A larger range requires storing more nonces for a longer time. + * A shorter range increases the chance that clock-skew and transaction time will cause + * a spurious rejection. + * @param $allowed_skew + * @return bool + */ + public function isValid($allowed_skew) { - $server_configuration_service = ServiceLocator::getInstance()->getService(UtilsServiceCatalog::ServerConfigurationService); - $allowed_skew = $server_configuration_service->getConfigValue("Nonce.Lifetime"); $now = time(); // Time after which we should not use the nonce $past = $now - $allowed_skew; diff --git a/app/libs/openid/requests/OpenIdAuthenticationRequest.php b/app/libs/openid/requests/OpenIdAuthenticationRequest.php index dba68f95..887fae68 100644 --- a/app/libs/openid/requests/OpenIdAuthenticationRequest.php +++ b/app/libs/openid/requests/OpenIdAuthenticationRequest.php @@ -2,22 +2,32 @@ namespace openid\requests; +use openid\exceptions\InvalidOpenIdMessageException; use openid\helpers\OpenIdUriHelper; use openid\OpenIdMessage; use openid\OpenIdProtocol; - -use openid\services\OpenIdServiceCatalog; -use utils\services\ServiceLocator; -use Exception; - - +/** + * Class OpenIdAuthenticationRequest + * @package openid\requests + */ class OpenIdAuthenticationRequest extends OpenIdRequest { + private $user_identity_endpoint; - public function __construct(OpenIdMessage $message) + /** + * @param OpenIdMessage $message + * @param null $user_identity_endpoint + */ + public function __construct(OpenIdMessage $message, $user_identity_endpoint = null) { parent::__construct($message); + $this->user_identity_endpoint = $user_identity_endpoint; + if(!empty($this->user_identity_endpoint)){ + if(!str_contains($this->user_identity_endpoint,'@identifier')){ + throw new InvalidOpenIdMessageException("user_identity_endpoint value must contain @identifier placeholder!."); + } + } } public static function IsOpenIdAuthenticationRequest(OpenIdMessage $message) @@ -34,24 +44,24 @@ class OpenIdAuthenticationRequest extends OpenIdRequest public function isValid() { - $res = true; - try{ - $return_to = $this->getReturnTo(); - $claimed_id = $this->getClaimedId(); - $identity = $this->getIdentity(); - $mode = $this->getMode(); - $realm = $this->getRealm(); - $valid_realm = OpenIdUriHelper::checkRealm($realm, $return_to); - $valid_id = $this->isValidIdentifier($claimed_id, $identity); - $res = !empty($return_to) + $return_to = $this->getReturnTo(); + $claimed_id = $this->getClaimedId(); + $identity = $this->getIdentity(); + $mode = $this->getMode(); + $realm = $this->getRealm(); + $valid_id = $this->isValidIdentifier($claimed_id, $identity); + $valid_realm = OpenIdUriHelper::checkRealm($realm, $return_to); + + $res = !empty($return_to) && !empty($realm) && $valid_realm && !empty($claimed_id) && !empty($identity) && $valid_id && !empty($mode) && ($mode == OpenIdProtocol::ImmediateMode || $mode == OpenIdProtocol::SetupMode); - if(!$res){ + + if(!$res){ $msg = sprintf("return_to is empty? %b.",empty($return_to)).PHP_EOL; $msg = $msg.sprintf("realm is empty? %b.",empty($realm)).PHP_EOL; $msg = $msg.sprintf("claimed_id is empty? %b.",empty($claimed_id)).PHP_EOL; @@ -59,13 +69,9 @@ class OpenIdAuthenticationRequest extends OpenIdRequest $msg = $msg.sprintf("mode is empty? %b.",empty($mode)).PHP_EOL; $msg = $msg.sprintf("is valid realm? %b.",$valid_realm).PHP_EOL; $msg = $msg.sprintf("is valid identifier? %b.",$valid_id).PHP_EOL; - $this->log_service->warning_msg($msg); - } - } - catch(Exception $ex){ - $this->log_service->error($ex); - $res = false; + throw new InvalidOpenIdMessageException($msg); } + return $res; } @@ -100,12 +106,13 @@ class OpenIdAuthenticationRequest extends OpenIdRequest return false; } - /** - * @param $claimed_id The Claimed Identifier. - * @param $identity The OP-Local Identifier. - * @return bool - */ - private function isValidIdentifier($claimed_id, $identity) + /** + * @param $claimed_id + * @param $identity + * @return bool + * @throws \openid\exceptions\InvalidOpenIdMessageException + */ + private function isValidIdentifier($claimed_id, $identity) { /* * openid.claimed_id" and "openid.identity" SHALL be either both present or both absent. @@ -113,7 +120,9 @@ class OpenIdAuthenticationRequest extends OpenIdRequest * other information in its payload, using extensions. */ - $server_configuration_service = ServiceLocator::getInstance()->getService(OpenIdServiceCatalog::ServerConfigurationService); + if(empty($this->user_identity_endpoint)) + throw new InvalidOpenIdMessageException("user_identity_endpoint is not set"); + if (is_null($claimed_id) && is_null($identity)) return false; //http://specs.openid.net/auth/2.0/identifier_select @@ -121,7 +130,7 @@ class OpenIdAuthenticationRequest extends OpenIdRequest return true; if (OpenIdUriHelper::isValidUrl($claimed_id) && OpenIdUriHelper::isValidUrl($identity)) { - $identity_url_pattern = $server_configuration_service->getUserIdentityEndpointURL("@identifier"); + $identity_url_pattern = $this->user_identity_endpoint; $url_parts = explode("@", $identity_url_pattern, 2); $base_identity_url = $url_parts[0]; if (strpos($identity, $base_identity_url) !== false) diff --git a/app/libs/openid/requests/OpenIdCheckAuthenticationRequest.php b/app/libs/openid/requests/OpenIdCheckAuthenticationRequest.php index 6792eec3..0ac1c2d2 100644 --- a/app/libs/openid/requests/OpenIdCheckAuthenticationRequest.php +++ b/app/libs/openid/requests/OpenIdCheckAuthenticationRequest.php @@ -5,15 +5,20 @@ namespace openid\requests; use openid\helpers\OpenIdUriHelper; use openid\OpenIdMessage; use openid\OpenIdProtocol; -use openid\services\OpenIdServiceCatalog; -use utils\services\ServiceLocator; class OpenIdCheckAuthenticationRequest extends OpenIdAuthenticationRequest { - public function __construct(OpenIdMessage $message) + private $op_endpoint_url; + + /** + * @param OpenIdMessage $message + * @param $op_endpoint_url + */ + public function __construct(OpenIdMessage $message, $op_endpoint_url) { parent::__construct($message); + $this->op_endpoint_url = $op_endpoint_url; } public static function IsOpenIdCheckAuthenticationRequest(OpenIdMessage $message) @@ -35,22 +40,27 @@ class OpenIdCheckAuthenticationRequest extends OpenIdAuthenticationRequest $claimed_returnTo = $this->getReturnTo(); $signed = $this->getSigned(); - $server_configuration_service = ServiceLocator::getInstance()->getService(OpenIdServiceCatalog::ServerConfigurationService); + $valid_realm = OpenIdUriHelper::checkRealm($claimed_realm, $claimed_returnTo); - if ( - !is_null($mode) && !empty($mode) && $mode == OpenIdProtocol::CheckAuthenticationMode - && !is_null($claimed_returnTo) && !empty($claimed_returnTo) && OpenIdUriHelper::checkReturnTo($claimed_returnTo) - && !is_null($claimed_realm) && !empty($claimed_realm) && OpenIdUriHelper::checkRealm($claimed_realm, $claimed_returnTo) - && !is_null($claimed_assoc) && !empty($claimed_assoc) - && !is_null($claimed_sig) && !empty($claimed_sig) - && !is_null($signed) && !empty($signed) - && !is_null($claimed_nonce) && !empty($claimed_nonce) - && !is_null($claimed_op_endpoint) && !empty($claimed_op_endpoint) && $server_configuration_service->getOPEndpointURL() == $claimed_op_endpoint - && !is_null($claimed_identity) && !empty($claimed_identity) && OpenIdUriHelper::isValidUrl($claimed_identity) - ) { - return true; + $res = !is_null($mode) && !empty($mode) && $mode == OpenIdProtocol::CheckAuthenticationMode + && !is_null($claimed_returnTo) && !empty($claimed_returnTo) && OpenIdUriHelper::checkReturnTo($claimed_returnTo) + && !is_null($claimed_realm) && !empty($claimed_realm) && $valid_realm + && !is_null($claimed_assoc) && !empty($claimed_assoc) + && !is_null($claimed_sig) && !empty($claimed_sig) + && !is_null($signed) && !empty($signed) + && !is_null($claimed_nonce) && !empty($claimed_nonce) + && !is_null($claimed_op_endpoint) && !empty($claimed_op_endpoint) && $claimed_op_endpoint == $this->op_endpoint_url + && !is_null($claimed_identity) && !empty($claimed_identity) && OpenIdUriHelper::isValidUrl($claimed_identity); + if (!$res) { + $msg = sprintf("return_to is empty? %b.",empty($claimed_returnTo)).PHP_EOL; + $msg = $msg.sprintf("realm is empty? %b.",empty($claimed_realm)).PHP_EOL; + $msg = $msg.sprintf("claimed_id is empty? %b.",empty($claimed_id)).PHP_EOL; + $msg = $msg.sprintf("identity is empty? %b.",empty($claimed_identity)).PHP_EOL; + $msg = $msg.sprintf("mode is empty? %b.",empty($mode)).PHP_EOL; + $msg = $msg.sprintf("is valid realm? %b.",$valid_realm).PHP_EOL; + throw new InvalidOpenIdMessageException($msg); } - return false; + return $res; } public function getNonce() diff --git a/app/libs/openid/requests/OpenIdRequest.php b/app/libs/openid/requests/OpenIdRequest.php index c7d8dad7..c25f65af 100644 --- a/app/libs/openid/requests/OpenIdRequest.php +++ b/app/libs/openid/requests/OpenIdRequest.php @@ -3,19 +3,18 @@ namespace openid\requests; use openid\OpenIdMessage; -use utils\services\ServiceLocator; -use utils\services\UtilsServiceCatalog; +/** + * Class OpenIdRequest + * @package openid\requests + */ abstract class OpenIdRequest { protected $message; - protected $log_service; - public function __construct(OpenIdMessage $message) { $this->message = $message; - $this->log_service = ServiceLocator::getInstance()->getService(UtilsServiceCatalog::LogService); } public function getMessage() diff --git a/app/libs/utils/services/ServiceLocator.php b/app/libs/utils/services/ServiceLocator.php index 76b0b3a2..1f1f19de 100644 --- a/app/libs/utils/services/ServiceLocator.php +++ b/app/libs/utils/services/ServiceLocator.php @@ -13,7 +13,7 @@ class ServiceLocator { public static function getInstance() { - if (self::$instance === null) { + if (self::$instance == null) { self::$instance = new ServiceLocator(); } diff --git a/app/models/oauth2/AccessToken.php b/app/models/oauth2/AccessToken.php index b5f6d101..8dc44460 100644 --- a/app/models/oauth2/AccessToken.php +++ b/app/models/oauth2/AccessToken.php @@ -27,7 +27,7 @@ class AccessToken extends Eloquent { public function isVoid(){ //check lifetime... $created_at = $this->created_at; - $created_at->add(new DateInterval('PT' . $this->lifetime . 'S')); + $created_at->add(new DateInterval('PT' . intval($this->lifetime) . 'S')); $now = new DateTime(gmdate("Y-m-d H:i:s", time())); return ($now > $created_at); } @@ -43,9 +43,9 @@ class AccessToken extends Eloquent { public function getRemainingLifetime() { //check is refresh token is stills alive... (ZERO is infinite lifetime) - if ($this->lifetime === 0) return 0; + if (intval($this->lifetime) == 0) return 0; $created_at = new DateTime($this->created_at); - $created_at->add(new DateInterval('PT' . $this->lifetime . 'S')); + $created_at->add(new DateInterval('PT' . intval($this->lifetime) . 'S')); $now = new DateTime(gmdate("Y-m-d H:i:s", time())); //check validity... if ($now > $created_at) diff --git a/app/models/oauth2/Client.php b/app/models/oauth2/Client.php index 7ff021a1..0e51510a 100644 --- a/app/models/oauth2/Client.php +++ b/app/models/oauth2/Client.php @@ -116,7 +116,7 @@ class Client extends BaseModelEloquent implements IClient { { if(!filter_var($uri, FILTER_VALIDATE_URL)) return false; $parts = @parse_url($uri); - if ($parts === false) { + if ($parts == false) { return false; } if($parts['scheme']!=='https') @@ -227,7 +227,7 @@ class Client extends BaseModelEloquent implements IClient { { if(!filter_var($origin, FILTER_VALIDATE_URL)) return false; $parts = @parse_url($origin); - if ($parts === false) { + if ($parts == false) { return false; } if($parts['scheme']!=='https') diff --git a/app/models/oauth2/RefreshToken.php b/app/models/oauth2/RefreshToken.php index 017c0ea9..cdd064f7 100644 --- a/app/models/oauth2/RefreshToken.php +++ b/app/models/oauth2/RefreshToken.php @@ -26,10 +26,10 @@ class RefreshToken extends Eloquent { } public function isVoid(){ - if($this->lifetime === 0) return false; + if(intval($this->lifetime) == 0) return false; //check lifetime... $created_at = $this->created_at; - $created_at->add(new DateInterval('PT' . $this->lifetime . 'S')); + $created_at->add(new DateInterval('PT' . intval($this->lifetime) . 'S')); $now = new DateTime(gmdate("Y-m-d H:i:s", time())); return ($now > $created_at); } @@ -38,9 +38,9 @@ class RefreshToken extends Eloquent { public function getRemainingLifetime() { //check is refresh token is stills alive... (ZERO is infinite lifetime) - if ($this->lifetime === 0) return 0; + if (intval($this->lifetime) == 0) return 0; $created_at = new DateTime($this->created_at); - $created_at->add(new DateInterval('PT' . $this->lifetime . 'S')); + $created_at->add(new DateInterval('PT' . intval($this->lifetime) . 'S')); $now = new DateTime(gmdate("Y-m-d H:i:s", time())); //check validity... if ($now > $created_at) diff --git a/app/models/openid/OpenIdAssociation.php b/app/models/openid/OpenIdAssociation.php index c4e4f5b8..bf996f0a 100644 --- a/app/models/openid/OpenIdAssociation.php +++ b/app/models/openid/OpenIdAssociation.php @@ -30,7 +30,7 @@ class OpenIdAssociation extends Eloquent implements IAssociation public function getLifetime() { - return $this->lifetime; + return intval($this->lifetime); } public function setLifetime($lifetime) @@ -76,7 +76,7 @@ class OpenIdAssociation extends Eloquent implements IAssociation public function getRemainingLifetime() { $created_at = new DateTime($this->issued); - $created_at->add(new DateInterval('PT' . $this->lifetime . 'S')); + $created_at->add(new DateInterval('PT' . intval($this->lifetime) . 'S')); $now = new DateTime(gmdate("Y-m-d H:i:s", time())); //check validity... if ($now > $created_at) diff --git a/app/services/oauth2/ApiEndpointService.php b/app/services/oauth2/ApiEndpointService.php index 2a32af3a..c9a855b3 100644 --- a/app/services/oauth2/ApiEndpointService.php +++ b/app/services/oauth2/ApiEndpointService.php @@ -195,7 +195,7 @@ class ApiEndpointService implements IApiEndpointService { $res = $api_endpoint->scopes()->where('id','=',$scope_id)->count(); - if($res===0) + if($res==0) throw new InvalidApiScope(sprintf("api scope id %s does not belongs to endpoint id %s !.",$scope_id,$api_endpoint->id)); $api_endpoint->scopes()->detach($scope_id); diff --git a/app/services/oauth2/ApiService.php b/app/services/oauth2/ApiService.php index 13087a49..94473973 100644 --- a/app/services/oauth2/ApiService.php +++ b/app/services/oauth2/ApiService.php @@ -53,7 +53,7 @@ class ApiService implements IApiService { { $instance = null; if(is_string($active)){ - $active = $active==='true'?true:false; + $active = strtoupper($active) == 'TRUE'?true:false; } DB::transaction(function () use ($name, $description, $active, $resource_server_id, &$instance) { diff --git a/app/services/oauth2/AuthorizationCodeRedeemPolicy.php b/app/services/oauth2/AuthorizationCodeRedeemPolicy.php index cf5aa986..8c9f1782 100644 --- a/app/services/oauth2/AuthorizationCodeRedeemPolicy.php +++ b/app/services/oauth2/AuthorizationCodeRedeemPolicy.php @@ -35,7 +35,7 @@ class AuthorizationCodeRedeemPolicy extends AbstractBlacklistSecurityPolicy { { try { $exception_class = get_class($ex); - if($exception_class === 'oauth2\exceptions\ReplayAttackException'){ + if($exception_class == 'oauth2\exceptions\ReplayAttackException'){ $auth_code = $ex->getAuthCode(); $this->counter_measure->trigger(array('auth_code'=>$auth_code)); } diff --git a/app/services/oauth2/CORS/CORSMiddleware.php b/app/services/oauth2/CORS/CORSMiddleware.php index 5bedc0f1..9d42070f 100644 --- a/app/services/oauth2/CORS/CORSMiddleware.php +++ b/app/services/oauth2/CORS/CORSMiddleware.php @@ -185,7 +185,7 @@ class CORSMiddleware { $preflight = false; //preflight checks - if ($method === 'OPTIONS') { + if ($method == 'OPTIONS') { $request_method = $request->headers->get('Access-Control-Request-Method'); if(!is_null($request_method)){ // sets the original method on request in order to be able to find the diff --git a/app/services/oauth2/ClientService.php b/app/services/oauth2/ClientService.php index c8f360f3..3a7cc52c 100644 --- a/app/services/oauth2/ClientService.php +++ b/app/services/oauth2/ClientService.php @@ -19,11 +19,10 @@ use oauth2\services\IApiScopeService; use oauth2\services\IApiScope; use oauth2\services\IClientService; use oauth2\services\id; -use oauth2\services\OAuth2ServiceCatalog; use Request; use utils\services\IAuthService; -use utils\services\ServiceLocator; use Zend\Math\Rand; +use Event; /** * Class ClientService @@ -176,8 +175,7 @@ class ClientService implements IClientService if (!is_null($client)) { $client->authorized_uris()->delete(); $client->scopes()->detach(); - $token_service = ServiceLocator::getInstance()->getService(OAuth2ServiceCatalog::TokenService); - $token_service->revokeClientRelatedTokens($client->client_id); + Event::fire('oauth2.client.delete', array($client->client_id)); $res = $client->delete(); } }); @@ -205,8 +203,7 @@ class ClientService implements IClientService $client_secret = Rand::getString(24, OAuth2Protocol::VsChar, true); $client->client_secret = $client_secret; $client->Save(); - $token_service = ServiceLocator::getInstance()->getService(OAuth2ServiceCatalog::TokenService); - $token_service->revokeClientRelatedTokens($client->client_id); + Event::fire('oauth2.client.regenerate.secret', array($client->client_id)); $new_secret = $client->client_secret; }); diff --git a/app/services/oauth2/MementoOAuth2AuthenticationRequestService.php b/app/services/oauth2/MementoOAuth2AuthenticationRequestService.php index 2420fa7b..1c1e58db 100644 --- a/app/services/oauth2/MementoOAuth2AuthenticationRequestService.php +++ b/app/services/oauth2/MementoOAuth2AuthenticationRequestService.php @@ -21,7 +21,7 @@ class MementoOAuth2AuthenticationRequestService implements IMementoOAuth2Authent $input = Input::all(); $oauth2_params = array(); foreach ($input as $key => $value) { - if (array_key_exists($key, OAuth2AuthorizationRequest::$params) === true) { + if (array_key_exists($key, OAuth2AuthorizationRequest::$params) == true) { array_push($oauth2_params, $key); } } @@ -33,7 +33,7 @@ class MementoOAuth2AuthenticationRequestService implements IMementoOAuth2Authent $old_data = Input::old(); $oauth2_params = array(); foreach ($old_data as $key => $value) { - if (array_key_exists($key, OAuth2AuthorizationRequest::$params) === true) { + if (array_key_exists($key, OAuth2AuthorizationRequest::$params) == true) { array_push($oauth2_params, $key); } } @@ -59,7 +59,7 @@ class MementoOAuth2AuthenticationRequestService implements IMementoOAuth2Authent $old_data = Input::old(); $oauth2_params = array(); foreach ($old_data as $key => $value) { - if (array_key_exists($key, OAuth2AuthorizationRequest::$params) === true) { + if (array_key_exists($key, OAuth2AuthorizationRequest::$params) == true) { $oauth2_params[$key] = $value; } } @@ -76,7 +76,7 @@ class MementoOAuth2AuthenticationRequestService implements IMementoOAuth2Authent $oauth2_params = array(); foreach ($old_data as $key => $value) { - if (array_key_exists($key, OAuth2AuthorizationRequest::$params) === true){ + if (array_key_exists($key, OAuth2AuthorizationRequest::$params) == true){ array_push($oauth2_params, $key); } } diff --git a/app/services/oauth2/ResourceServerService.php b/app/services/oauth2/ResourceServerService.php index 01b51e93..8a8c373e 100644 --- a/app/services/oauth2/ResourceServerService.php +++ b/app/services/oauth2/ResourceServerService.php @@ -145,7 +145,7 @@ class ResourceServerService implements IResourceServerService { $client_service = $this->client_service; if(is_string($active)){ - $active = $active ==='true'?true:false; + $active = strtoupper($active) =='TRUE' ?true:false; } DB::transaction(function () use ($host, $ip, $friendly_name, $active, &$instance, &$client_service) { diff --git a/app/services/oauth2/RevokeAuthorizationCodeRelatedTokens.php b/app/services/oauth2/RevokeAuthorizationCodeRelatedTokens.php index f02e1222..07fbb38b 100644 --- a/app/services/oauth2/RevokeAuthorizationCodeRelatedTokens.php +++ b/app/services/oauth2/RevokeAuthorizationCodeRelatedTokens.php @@ -4,8 +4,7 @@ namespace services\oauth2; use Exception; use Log; -use oauth2\services\OAuth2ServiceCatalog; -use utils\services\ServiceLocator; +use oauth2\services\ITokenService; use utils\services\ISecurityPolicyCounterMeasure; @@ -22,23 +21,22 @@ use utils\services\ISecurityPolicyCounterMeasure; */ class RevokeAuthorizationCodeRelatedTokens implements ISecurityPolicyCounterMeasure { + + private $token_service; + + /** + * @param ITokenService $token_service + */ + public function __construct(ITokenService $token_service){ + $this->token_service = $token_service; + } + public function trigger(array $params = array()) { try { - if (!isset($params["auth_code"])) return; - //if (!isset($params["client_id"])) return; - $auth_code = $params["auth_code"]; - //$client_id = $params["client_id"]; - - $token_service = ServiceLocator::getInstance()->getService(OAuth2ServiceCatalog::TokenService); - //$client_service = ServiceLocator::getInstance()->getService(OAuth2ServiceCatalog::ClientService); - - $token_service->revokeAuthCodeRelatedTokens($auth_code); - - //$client_service->lockClient($client_id); - + $this->token_service->revokeAuthCodeRelatedTokens($auth_code); } catch (Exception $ex) { Log::error($ex); } diff --git a/app/services/oauth2/TokenService.php b/app/services/oauth2/TokenService.php index a1f459d0..c6f57d0d 100644 --- a/app/services/oauth2/TokenService.php +++ b/app/services/oauth2/TokenService.php @@ -32,6 +32,8 @@ use Zend\Crypt\Hash; use utils\services\ICacheService; use utils\services\IAuthService; + +use Event; /** * Class TokenService * Provides all Tokens related operations (create, get and revoke) @@ -68,6 +70,18 @@ class TokenService implements ITokenService $this->cache_service = $cache_service; $this->auth_service = $auth_service; $this->user_consent_service = $user_consent_service; + + $this_var = $this; + + Event::listen('oauth2.client.delete', function($client_id) use (&$this_var) + { + $this_var->revokeClientRelatedTokens($client_id); + }); + + Event::listen('oauth2.client.regenerate.secret', function($client_id) use (&$this_var) + { + $this_var->revokeClientRelatedTokens($client_id); + }); } /** @@ -410,7 +424,7 @@ class TokenService implements ITokenService 'audience' => $access_token->audience, 'refresh_token' => $refresh_token_value ) - ,$access_token->lifetime); + ,intval($access_token->lifetime)); } @@ -596,7 +610,7 @@ class TokenService implements ITokenService 'from_ip' => $refresh_token_db->from_ip, 'issued' => $refresh_token_db->created_at, 'is_hashed' => $is_hashed - ), $refresh_token_db->lifetime); + ), intval($refresh_token_db->lifetime)); return $refresh_token; } diff --git a/app/services/oauth2/resource_server/UserService.php b/app/services/oauth2/resource_server/UserService.php index a566b7fb..f4fd9268 100644 --- a/app/services/oauth2/resource_server/UserService.php +++ b/app/services/oauth2/resource_server/UserService.php @@ -8,7 +8,7 @@ use oauth2\IResourceServerContext; use utils\services\ILogService; use openid\services\IUserService as IAPIUserService; use Exception; - +use utils\services\IServerConfigurationService; /** * Class UserService * OAUTH2 Protected Endpoint @@ -17,10 +17,15 @@ use Exception; class UserService extends OAuth2ProtectedService implements IUserService { private $user_service; + private $configuration_service; - public function __construct(IAPIUserService $user_service, IResourceServerContext $resource_server_context, ILogService $log_service){ + public function __construct(IAPIUserService $user_service, + IResourceServerContext $resource_server_context, + IServerConfigurationService $configuration_service, + ILogService $log_service){ parent::__construct($resource_server_context,$log_service); - $this->user_service = $user_service; + $this->user_service = $user_service; + $this->configuration_service = $configuration_service; } /** @@ -52,10 +57,13 @@ class UserService extends OAuth2ProtectedService implements IUserService { } if(in_array(self::UserProfileScope_Profile, $scopes)){ // Address Claim - $data['name'] = $current_user->getFirstName(); + $assets_url = $this->configuration_service->getConfigValue('Assets.Url'); + $pic_url = $current_user->getPic(); + $pic_url = str_contains($pic_url,'http')?$pic_url:$assets_url.$pic_url; + $data['name'] = $current_user->getFirstName(); $data['family_name'] = $current_user->getLastName(); $data['nickname'] = $current_user->getNickName(); - $data['picture'] = $current_user->getPic(); + $data['picture'] = $pic_url; $data['birthdate'] = $current_user->getDateOfBirth(); $data['gender'] = $current_user->getGender(); } diff --git a/app/services/openid/AssociationService.php b/app/services/openid/AssociationService.php index 01d557b1..cfc6d6d3 100644 --- a/app/services/openid/AssociationService.php +++ b/app/services/openid/AssociationService.php @@ -67,8 +67,7 @@ class AssociationService implements IAssociationService "mac_function" => $assoc->mac_function, "issued" => $assoc->issued, "lifetime" => $assoc->lifetime, - //"secret" => \bin2hex($assoc->secret), - "secret" => \unpack('H*',$secret_unpack ), + "secret" => \unpack('H*',$secret_unpack ), "realm" => $assoc->realm), $remaining_lifetime); } @@ -96,8 +95,7 @@ class AssociationService implements IAssociationService $assoc->type = $cache_values['type']; $assoc->mac_function = $cache_values['mac_function']; $assoc->issued = $cache_values['issued']; - $assoc->lifetime = $cache_values['lifetime']; - //$assoc->secret = \hex2bin($cache_values['secret']); + $assoc->lifetime = intval($cache_values['lifetime']); $assoc->secret = $secret; $realm = $cache_values['realm']; if (!empty($realm)) @@ -146,7 +144,7 @@ class AssociationService implements IAssociationService $assoc->secret = $secret; $assoc->type = $type; $assoc->mac_function = $mac_function; - $assoc->lifetime = $lifetime; + $assoc->lifetime = intval($lifetime); $assoc->issued = $issued; if (!is_null($realm)) @@ -159,14 +157,14 @@ class AssociationService implements IAssociationService if (is_null($realm)) $realm = ''; - $secret_unpack = \unpack('H*', $secret); + $secret_unpack = \unpack('H*', $secret); $secret_unpack = array_shift($secret_unpack); + $this->cache_service->storeHash($handle, array( "type" => $type, "mac_function" => $mac_function, "issued" => $issued, "lifetime" => $lifetime, - //"secret" => \bin2hex($secret), "secret" => $secret_unpack, "realm" => $realm),$lifetime); diff --git a/app/services/openid/ServerExtensionsService.php b/app/services/openid/ServerExtensionsService.php index b39e3054..e5b3fe93 100644 --- a/app/services/openid/ServerExtensionsService.php +++ b/app/services/openid/ServerExtensionsService.php @@ -4,24 +4,47 @@ namespace services\openid; use openid\services\IServerExtensionsService; use utils\services\ServiceLocator; -use utils\services\UtilsServiceCatalog; use ServerExtension; +use ReflectionClass; +/** + * Class ServerExtensionsService + * @package services\openid + */ class ServerExtensionsService implements IServerExtensionsService { - public function getAllActiveExtensions() + /** + * @return array + */ + public function getAllActiveExtensions() { $extensions = ServerExtension::where('active', '=', true)->get(); $res = array(); foreach ($extensions as $extension) { - $class = $extension->extension_class; - if (empty($class) /*|| !class_exists($class)*/) continue; - $implementation = new $class($extension->name, - $extension->namespace, - $extension->view_name, - $extension->description, - ServiceLocator::getInstance()->getService(UtilsServiceCatalog::LogService)); + $class_name = $extension->extension_class; + if (empty($class_name)) continue; + + $class = new ReflectionClass($class_name); + $constructor = $class->getConstructor(); + $constructor_params = $constructor->getParameters(); + + $deps = array(); + + foreach($constructor_params as $constructor_param){ + $param_class = $constructor_param->getClass(); + $name = $constructor_param->getName(); + if(is_null($param_class)){ + array_push($deps,$extension->$name); + } + else{ + $service = ServiceLocator::getInstance()->getService($param_class->getName()); + array_push($deps,$service); + } + } + + $implementation = $class->newInstanceArgs($deps); + array_push($res, $implementation); } return $res; diff --git a/app/services/security_policies/LockUserCounterMeasure.php b/app/services/security_policies/LockUserCounterMeasure.php index e0d51063..f839f670 100644 --- a/app/services/security_policies/LockUserCounterMeasure.php +++ b/app/services/security_policies/LockUserCounterMeasure.php @@ -5,12 +5,19 @@ namespace services; use auth\User; use Exception; use Log; -use openid\services\OpenIdServiceCatalog; -use utils\services\ServiceLocator; +use openid\services\IUserService; +use utils\services\IServerConfigurationService; use utils\services\ISecurityPolicyCounterMeasure; class LockUserCounterMeasure implements ISecurityPolicyCounterMeasure { + private $server_configuration; + private $user_service; + + public function __construct(IUserService $user_service, IServerConfigurationService $server_configuration){ + $this->user_service = $user_service; + $this->server_configuration = $server_configuration; + } public function trigger(array $params = array()) { @@ -18,17 +25,15 @@ class LockUserCounterMeasure implements ISecurityPolicyCounterMeasure if (!isset($params["user_identifier"])) return; $user_identifier = $params["user_identifier"]; - $server_configuration = ServiceLocator::getInstance()->getService(OpenIdServiceCatalog::ServerConfigurationService); - $user_service = ServiceLocator::getInstance()->getService(OpenIdServiceCatalog::UserService); $user = User::where('external_id', '=', $user_identifier)->first(); if(is_null($user)) return; //apply lock policy - if (intval($user->login_failed_attempt) < intval($server_configuration->getConfigValue("MaxFailed.Login.Attempts"))) - $user_service->updateFailedLoginAttempts($user->id); + if (intval($user->login_failed_attempt) < intval($this->server_configuration->getConfigValue("MaxFailed.Login.Attempts"))) + $this->user_service->updateFailedLoginAttempts($user->id); else { - $user_service->lockUser($user->id); + $this->user_service->lockUser($user->id); } } catch (Exception $ex) { Log::error($ex); diff --git a/app/services/security_policies/OAuth2LockClientCounterMeasure.php b/app/services/security_policies/OAuth2LockClientCounterMeasure.php index b3628613..1a8846b4 100644 --- a/app/services/security_policies/OAuth2LockClientCounterMeasure.php +++ b/app/services/security_policies/OAuth2LockClientCounterMeasure.php @@ -4,26 +4,29 @@ namespace services; use Exception; use Log; -use oauth2\services\OAuth2ServiceCatalog; -use utils\services\ServiceLocator; +use oauth2\services\IClientService; use utils\services\ISecurityPolicyCounterMeasure; -use Client as OAuth2Client; class OAuth2LockClientCounterMeasure implements ISecurityPolicyCounterMeasure{ + + private $client_service; + + public function __construct(IClientService $client_service){ + $this->client_service = $client_service; + } + public function trigger(array $params = array()) { try{ if (!isset($params["client_id"])) return; $client_id = $params['client_id']; - - $client_service = ServiceLocator::getInstance()->getService(OAuth2ServiceCatalog::ClientService); - $client = OAuth2Client::where('id', '=', client_id)->first(); + $client = $this->client_service->getClientByIdentifier($client_id); if(is_null($client)) return; //apply lock policy - $client_service->lockClient($client->id); + $this->client_service->lockClient($client->id); } catch(Exception $ex){ Log::error($ex); diff --git a/app/services/security_policies/OAuth2SecurityPolicy.php b/app/services/security_policies/OAuth2SecurityPolicy.php index 913cf805..c9a902ad 100644 --- a/app/services/security_policies/OAuth2SecurityPolicy.php +++ b/app/services/security_policies/OAuth2SecurityPolicy.php @@ -5,6 +5,7 @@ namespace services; use DB; use Exception; use Log; +use oauth2\services\IClientService; use oauth2\services\OAuth2ServiceCatalog; use utils\services\ISecurityPolicy; use utils\services\ISecurityPolicyCounterMeasure; @@ -24,10 +25,11 @@ class OAuth2SecurityPolicy implements ISecurityPolicy{ private $server_configuration_service; private $client_service; - public function __construct(IServerConfigurationService $server_configuration_service) + public function __construct(IServerConfigurationService $server_configuration_service, IClientService $client_service) { $this->server_configuration_service = $server_configuration_service; - ; + $this->client_service = $client_service; + $this->exception_dictionary = array( 'auth2\exceptions\BearerTokenDisclosureAttemptException' => array('OAuth2SecurityPolicy.MaxBearerTokenDisclosureAttempts'), 'auth2\exceptions\InvalidClientException' => array('OAuth2SecurityPolicy.MaxInvalidClientExceptionAttempts'), @@ -53,7 +55,6 @@ class OAuth2SecurityPolicy implements ISecurityPolicy{ { try { if(get_parent_class($ex)=='oauth2\\exceptions\\OAuth2ClientBaseException'){ - $this->client_service = ServiceLocator::getInstance()->getService(OAuth2ServiceCatalog::ClientService); $client_id = $ex->getClientId(); //save oauth2 exception by client id if (!is_null($client_id) && !empty($client_id)){ diff --git a/app/strategies/IndirectResponseQueryStringStrategy.php b/app/strategies/IndirectResponseQueryStringStrategy.php index 39d2561b..302e369f 100644 --- a/app/strategies/IndirectResponseQueryStringStrategy.php +++ b/app/strategies/IndirectResponseQueryStringStrategy.php @@ -27,7 +27,7 @@ class IndirectResponseQueryStringStrategy implements IHttpResponseStrategy if (is_null($return_to) || empty($return_to)) { return \View::make('404'); } - $return_to = (strpos($return_to, "?") === false) ? $return_to . "?" . $query_string : $return_to . "&" . $query_string; + $return_to = (strpos($return_to, "?") == false) ? $return_to . "?" . $query_string : $return_to . "&" . $query_string; return Redirect::to($return_to); } } \ No newline at end of file diff --git a/app/strategies/IndirectResponseUrlFragmentStrategy.php b/app/strategies/IndirectResponseUrlFragmentStrategy.php index 5e9a02c9..779c50ea 100644 --- a/app/strategies/IndirectResponseUrlFragmentStrategy.php +++ b/app/strategies/IndirectResponseUrlFragmentStrategy.php @@ -27,7 +27,7 @@ class IndirectResponseUrlFragmentStrategy implements IHttpResponseStrategy return \View::make('404'); } - $return_to = (strpos($return_to, "#") === false) ? $return_to . "#" . $fragment : $return_to . "&" . $fragment; + $return_to = (strpos($return_to, "#") == false) ? $return_to . "#" . $fragment : $return_to . "&" . $fragment; return Redirect::to($return_to); } } \ No newline at end of file diff --git a/app/tests/OAuth2UserServiceApiTest.php b/app/tests/OAuth2UserServiceApiTest.php index abe533a8..85be5bca 100644 --- a/app/tests/OAuth2UserServiceApiTest.php +++ b/app/tests/OAuth2UserServiceApiTest.php @@ -22,6 +22,12 @@ class OAuth2UserServiceApiTest extends TestCase { $this->current_realm = Config::get('app.url'); + $user = User::where('external_id', '=', 'smarcet@gmail.com')->first(); + + $this->be($user); + + Session::start(); + $scope = array( IUserService::UserProfileScope_Address, IUserService::UserProfileScope_Email, @@ -39,9 +45,6 @@ class OAuth2UserServiceApiTest extends TestCase { OAuth2Protocol::OAuth2Protocol_AccessType =>OAuth2Protocol::OAuth2Protocol_AccessType_Offline, ); - $user = User::where('external_id', '=', 'smarcet@gmail.com')->first(); - - Auth::login($user); Session::set("openid.authorization.response", IAuthService::AuthorizationResponse_AllowOnce); diff --git a/app/validators/CustomValidator.php b/app/validators/CustomValidator.php index b1acf8a8..97ed08ce 100644 --- a/app/validators/CustomValidator.php +++ b/app/validators/CustomValidator.php @@ -23,7 +23,7 @@ class CustomValidator extends Validator { return true; if(is_int($value)) return true; - return strtoupper(trim($value))==='TRUE' || strtoupper(trim($value))==='FALSE' || strtoupper(trim($value))==='1' || strtoupper(trim($value))==='0' ; + return strtoupper(trim($value)) =='TRUE' || strtoupper(trim($value))=='FALSE' || strtoupper(trim($value))=='1' || strtoupper(trim($value))=='0' ; } public function validateText($attribute, $value, $parameters) @@ -81,11 +81,11 @@ class CustomValidator extends Validator { if(filter_var($value, FILTER_VALIDATE_URL)){ $parts = @parse_url($value); - if ($parts === false) { + if ($parts == false) { return false; } - if($parts['scheme']!=='https') + if($parts['scheme']!= 'https') return false; if(isset($parts['query']))