From 1c8bb7551dd59ef869f105f8aba7b560b35756ce Mon Sep 17 00:00:00 2001 From: harshanl Date: Wed, 7 Oct 2015 23:15:17 +0530 Subject: [PATCH 01/23] Refactored Dynamic-client registration service to use AppMgt osgi service --- .../webapp/publisher/APIPublisherUtil.java | 3 +- .../pom.xml | 5 +- .../impl/DynamicClientRegistrationImpl.java | 17 ++-- ...amicClientRegistrationBundleActivator.java | 48 ----------- .../DynamicClientRegistrationDataHolder.java | 51 +++++++++++ ...micClientRegistrationServiceComponent.java | 85 +++++++++++++++++++ ...ava => PermissionBasedScopeValidator.java} | 8 +- 7 files changed, 157 insertions(+), 60 deletions(-) delete mode 100644 components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationBundleActivator.java create mode 100644 components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationDataHolder.java create mode 100644 components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java rename components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/{ScopeValidator.java => PermissionBasedScopeValidator.java} (92%) diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java index 8a2f782da59..533a7fc2dcf 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java @@ -67,7 +67,8 @@ public class APIPublisherUtil { api.setEndpointSecured(true); api.setStatus(APIStatus.PUBLISHED); api.setTransports(config.getTransports()); - + api.setAsDefaultVersion(true); + api.setAsPublishedDefaultVersion(true); return api; } diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/pom.xml b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/pom.xml index 51bce89c192..b2d8ec58b90 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/pom.xml +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/pom.xml @@ -36,6 +36,10 @@ + + org.apache.felix + maven-scr-plugin + org.apache.felix maven-bundle-plugin @@ -47,7 +51,6 @@ ${project.artifactId} ${carbon.device.mgt.version} Dynamic Client Registration Bundle - org.wso2.carbon.dynamic.client.registration.internal.DynamicClientRegistrationBundleActivator org.wso2.carbon.dynamic.client.registration.internal !org.wso2.carbon.dynamic.client.registration.internal, diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationImpl.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationImpl.java index fa8c10d1c6d..339a0d32f26 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationImpl.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationImpl.java @@ -25,6 +25,7 @@ import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.RegistryType; import org.wso2.carbon.dynamic.client.registration.*; +import org.wso2.carbon.dynamic.client.registration.internal.DynamicClientRegistrationDataHolder; import org.wso2.carbon.dynamic.client.registration.profile.RegistrationProfile; import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; import org.wso2.carbon.identity.application.common.model.*; @@ -153,7 +154,8 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS serviceProvider.setDescription("Service Provider for application " + applicationName); - ApplicationManagementService appMgtService = ApplicationManagementService.getInstance(); + ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder. + getInstance().getApplicationManagementService(); if (appMgtService == null) { throw new IllegalStateException( "Error occurred while retrieving Application Management" + @@ -164,7 +166,7 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS applicationName, tenantDomain); if (existingServiceProvider == null) { - appMgtService.createApplication(serviceProvider, userName, tenantDomain); + appMgtService.createApplication(serviceProvider, tenantDomain, userName); } ServiceProvider createdServiceProvider = appMgtService.getServiceProvider( @@ -324,7 +326,8 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS try { oAuthAdminService.removeOAuthApplicationData(consumerKey); - ApplicationManagementService appMgtService = ApplicationManagementService.getInstance(); + ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder. + getInstance().getApplicationManagementService(); if (appMgtService == null) { throw new IllegalStateException( @@ -357,15 +360,17 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS @Override public boolean isOAuthApplicationExists(String applicationName) throws DynamicClientRegistrationException { - ApplicationManagementService appMgtService = ApplicationManagementService.getInstance(); + ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder. + getInstance().getApplicationManagementService(); if (appMgtService == null) { throw new IllegalStateException( "Error occurred while retrieving Application Management" + "Service"); } try { - if (ApplicationManagementService.getInstance().getServiceProvider(applicationName, - CarbonContext.getThreadLocalCarbonContext().getTenantDomain()) != null) { + if (appMgtService.getServiceProvider(applicationName, + CarbonContext.getThreadLocalCarbonContext() + .getTenantDomain()) != null) { return true; } } catch (IdentityApplicationManagementException e) { diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationBundleActivator.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationBundleActivator.java deleted file mode 100644 index a5ba8ecb2b4..00000000000 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationBundleActivator.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * you may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.dynamic.client.registration.internal; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService; -import org.wso2.carbon.dynamic.client.registration.impl.DynamicClientRegistrationImpl; - -/** - * BundleActivator class of DynamicClientRegistration component. - */ -public class DynamicClientRegistrationBundleActivator implements BundleActivator{ - - private static final Log log = LogFactory.getLog(DynamicClientRegistrationBundleActivator.class); - - @Override - public void start(BundleContext bundleContext) throws Exception { - DynamicClientRegistrationService dynamicClientRegistrationService = - new DynamicClientRegistrationImpl(); - bundleContext.registerService(DynamicClientRegistrationService.class.getName(), - dynamicClientRegistrationService, null); - } - - @Override - public void stop(BundleContext bundleContext) throws Exception { - - } - -} diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationDataHolder.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationDataHolder.java new file mode 100644 index 00000000000..63bda3e3379 --- /dev/null +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationDataHolder.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.dynamic.client.registration.internal; + +import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; + +/** + * DataHolder class of DynamicClientRegistration bundle. This hold a reference to + * ApplicationManagementService. + */ +public class DynamicClientRegistrationDataHolder { + + private ApplicationManagementService applicationManagementService; + + private static DynamicClientRegistrationDataHolder thisInstance = + new DynamicClientRegistrationDataHolder(); + + private DynamicClientRegistrationDataHolder() { + } + + public static DynamicClientRegistrationDataHolder getInstance() { + return thisInstance; + } + + public ApplicationManagementService getApplicationManagementService() { + if (applicationManagementService == null) { + throw new IllegalStateException("ApplicationManagementService is not initialized properly"); + } + return applicationManagementService; + } + + public void setApplicationManagementService(ApplicationManagementService realmService) { + this.applicationManagementService = realmService; + } +} diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java new file mode 100644 index 00000000000..daaa7366e59 --- /dev/null +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.dynamic.client.registration.internal; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.service.component.ComponentContext; +import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService; +import org.wso2.carbon.dynamic.client.registration.impl.DynamicClientRegistrationImpl; +import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; + +/** + * @scr.component name="org.wso2.carbon.dynamic.client.registration" immediate="true" + * @scr.reference name="identity.application.management.service" + * interface="org.wso2.carbon.identity.application.mgt.ApplicationManagementService" + * cardinality="1..1" + * policy="dynamic" + * bind="setApplicationManagementService" + * unbind="unsetApplicationManagementService" + */ +public class DynamicClientRegistrationServiceComponent { + + private static final Log log = LogFactory.getLog(DynamicClientRegistrationServiceComponent.class); + + @SuppressWarnings("unused") + protected void activate(ComponentContext componentContext) { + if(log.isDebugEnabled()){ + log.debug("Starting DynamicClientRegistrationServiceComponent"); + } + DynamicClientRegistrationService dynamicClientRegistrationService = + new DynamicClientRegistrationImpl(); + componentContext.getBundleContext().registerService(DynamicClientRegistrationService.class.getName(), + dynamicClientRegistrationService, null); + } + + @SuppressWarnings("unused") + protected void deactivate(ComponentContext componentContext) { + if(log.isDebugEnabled()){ + log.debug("Stopping DynamicClientRegistrationServiceComponent"); + } + } + + /** + * Sets ApplicationManagement Service. + * + * @param applicationManagementService An instance of ApplicationManagementService + */ + protected void setApplicationManagementService(ApplicationManagementService + applicationManagementService) { + if (log.isDebugEnabled()) { + log.debug("Setting ApplicationManagement Service"); + } + DynamicClientRegistrationDataHolder.getInstance(). + setApplicationManagementService(applicationManagementService); + } + + /** + * Unsets ApplicationManagement Service. + * + * @param applicationManagementService An instance of ApplicationManagementService + */ + protected void unsetApplicationManagementService(ApplicationManagementService + applicationManagementService) { + if (log.isDebugEnabled()) { + log.debug("Unsetting ApplicationManagement Service"); + } + DynamicClientRegistrationDataHolder.getInstance().setApplicationManagementService(null); + } +} diff --git a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/ScopeValidator.java b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java similarity index 92% rename from components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/ScopeValidator.java rename to components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java index 0432238face..39d62f00637 100644 --- a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/ScopeValidator.java +++ b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java @@ -37,7 +37,7 @@ import java.util.Properties; * Custom OAuth2Token Scope validation implementation for DeviceManagement. This will validate the * user permissions before dispatching the HTTP request to the actual endpoint. */ -public class ScopeValidator extends OAuth2ScopeValidator { +public class PermissionBasedScopeValidator extends OAuth2ScopeValidator { private static final String URL_PROPERTY = "URL"; private static final String HTTP_METHOD_PROPERTY = "HTTP_METHOD"; @@ -52,7 +52,7 @@ public class ScopeValidator extends OAuth2ScopeValidator { public static final String ACTION = "action"; } - private static final Log log = LogFactory.getLog(ScopeValidator.class); + private static final Log log = LogFactory.getLog(PermissionBasedScopeValidator.class); @Override public boolean validateScope(AccessTokenDO accessTokenDO, String resource) @@ -64,8 +64,8 @@ public class ScopeValidator extends OAuth2ScopeValidator { String method = resource.substring(++idx, resource.length()); Properties properties = new Properties(); - properties.put(ScopeValidator.URL_PROPERTY, url); - properties.put(ScopeValidator.HTTP_METHOD_PROPERTY, method); + properties.put(PermissionBasedScopeValidator.URL_PROPERTY, url); + properties.put(PermissionBasedScopeValidator.HTTP_METHOD_PROPERTY, method); PermissionManagerService permissionManagerService = OAuthExtensionsDataHolder.getInstance(). getPermissionManagerService(); try { From 97df36842df27b293716f2d885b570bdf98fe08d Mon Sep 17 00:00:00 2001 From: Kamidu Sachith Date: Thu, 8 Oct 2015 14:02:29 +0530 Subject: [PATCH 02/23] Enabling OAuth Authentication for BackEnd Services --- .../backend-oauth-authenticator/pom.xml | 108 +++++++++++ .../backend/oauth/AuthenticatorException.java | 41 +++++ .../backend/oauth/OauthAuthenticator.java | 170 ++++++++++++++++++ .../oauth/OauthAuthenticatorConstants.java | 28 +++ .../OauthAuthenticatorServiceComponent.java | 56 ++++++ .../oauth/validator/OAuth2TokenValidator.java | 34 ++++ .../validator/OAuthValidationRespond.java | 57 ++++++ .../validator/OAuthValidatorFactory.java | 52 ++++++ .../impl/ExternalOAuthValidator.java | 98 ++++++++++ .../validator/impl/LocalOAuthValidator.java | 69 +++++++ components/identity-extensions/pom.xml | 1 + pom.xml | 21 ++- 12 files changed, 730 insertions(+), 5 deletions(-) create mode 100644 components/identity-extensions/backend-oauth-authenticator/pom.xml create mode 100755 components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/AuthenticatorException.java create mode 100755 components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticator.java create mode 100755 components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticatorConstants.java create mode 100755 components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/internal/OauthAuthenticatorServiceComponent.java create mode 100755 components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuth2TokenValidator.java create mode 100755 components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidationRespond.java create mode 100755 components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidatorFactory.java create mode 100755 components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java create mode 100755 components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java diff --git a/components/identity-extensions/backend-oauth-authenticator/pom.xml b/components/identity-extensions/backend-oauth-authenticator/pom.xml new file mode 100644 index 00000000000..ac4bc382e5c --- /dev/null +++ b/components/identity-extensions/backend-oauth-authenticator/pom.xml @@ -0,0 +1,108 @@ + + + + identity-extensions + org.wso2.carbon.devicemgt + 0.9.2-SNAPSHOT + + 4.0.0 + bundle + WSO2 Carbon - OAuth Back End Authenticator + org.wso2.carbon.identity.authenticator.backend.oauth + + + + org.wso2.carbon + org.wso2.carbon.utils + ${carbon.kernel.version} + + + org.wso2.carbon.identity + org.wso2.carbon.identity.base + ${carbon.identity.version} + + + org.wso2.carbon.identity + org.wso2.carbon.identity.core + ${carbon.identity.version} + + + org.wso2.carbon + org.wso2.carbon.core + ${carbon.kernel.version} + + + org.wso2.carbon + org.wso2.carbon.logging + ${carbon.kernel.version} + + + org.wso2.carbon.identity + org.wso2.carbon.identity.application.authentication.framework + ${carbon.identity.version} + + + org.wso2.carbon + org.wso2.carbon.core.services + ${carbon.kernel.version} + + + org.wso2.carbon.identity + org.wso2.carbon.identity.oauth + ${carbon.identity.version} + + + org.wso2.carbon.identity + org.wso2.carbon.identity.application.common + ${carbon.identity.version} + + + org.wso2.carbon.identity + org.wso2.carbon.identity.oauth.stub + + + + + + + org.apache.felix + maven-scr-plugin + + + org.apache.felix + maven-bundle-plugin + 1.4.0 + true + + + ${pom.artifactId} + ${pom.artifactId} + + org.wso2.sample.authenticator.internal + + + !org.wso2.sample.authenticator.internal, + org.wso2.sample.authenticator.*, + + + javax.servlet.http, + org.apache.commons.logging, + org.wso2.carbon.identity.application.authentication.framework.*, + org.wso2.carbon.identity.oauth2, + org.wso2.carbon.identity.oauth2.dto, + org.wso2.carbon.user.core.service, + org.wso2.carbon.utils.multitenancy + + + org.wso2.carbon.identity.authenticator.backend.oauth.*; + + * + + + + + + + \ No newline at end of file diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/AuthenticatorException.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/AuthenticatorException.java new file mode 100755 index 00000000000..05bc3d69f70 --- /dev/null +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/AuthenticatorException.java @@ -0,0 +1,41 @@ +/* +* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* WSO2 Inc. licenses this file to you under the Apache License, +* Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +package org.wso2.carbon.identity.authenticator.backend.oauth; + +/** + *Custom exception for backend OAuth authentication + */ +@SuppressWarnings("unused") +public class AuthenticatorException extends Exception { + + private static final long serialVersionUID = 1L; + + public AuthenticatorException(String message) { + super(message); + } + + public AuthenticatorException(Throwable e) { + super(e); + } + + public AuthenticatorException(String message, Throwable e) { + super(message, e); + } + + +} diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticator.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticator.java new file mode 100755 index 00000000000..43877ba832c --- /dev/null +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticator.java @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.wso2.carbon.identity.authenticator.backend.oauth; + +import org.apache.axis2.context.MessageContext; +import org.apache.axis2.transport.http.HTTPConstants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.core.security.AuthenticatorsConfiguration; +import org.wso2.carbon.core.services.authentication.CarbonServerAuthenticator; +import org.wso2.carbon.utils.ServerConstants; +import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator; +import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationRespond; +import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidatorFactory; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; +import java.rmi.RemoteException; + +/** + * This is a custom back end authenticator for enable OAuth token authentication for admin services + */ +public class OauthAuthenticator implements CarbonServerAuthenticator { + + private static final Log log = LogFactory.getLog(OauthAuthenticator.class); + private static final int PRIORITY = 5; + private static final int ACCESS_TOKEN_INDEX = 1; + + private static String hostUrl = ""; + private static boolean isRemote = false; + + static { + AuthenticatorsConfiguration authenticatorsConfiguration = AuthenticatorsConfiguration.getInstance(); + AuthenticatorsConfiguration.AuthenticatorConfig authenticatorConfig = authenticatorsConfiguration.getAuthenticatorConfig(OauthAuthenticatorConstants.AUTHENTICATOR_NAME); + + if (authenticatorConfig != null) { + isRemote = Boolean.parseBoolean(authenticatorConfig.getParameters().get("isRemote")); + hostUrl = authenticatorConfig.getParameters().get("hostURL"); + + } + } + + /** + * Checks whether the authentication of the context can be handled using this authenticator. + * + * @param messageContext containing the request need to be authenticated. + * @return boolean indicating whether the request can be authenticated by this Authenticator. + */ + public boolean isHandle(MessageContext messageContext) { + HttpServletRequest httpServletRequest = getHttpRequest(messageContext); + String headerValue = httpServletRequest.getHeader(HTTPConstants.HEADER_AUTHORIZATION); + + if (headerValue != null && !headerValue.trim().isEmpty()) { + String[] headerPart = headerValue.trim().split(OauthAuthenticatorConstants.SPLITING_CHARACTOR); + + if (OauthAuthenticatorConstants.AUTHORIZATION_HEADER_PREFIX_BEARER.equals(headerPart[0])) { + return true; + } + } else if (httpServletRequest.getParameter(OauthAuthenticatorConstants.BEARER_TOKEN_IDENTIFIER) != null) { + return true; + } + return false; + } + + /** + * Authenticates the user using the provided OAuth token and returns the status as a boolean. + * Sets the tenant domain and tenant friendly username to the session as attributes. + * + * @param messageContext containing the request need to be authenticated. + * @return boolean indicating the authentication status. + */ + public boolean isAuthenticated(MessageContext messageContext) { + HttpServletRequest httpServletRequest = getHttpRequest(messageContext); + String headerValue = httpServletRequest.getHeader(HTTPConstants.HEADER_AUTHORIZATION); + //split the header value to separate the identity type and the token. + String[] headerPart = headerValue.trim().split(OauthAuthenticatorConstants.SPLITING_CHARACTOR); + String accessToken = headerPart[ACCESS_TOKEN_INDEX]; + OAuth2TokenValidator tokenValidator = OAuthValidatorFactory.getValidator(isRemote,hostUrl); + + if (tokenValidator == null) { + log.error("OAuthValidationFactory failed to return a validator", + new AuthenticatorException("OAuthValidatorFactory Failed to determine the validator")); + return false; + } + + OAuthValidationRespond respond = null; + try { + respond = tokenValidator.validateToken(accessToken); + } catch (RemoteException e) { + log.error("Failed to validate the OAuth token provided.", e); + } + + if (respond != null && respond.isValid()) { + HttpSession session; + + if ((session = httpServletRequest.getSession(false)) != null) { + session.setAttribute(MultitenantConstants.TENANT_DOMAIN, respond.getTenantDomain()); + session.setAttribute(ServerConstants.USER_LOGGED_IN, respond.getUserName()); + + if (log.isDebugEnabled()) { + log.debug("Authentication successful for " + session.getAttribute(ServerConstants.USER_LOGGED_IN)); + } + } + return true; + } + + if (log.isDebugEnabled()) { + log.debug("Authentication failed.Illegal attempt from session " + httpServletRequest.getSession().getId()); + } + return false; + } + + /** + * this method is currently not implemented. + * + * @param messageContext containing the request need to be authenticated. + * @return boolean + */ + public boolean authenticateWithRememberMe(MessageContext messageContext) { + throw new UnsupportedOperationException(); + } + + /** + * @return string Authenticator name. + */ + public String getAuthenticatorName() { + return OauthAuthenticatorConstants.AUTHENTICATOR_NAME; + } + + /** + * @return int priority of the authenticator. + */ + public int getPriority() { + return PRIORITY; + } + + /** + * @return boolean true for enable or otherwise for disable status. + */ + public boolean isDisabled() { + return false; + } + + /** + * Retrieve HTTP Servlet Request form thr Message Context. + * + * @param messageContext Containing the Servlet Request for backend authentication. + * @return HTTPServletRequest. + */ + private HttpServletRequest getHttpRequest(MessageContext messageContext) { + return (HttpServletRequest) messageContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST); + } + +} diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticatorConstants.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticatorConstants.java new file mode 100755 index 00000000000..badaf8dbed4 --- /dev/null +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticatorConstants.java @@ -0,0 +1,28 @@ +/* +* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* WSO2 Inc. licenses this file to you under the Apache License, +* Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +package org.wso2.carbon.identity.authenticator.backend.oauth; + +public class OauthAuthenticatorConstants { + public static final String AUTHORIZATION_HEADER_PREFIX_BEARER = "Bearer"; + public static final String BEARER_TOKEN_TYPE = "bearer"; + public static final String BEARER_TOKEN_IDENTIFIER = "token"; + public static final String AUTHENTICATOR_NAME = "BackEndOAuthAuthenticator"; + public static final String SPLITING_CHARACTOR = " "; + public static String OAUTH_ENDPOINT_POSTFIX = + "/services/OAuth2TokenValidationService.OAuth2TokenValidationServiceHttpsSoap12Endpoint/"; +} diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/internal/OauthAuthenticatorServiceComponent.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/internal/OauthAuthenticatorServiceComponent.java new file mode 100755 index 00000000000..59577ac633b --- /dev/null +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/internal/OauthAuthenticatorServiceComponent.java @@ -0,0 +1,56 @@ +/* +* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* WSO2 Inc. licenses this file to you under the Apache License, +* Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ + +package org.wso2.carbon.identity.authenticator.backend.oauth.internal; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.service.component.ComponentContext; +import org.wso2.carbon.core.services.authentication.CarbonServerAuthenticator; +import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticator; + + +/** + * @scr.component component.name="org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticator" immediate="true" + */ +@SuppressWarnings("unused") +public class OauthAuthenticatorServiceComponent { + + private static final Log log = LogFactory.getLog(OauthAuthenticatorServiceComponent + .class); + + protected void activate(ComponentContext ctxt) { + try { + OauthAuthenticator oauthAuthenticator = new OauthAuthenticator(); + ctxt.getBundleContext().registerService(CarbonServerAuthenticator.class.getName(), + oauthAuthenticator, null); + if (log.isDebugEnabled()) { + log.debug("OAuth Authenticator bundle is activated"); + } + } catch (Throwable e) { + log.fatal(" Error while activating OAuth authenticator ", e); + } + } + + protected void deactivate(ComponentContext ctxt) { + if (log.isDebugEnabled()) { + log.debug("OAuth Authenticator bundle is deactivated"); + } + } + +} diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuth2TokenValidator.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuth2TokenValidator.java new file mode 100755 index 00000000000..7382fe1370d --- /dev/null +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuth2TokenValidator.java @@ -0,0 +1,34 @@ +/* +* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* WSO2 Inc. licenses this file to you under the Apache License, +* Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +package org.wso2.carbon.identity.authenticator.backend.oauth.validator; + +import java.rmi.RemoteException; + +/** + * Interface for the OAuth@TokenValidators + */ +public interface OAuth2TokenValidator { + /** + * This method gets a string accessToken and validates it and generate the OAuth2ClientApplicationDTO + * containing the validity and user details if valid. + * + * @param accessToken which need to be validated. + * @return OAuthValidationRespond with the validated results. + */ + OAuthValidationRespond validateToken(String accessToken) throws RemoteException; +} diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidationRespond.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidationRespond.java new file mode 100755 index 00000000000..1e45aa59236 --- /dev/null +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidationRespond.java @@ -0,0 +1,57 @@ +/* +* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* WSO2 Inc. licenses this file to you under the Apache License, +* Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +package org.wso2.carbon.identity.authenticator.backend.oauth.validator; + +/** + * This class hold the validation information which can be retrieve by both remote and in house IDPs + */ +public class OAuthValidationRespond { + private String userName; + private String tenantDomain; + private boolean isValid; + + public OAuthValidationRespond(String userName, String tenantDomain, boolean isValid) { + this.userName = userName; + this.tenantDomain = tenantDomain; + this.isValid = isValid; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getTenantDomain() { + return tenantDomain; + } + + public void setTenantDomain(String tenantDomain) { + this.tenantDomain = tenantDomain; + } + + public boolean isValid() { + return isValid; + } + + public void setIsValid(boolean isValid) { + this.isValid = isValid; + } +} \ No newline at end of file diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidatorFactory.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidatorFactory.java new file mode 100755 index 00000000000..e3dab669c6a --- /dev/null +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidatorFactory.java @@ -0,0 +1,52 @@ +/* +* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* WSO2 Inc. licenses this file to you under the Apache License, +* Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +package org.wso2.carbon.identity.authenticator.backend.oauth.validator; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.identity.authenticator.backend.oauth.AuthenticatorException; +import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorConstants; +import org.wso2.carbon.identity.authenticator.backend.oauth.validator.impl.ExternalOAuthValidator; +import org.wso2.carbon.identity.authenticator.backend.oauth.validator.impl.LocalOAuthValidator; + +/** + * the class validate the configurations and provide the most suitable implementation according to the configuration. + * Factory class for OAuthValidator. + */ +public class OAuthValidatorFactory { + private static Log log = LogFactory.getLog(OAuthValidatorFactory.class); + + /** + * the method check the configuration and provide the appropriate implementation for OAuth2TokenValidator + * + * @return OAuth2TokenValidator + */ + public static OAuth2TokenValidator getValidator(boolean isRemote ,String hostURL) { + if(isRemote){ + if(!(hostURL == null || hostURL.trim().isEmpty())){ + hostURL = hostURL + OauthAuthenticatorConstants.OAUTH_ENDPOINT_POSTFIX; + return new ExternalOAuthValidator(hostURL); + }else { + log.error("IDP Configuration error", + new AuthenticatorException("Remote server name and ip both can't be empty")); + return null; + } + } + return new LocalOAuthValidator(); + } +} diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java new file mode 100755 index 00000000000..4a337e9a9cf --- /dev/null +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java @@ -0,0 +1,98 @@ +/* +* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* WSO2 Inc. licenses this file to you under the Apache License, +* Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +package org.wso2.carbon.identity.authenticator.backend.oauth.validator.impl; + +import org.apache.axis2.client.Options; +import org.apache.axis2.client.ServiceClient; +import org.apache.axis2.transport.http.HTTPConstants; +import org.apache.commons.httpclient.Header; +import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; +import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2ClientApplicationDTO; +import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO; +import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_OAuth2AccessToken; +import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_TokenValidationContextParam; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; +import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorConstants; +import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator; +import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationRespond; + +import java.rmi.RemoteException; +import java.util.ArrayList; +import java.util.List; + +/** + * Handles the Authentication form external IDP servers. + * Currently only supports WSO2 IS. + * External IDP support is planned for future. + */ +public class ExternalOAuthValidator implements OAuth2TokenValidator{ + protected String hostURL ; + + public ExternalOAuthValidator(String hostURL) { + this.hostURL = hostURL; + } + /** + * This method gets a string accessToken and validates it and generate the OAuth2ClientApplicationDTO + * containing the validity and user details if valid. + * + * @param token which need to be validated. + * @return OAuthValidationRespond with the validated results. + */ + public OAuthValidationRespond validateToken(String token) throws RemoteException { + + // create an OAuth token validating request DTO + OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO(); + + // create access token object to validate and populate it + OAuth2TokenValidationRequestDTO_OAuth2AccessToken accessToken = + new OAuth2TokenValidationRequestDTO_OAuth2AccessToken(); + accessToken.setTokenType(OauthAuthenticatorConstants.BEARER_TOKEN_TYPE); + accessToken.setIdentifier(token); + OAuth2TokenValidationRequestDTO_TokenValidationContextParam tokenValidationContextParam[] = + new OAuth2TokenValidationRequestDTO_TokenValidationContextParam[1]; + validationRequest.setContext(tokenValidationContextParam); + + //set the token to the validation request + validationRequest.setAccessToken(accessToken); + OAuth2TokenValidationServiceStub validationService = + new OAuth2TokenValidationServiceStub(hostURL); + ServiceClient client = validationService._getServiceClient(); + Options options = client.getOptions(); + List
list = new ArrayList<>(); + Header header = new Header(); + header.setName(HTTPConstants.HEADER_AUTHORIZATION); + header.setValue(OauthAuthenticatorConstants.AUTHORIZATION_HEADER_PREFIX_BEARER+ " " + token); + list.add(header); + options.setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_HEADERS, list); + client.setOptions(options); + OAuth2ClientApplicationDTO respond = + validationService.findOAuthConsumerIfTokenIsValid(validationRequest); + boolean isValid = respond.getAccessTokenValidationResponse().getValid(); + String userName = null; + String tenantDomain = null; + + if(isValid){ + userName = MultitenantUtils.getTenantAwareUsername( + respond.getAccessTokenValidationResponse().getAuthorizedUser()); + tenantDomain = + MultitenantUtils.getTenantDomain(respond.getAccessTokenValidationResponse().getAuthorizedUser()); + } + + return new OAuthValidationRespond(userName,tenantDomain,isValid); + } +} diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java new file mode 100755 index 00000000000..d81e7f3531d --- /dev/null +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java @@ -0,0 +1,69 @@ + +/* +* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* WSO2 Inc. licenses this file to you under the Apache License, +* Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +package org.wso2.carbon.identity.authenticator.backend.oauth.validator.impl; + +import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; +import org.wso2.carbon.identity.oauth2.dto.OAuth2ClientApplicationDTO; +import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; +import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorConstants; +import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator; +import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationRespond; + +/** + * Handles the authentication using the inbuilt IS features. + */ +public class LocalOAuthValidator implements OAuth2TokenValidator { + /** + * This method gets a string accessToken and validates it and generate the OAuth2ClientApplicationDTO + * containing the validity and user details if valid. + * + * @param token which need to be validated. + * @return OAuthValidationRespond with the validated results. + */ + public OAuthValidationRespond validateToken(String token) { + // create an OAuth token validating request DTO + OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO(); + // create access token object to validate and populate it + OAuth2TokenValidationRequestDTO.OAuth2AccessToken accessToken = + validationRequest.new OAuth2AccessToken(); + accessToken.setTokenType(OauthAuthenticatorConstants.BEARER_TOKEN_TYPE); + accessToken.setIdentifier(token); + //the workaround till the version is upgraded in both is and EMM to be the same. + OAuth2TokenValidationRequestDTO.TokenValidationContextParam tokenValidationContextParam[] = + new OAuth2TokenValidationRequestDTO.TokenValidationContextParam[1]; + //== + validationRequest.setContext(tokenValidationContextParam); + //set the token to the validation request + validationRequest.setAccessToken(accessToken); + OAuth2TokenValidationService validationService = new OAuth2TokenValidationService(); + OAuth2ClientApplicationDTO respond = validationService. + findOAuthConsumerIfTokenIsValid(validationRequest); + boolean isValid = respond.getAccessTokenValidationResponse().isValid(); + String userName = null; + String tenantDomain = null; + if(isValid){ + userName = MultitenantUtils.getTenantAwareUsername( + respond.getAccessTokenValidationResponse().getAuthorizedUser()); + tenantDomain = + MultitenantUtils.getTenantDomain(respond.getAccessTokenValidationResponse().getAuthorizedUser()); + } + return new OAuthValidationRespond(userName,tenantDomain,isValid); + } +} diff --git a/components/identity-extensions/pom.xml b/components/identity-extensions/pom.xml index 78a24d9adb0..8dbb24619dd 100644 --- a/components/identity-extensions/pom.xml +++ b/components/identity-extensions/pom.xml @@ -37,6 +37,7 @@ org.wso2.carbon.device.mgt.oauth.extensions dynamic-client-registration + backend-oauth-authenticator diff --git a/pom.xml b/pom.xml index 26df26d760a..fbfa9406f04 100644 --- a/pom.xml +++ b/pom.xml @@ -941,6 +941,22 @@ org.wso2.carbon.identity.oauth.stub ${carbon.identity.version} + + org.wso2.carbon.identity + org.wso2.carbon.identity.application.authentication.framework + ${carbon.identity.version} + + + + org.wso2.carbon.identity + org.wso2.carbon.identity.oauth + ${carbon.identity.version} + + + org.wso2.carbon.identity + org.wso2.carbon.identity.application.common + ${carbon.identity.version} + @@ -1126,11 +1142,6 @@ - - org.wso2.carbon.identity - org.wso2.carbon.identity.oauth - ${carbon.identity.version} - org.wso2.carbon.identity org.wso2.carbon.identity.sso.saml From 786728b49b978dd82021e828f49f7010f554082f Mon Sep 17 00:00:00 2001 From: Kamidu Sachith Date: Thu, 8 Oct 2015 17:54:49 +0530 Subject: [PATCH 03/23] Recomended Changes to Enabling OAuth Authentication for BackEnd Services --- .../backend-oauth-authenticator/pom.xml | 48 +++++++++++-------- .../backend/oauth/AuthenticatorException.java | 2 +- .../backend/oauth/OauthAuthenticator.java | 45 +++++++---------- .../validator/OAuthValidationRespond.java | 1 + .../validator/OAuthValidatorFactory.java | 20 +++----- .../impl/ExternalOAuthValidator.java | 21 ++------ .../validator/impl/LocalOAuthValidator.java | 9 ---- 7 files changed, 58 insertions(+), 88 deletions(-) diff --git a/components/identity-extensions/backend-oauth-authenticator/pom.xml b/components/identity-extensions/backend-oauth-authenticator/pom.xml index ac4bc382e5c..37cc5274f67 100644 --- a/components/identity-extensions/backend-oauth-authenticator/pom.xml +++ b/components/identity-extensions/backend-oauth-authenticator/pom.xml @@ -1,4 +1,21 @@ + @@ -16,48 +33,39 @@ org.wso2.carbon org.wso2.carbon.utils - ${carbon.kernel.version} - + org.wso2.carbon.identity org.wso2.carbon.identity.base - ${carbon.identity.version} - + org.wso2.carbon.identity org.wso2.carbon.identity.core - ${carbon.identity.version} - + org.wso2.carbon org.wso2.carbon.core - ${carbon.kernel.version} - + org.wso2.carbon org.wso2.carbon.logging - ${carbon.kernel.version} - + org.wso2.carbon.identity org.wso2.carbon.identity.application.authentication.framework - ${carbon.identity.version} - + org.wso2.carbon org.wso2.carbon.core.services - ${carbon.kernel.version} - + org.wso2.carbon.identity org.wso2.carbon.identity.oauth - ${carbon.identity.version} - + org.wso2.carbon.identity org.wso2.carbon.identity.application.common - ${carbon.identity.version} - + org.wso2.carbon.identity org.wso2.carbon.identity.oauth.stub @@ -98,11 +106,9 @@ org.wso2.carbon.identity.authenticator.backend.oauth.*; - * - + - \ No newline at end of file diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/AuthenticatorException.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/AuthenticatorException.java index 05bc3d69f70..42eafd7888c 100755 --- a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/AuthenticatorException.java +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/AuthenticatorException.java @@ -18,7 +18,7 @@ package org.wso2.carbon.identity.authenticator.backend.oauth; /** - *Custom exception for backend OAuth authentication + * Custom exception for backend OAuth authentication */ @SuppressWarnings("unused") public class AuthenticatorException extends Exception { diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticator.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticator.java index 43877ba832c..adfcf71214a 100755 --- a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticator.java +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticator.java @@ -41,18 +41,24 @@ public class OauthAuthenticator implements CarbonServerAuthenticator { private static final Log log = LogFactory.getLog(OauthAuthenticator.class); private static final int PRIORITY = 5; private static final int ACCESS_TOKEN_INDEX = 1; + private OAuth2TokenValidator tokenValidator; - private static String hostUrl = ""; - private static boolean isRemote = false; - - static { + public OauthAuthenticator() { AuthenticatorsConfiguration authenticatorsConfiguration = AuthenticatorsConfiguration.getInstance(); - AuthenticatorsConfiguration.AuthenticatorConfig authenticatorConfig = authenticatorsConfiguration.getAuthenticatorConfig(OauthAuthenticatorConstants.AUTHENTICATOR_NAME); - + AuthenticatorsConfiguration.AuthenticatorConfig authenticatorConfig = authenticatorsConfiguration. + getAuthenticatorConfig(OauthAuthenticatorConstants.AUTHENTICATOR_NAME); + boolean isRemote; + String hostUrl; if (authenticatorConfig != null) { isRemote = Boolean.parseBoolean(authenticatorConfig.getParameters().get("isRemote")); hostUrl = authenticatorConfig.getParameters().get("hostURL"); - + }else{ + throw new IllegalArgumentException("Configuration parameters need to be defined in Authenticators.xml"); + } + try { + tokenValidator = OAuthValidatorFactory.getValidator(isRemote, hostUrl); + } catch (IllegalArgumentException e) { + log.error("Failed to initialise Authenticator",e); } } @@ -65,10 +71,8 @@ public class OauthAuthenticator implements CarbonServerAuthenticator { public boolean isHandle(MessageContext messageContext) { HttpServletRequest httpServletRequest = getHttpRequest(messageContext); String headerValue = httpServletRequest.getHeader(HTTPConstants.HEADER_AUTHORIZATION); - if (headerValue != null && !headerValue.trim().isEmpty()) { String[] headerPart = headerValue.trim().split(OauthAuthenticatorConstants.SPLITING_CHARACTOR); - if (OauthAuthenticatorConstants.AUTHORIZATION_HEADER_PREFIX_BEARER.equals(headerPart[0])) { return true; } @@ -88,38 +92,25 @@ public class OauthAuthenticator implements CarbonServerAuthenticator { public boolean isAuthenticated(MessageContext messageContext) { HttpServletRequest httpServletRequest = getHttpRequest(messageContext); String headerValue = httpServletRequest.getHeader(HTTPConstants.HEADER_AUTHORIZATION); - //split the header value to separate the identity type and the token. String[] headerPart = headerValue.trim().split(OauthAuthenticatorConstants.SPLITING_CHARACTOR); String accessToken = headerPart[ACCESS_TOKEN_INDEX]; - OAuth2TokenValidator tokenValidator = OAuthValidatorFactory.getValidator(isRemote,hostUrl); - - if (tokenValidator == null) { - log.error("OAuthValidationFactory failed to return a validator", - new AuthenticatorException("OAuthValidatorFactory Failed to determine the validator")); - return false; - } - - OAuthValidationRespond respond = null; + OAuthValidationRespond response = null; try { - respond = tokenValidator.validateToken(accessToken); + response = tokenValidator.validateToken(accessToken); } catch (RemoteException e) { log.error("Failed to validate the OAuth token provided.", e); } - - if (respond != null && respond.isValid()) { + if (response != null && response.isValid()) { HttpSession session; - if ((session = httpServletRequest.getSession(false)) != null) { - session.setAttribute(MultitenantConstants.TENANT_DOMAIN, respond.getTenantDomain()); - session.setAttribute(ServerConstants.USER_LOGGED_IN, respond.getUserName()); - + session.setAttribute(MultitenantConstants.TENANT_DOMAIN, response.getTenantDomain()); + session.setAttribute(ServerConstants.USER_LOGGED_IN, response.getUserName()); if (log.isDebugEnabled()) { log.debug("Authentication successful for " + session.getAttribute(ServerConstants.USER_LOGGED_IN)); } } return true; } - if (log.isDebugEnabled()) { log.debug("Authentication failed.Illegal attempt from session " + httpServletRequest.getSession().getId()); } diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidationRespond.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidationRespond.java index 1e45aa59236..346ac2ac303 100755 --- a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidationRespond.java +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidationRespond.java @@ -20,6 +20,7 @@ package org.wso2.carbon.identity.authenticator.backend.oauth.validator; /** * This class hold the validation information which can be retrieve by both remote and in house IDPs */ +@SuppressWarnings("unused") public class OAuthValidationRespond { private String userName; private String tenantDomain; diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidatorFactory.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidatorFactory.java index e3dab669c6a..bb88d98f7e7 100755 --- a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidatorFactory.java +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidatorFactory.java @@ -17,34 +17,28 @@ */ package org.wso2.carbon.identity.authenticator.backend.oauth.validator; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.wso2.carbon.identity.authenticator.backend.oauth.AuthenticatorException; import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorConstants; import org.wso2.carbon.identity.authenticator.backend.oauth.validator.impl.ExternalOAuthValidator; import org.wso2.carbon.identity.authenticator.backend.oauth.validator.impl.LocalOAuthValidator; /** - * the class validate the configurations and provide the most suitable implementation according to the configuration. + * The class validate the configurations and provide the most suitable implementation according to the configuration. * Factory class for OAuthValidator. */ public class OAuthValidatorFactory { - private static Log log = LogFactory.getLog(OAuthValidatorFactory.class); /** - * the method check the configuration and provide the appropriate implementation for OAuth2TokenValidator - * + * The method check the configuration and provide the appropriate implementation for OAuth2TokenValidator * @return OAuth2TokenValidator */ - public static OAuth2TokenValidator getValidator(boolean isRemote ,String hostURL) { - if(isRemote){ - if(!(hostURL == null || hostURL.trim().isEmpty())){ + public static OAuth2TokenValidator getValidator(boolean isRemote, String hostURL) throws IllegalArgumentException { + if (isRemote) { + if (!(hostURL == null || hostURL.trim().isEmpty())) { hostURL = hostURL + OauthAuthenticatorConstants.OAUTH_ENDPOINT_POSTFIX; return new ExternalOAuthValidator(hostURL); - }else { - log.error("IDP Configuration error", - new AuthenticatorException("Remote server name and ip both can't be empty")); - return null; + } else { + throw new IllegalArgumentException("Remote server name and ip both can't be empty"); } } return new LocalOAuthValidator(); diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java index 4a337e9a9cf..0c0836165e2 100755 --- a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java @@ -21,15 +21,14 @@ import org.apache.axis2.client.Options; import org.apache.axis2.client.ServiceClient; import org.apache.axis2.transport.http.HTTPConstants; import org.apache.commons.httpclient.Header; +import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorConstants; +import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator; +import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationRespond; import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2ClientApplicationDTO; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_OAuth2AccessToken; -import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_TokenValidationContextParam; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorConstants; -import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator; -import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationRespond; import java.rmi.RemoteException; import java.util.ArrayList; @@ -37,8 +36,7 @@ import java.util.List; /** * Handles the Authentication form external IDP servers. - * Currently only supports WSO2 IS. - * External IDP support is planned for future. + * Currently only supports WSO@ IS */ public class ExternalOAuthValidator implements OAuth2TokenValidator{ protected String hostURL ; @@ -54,20 +52,11 @@ public class ExternalOAuthValidator implements OAuth2TokenValidator{ * @return OAuthValidationRespond with the validated results. */ public OAuthValidationRespond validateToken(String token) throws RemoteException { - - // create an OAuth token validating request DTO OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO(); - - // create access token object to validate and populate it OAuth2TokenValidationRequestDTO_OAuth2AccessToken accessToken = new OAuth2TokenValidationRequestDTO_OAuth2AccessToken(); accessToken.setTokenType(OauthAuthenticatorConstants.BEARER_TOKEN_TYPE); accessToken.setIdentifier(token); - OAuth2TokenValidationRequestDTO_TokenValidationContextParam tokenValidationContextParam[] = - new OAuth2TokenValidationRequestDTO_TokenValidationContextParam[1]; - validationRequest.setContext(tokenValidationContextParam); - - //set the token to the validation request validationRequest.setAccessToken(accessToken); OAuth2TokenValidationServiceStub validationService = new OAuth2TokenValidationServiceStub(hostURL); @@ -85,14 +74,12 @@ public class ExternalOAuthValidator implements OAuth2TokenValidator{ boolean isValid = respond.getAccessTokenValidationResponse().getValid(); String userName = null; String tenantDomain = null; - if(isValid){ userName = MultitenantUtils.getTenantAwareUsername( respond.getAccessTokenValidationResponse().getAuthorizedUser()); tenantDomain = MultitenantUtils.getTenantDomain(respond.getAccessTokenValidationResponse().getAuthorizedUser()); } - return new OAuthValidationRespond(userName,tenantDomain,isValid); } } diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java index d81e7f3531d..ea7edf1d13a 100755 --- a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java @@ -1,4 +1,3 @@ - /* * Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * @@ -38,19 +37,11 @@ public class LocalOAuthValidator implements OAuth2TokenValidator { * @return OAuthValidationRespond with the validated results. */ public OAuthValidationRespond validateToken(String token) { - // create an OAuth token validating request DTO OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO(); - // create access token object to validate and populate it OAuth2TokenValidationRequestDTO.OAuth2AccessToken accessToken = validationRequest.new OAuth2AccessToken(); accessToken.setTokenType(OauthAuthenticatorConstants.BEARER_TOKEN_TYPE); accessToken.setIdentifier(token); - //the workaround till the version is upgraded in both is and EMM to be the same. - OAuth2TokenValidationRequestDTO.TokenValidationContextParam tokenValidationContextParam[] = - new OAuth2TokenValidationRequestDTO.TokenValidationContextParam[1]; - //== - validationRequest.setContext(tokenValidationContextParam); - //set the token to the validation request validationRequest.setAccessToken(accessToken); OAuth2TokenValidationService validationService = new OAuth2TokenValidationService(); OAuth2ClientApplicationDTO respond = validationService. From 741777682a4358c78912898467f90319fae19b8e Mon Sep 17 00:00:00 2001 From: harshanl Date: Fri, 9 Oct 2015 19:20:12 +0530 Subject: [PATCH 04/23] Fixed dynamic client registration issues with server startup --- .../pom.xml | 20 ++- .../registration/OAuthApplicationInfo.java | 1 - .../impl/DynamicClientRegistrationImpl.java | 3 +- ...micClientRegistrationServiceComponent.java | 2 + .../pom.xml | 4 + ...ynamicClientWebAppRegistrationManager.java | 137 +++++++++++------- ...bAppRegistrationServerStartupObserver.java | 38 +++++ .../JaggeryOAuthConfigurationSettings.java} | 4 +- .../OAuthAppDetails.java} | 6 +- ...entWebAppRegistrationServiceComponent.java | 12 +- ...ientWebAppDeploymentLifecycleListener.java | 2 +- .../DynamicClientWebAppRegistrationUtil.java | 71 ++++----- pom.xml | 9 +- 13 files changed, 204 insertions(+), 105 deletions(-) create mode 100644 components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/WebAppRegistrationServerStartupObserver.java rename components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/{OAuthSettings.java => dto/JaggeryOAuthConfigurationSettings.java} (95%) rename components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/{OAuthApp.java => dto/OAuthAppDetails.java} (93%) diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/pom.xml b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/pom.xml index b2d8ec58b90..9b44329b6b3 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/pom.xml +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/pom.xml @@ -56,7 +56,25 @@ !org.wso2.carbon.dynamic.client.registration.internal, org.wso2.carbon.dynamic.client.registration.* - * + + org.apache.commons.logging, + org.json, + org.json.simple, + org.osgi.framework, + org.osgi.service.component, + org.wso2.carbon.context, + org.wso2.carbon.identity.application.common, + org.wso2.carbon.identity.application.common.model, + org.wso2.carbon.identity.application.mgt, + org.wso2.carbon.identity.base, + org.wso2.carbon.identity.oauth, + org.wso2.carbon.identity.oauth.dto, + org.wso2.carbon.identity.sso.saml.admin, + org.wso2.carbon.identity.sso.saml.dto, + org.wso2.carbon.registry.api, + org.wso2.carbon.registry.core, + org.wso2.carbon.utils.multitenancy + diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/OAuthApplicationInfo.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/OAuthApplicationInfo.java index 2eb570cb59d..379194a3bfd 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/OAuthApplicationInfo.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/OAuthApplicationInfo.java @@ -91,7 +91,6 @@ public class OAuthApplicationInfo { obj.put(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_NAME, this.getClientName()); obj.put(ApplicationConstants.ClientMetadata.OAUTH_CALLBACK_URIS, this.getCallBackURL()); obj.put(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_SECRET, this.getClientSecret()); - obj.put("parameters", this.getJsonString()); return obj.toString(); } diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationImpl.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationImpl.java index 339a0d32f26..3c2c49f0028 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationImpl.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationImpl.java @@ -188,7 +188,8 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS log.debug("Creating OAuth App " + applicationName); } - if (existingServiceProvider == null) { + if ((existingServiceProvider == null) || (existingServiceProvider. + getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs().length == 0)) { oAuthAdminService.registerOAuthApplicationData(oAuthConsumerApp); } diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java index daaa7366e59..d01b7fa5247 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java @@ -24,6 +24,7 @@ import org.osgi.service.component.ComponentContext; import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService; import org.wso2.carbon.dynamic.client.registration.impl.DynamicClientRegistrationImpl; import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; +import org.wso2.carbon.identity.core.util.IdentityCoreInitializedEvent; /** * @scr.component name="org.wso2.carbon.dynamic.client.registration" immediate="true" @@ -82,4 +83,5 @@ public class DynamicClientRegistrationServiceComponent { } DynamicClientRegistrationDataHolder.getInstance().setApplicationManagementService(null); } + } diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/pom.xml b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/pom.xml index 79be0e0b4f4..438dbcefd98 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/pom.xml +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/pom.xml @@ -87,6 +87,10 @@ org.wso2.carbon.identity org.wso2.carbon.identity.oauth + + org.wso2.carbon.identity + org.wso2.carbon.identity.core + org.wso2.tomcat tomcat diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/DynamicClientWebAppRegistrationManager.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/DynamicClientWebAppRegistrationManager.java index a5f2453f111..b159a3515c2 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/DynamicClientWebAppRegistrationManager.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/DynamicClientWebAppRegistrationManager.java @@ -19,17 +19,21 @@ package org.wso2.carbon.dynamic.client.web.app.registration; import org.apache.catalina.core.StandardContext; +import org.apache.commons.collections.iterators.IteratorEnumeration; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationException; import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService; import org.wso2.carbon.dynamic.client.registration.OAuthApplicationInfo; import org.wso2.carbon.dynamic.client.registration.profile.RegistrationProfile; +import org.wso2.carbon.dynamic.client.web.app.registration.dto.OAuthAppDetails; +import org.wso2.carbon.dynamic.client.web.app.registration.dto.JaggeryOAuthConfigurationSettings; import org.wso2.carbon.dynamic.client.web.app.registration.internal.DynamicClientWebAppRegistrationDataHolder; import org.wso2.carbon.dynamic.client.web.app.registration.util.DynamicClientWebAppRegistrationConstants; import org.wso2.carbon.dynamic.client.web.app.registration.util.DynamicClientWebAppRegistrationUtil; import javax.servlet.ServletContext; +import java.util.*; /** * This class contains the logic to handle the OAuth application creation process. @@ -37,6 +41,9 @@ import javax.servlet.ServletContext; public class DynamicClientWebAppRegistrationManager { private static DynamicClientWebAppRegistrationManager dynamicClientWebAppRegistrationManager; + private static List registrationProfileList = new ArrayList<>(); + private static Map webAppContexts = new HashMap<>(); + private static final Log log = LogFactory.getLog(DynamicClientWebAppRegistrationManager.class); @@ -47,108 +54,132 @@ public class DynamicClientWebAppRegistrationManager { if (dynamicClientWebAppRegistrationManager == null) { synchronized (DynamicClientWebAppRegistrationManager.class) { if (dynamicClientWebAppRegistrationManager == null) { - dynamicClientWebAppRegistrationManager = new DynamicClientWebAppRegistrationManager(); + dynamicClientWebAppRegistrationManager = + new DynamicClientWebAppRegistrationManager(); } } } return dynamicClientWebAppRegistrationManager; } - public OAuthApp registerOAuthApplication(RegistrationProfile registrationProfile) { + public OAuthAppDetails registerOAuthApplication(RegistrationProfile registrationProfile) { if (log.isDebugEnabled()) { - log.debug("Registering OAuth application for web app : " + registrationProfile.getClientName()); + log.debug("Registering OAuth application for web app : " + + registrationProfile.getClientName()); } if (DynamicClientWebAppRegistrationUtil.validateRegistrationProfile(registrationProfile)) { DynamicClientRegistrationService dynamicClientRegistrationService = DynamicClientWebAppRegistrationDataHolder.getInstance() - .getDynamicClientRegistrationService(); + .getDynamicClientRegistrationService(); try { OAuthApplicationInfo oAuthApplicationInfo = dynamicClientRegistrationService .registerOAuthApplication(registrationProfile); - OAuthApp oAuthApp = new OAuthApp(); - oAuthApp.setWebAppName(registrationProfile.getClientName()); - oAuthApp.setClientName(oAuthApplicationInfo.getClientName()); - oAuthApp.setClientKey(oAuthApplicationInfo.getClientId()); - oAuthApp.setClientSecret(oAuthApplicationInfo.getClientSecret()); + OAuthAppDetails oAuthAppDetails = new OAuthAppDetails(); + oAuthAppDetails.setWebAppName(registrationProfile.getClientName()); + oAuthAppDetails.setClientName(oAuthApplicationInfo.getClientName()); + oAuthAppDetails.setClientKey(oAuthApplicationInfo.getClientId()); + oAuthAppDetails.setClientSecret(oAuthApplicationInfo.getClientSecret()); //store it in registry - if (DynamicClientWebAppRegistrationUtil.putOAuthApplicationData(oAuthApp)) { - return oAuthApp; + if (DynamicClientWebAppRegistrationUtil.putOAuthApplicationData(oAuthAppDetails)) { + return oAuthAppDetails; } else { dynamicClientRegistrationService .unregisterOAuthApplication(registrationProfile.getOwner(), oAuthApplicationInfo.getClientName(), oAuthApplicationInfo.getClientId()); - log.warn("Error occurred while persisting the OAuth application data in registry."); + log.warn( + "Error occurred while persisting the OAuth application data in registry."); } } catch (DynamicClientRegistrationException e) { log.error("Error occurred while registering the OAuth application : " + registrationProfile.getClientName(), e); } } - return new OAuthApp(); + return new OAuthAppDetails(); } - public OAuthApp getOAuthApplicationData(String clientName) { + public OAuthAppDetails getOAuthApplicationData(String clientName) { try { return DynamicClientWebAppRegistrationUtil.getOAuthApplicationData(clientName); } catch (DynamicClientRegistrationException e) { log.error("Error occurred while fetching the OAuth application data for web app : " + clientName, e); } - return new OAuthApp(); + return new OAuthAppDetails(); } public boolean isRegisteredOAuthApplication(String clientName) { - OAuthApp oAuthApp = this.getOAuthApplicationData(clientName); - if (oAuthApp.getClientKey() != null && oAuthApp.getClientSecret() != null) { + OAuthAppDetails oAuthAppDetails = this.getOAuthApplicationData(clientName); + if (oAuthAppDetails.getClientKey() != null && oAuthAppDetails.getClientSecret() != null) { return true; } return false; } - public void initiateDynamicClientRegistrationProcess(StandardContext context) { - ServletContext servletContext = context.getServletContext(); - String requiredDynamicClientRegistration = servletContext.getInitParameter( - DynamicClientWebAppRegistrationConstants.DYNAMIC_CLIENT_REQUIRED_FLAG); + public void saveServletContextToCache(StandardContext context) { + DynamicClientWebAppRegistrationManager.webAppContexts.put(context.getBaseName(), + context.getServletContext()); + } + + public void initiateDynamicClientRegistration() { + String requiredDynamicClientRegistration, webAppName; + ServletContext servletContext; + RegistrationProfile registrationProfile; + OAuthAppDetails oAuthAppDetails = new OAuthAppDetails(); DynamicClientWebAppRegistrationManager dynamicClientWebAppRegistrationManager = DynamicClientWebAppRegistrationManager.getInstance(); - //Get the application name from web-context - String webAppName = context.getBaseName(); - RegistrationProfile registrationProfile; - OAuthApp oAuthApp = null; - //Java web-app section - if ((requiredDynamicClientRegistration != null) && - (Boolean.parseBoolean(requiredDynamicClientRegistration))) { - //Check whether this is an already registered application - if (!dynamicClientWebAppRegistrationManager.isRegisteredOAuthApplication(webAppName)) { - //Construct the RegistrationProfile - registrationProfile = DynamicClientWebAppRegistrationUtil. - constructRegistrationProfile(servletContext, webAppName); - //Register the OAuth application - oAuthApp = dynamicClientWebAppRegistrationManager.registerOAuthApplication( - registrationProfile); - } else { - oAuthApp = dynamicClientWebAppRegistrationManager.getOAuthApplicationData(webAppName); - } - } else { - //Jaggery apps - OAuthSettings oAuthSettings = DynamicClientWebAppRegistrationUtil - .getJaggeryAppOAuthSettings(servletContext); - if (oAuthSettings.isRequireDynamicClientRegistration()) { + Enumeration enumeration = new IteratorEnumeration(DynamicClientWebAppRegistrationManager. + webAppContexts.keySet().iterator()); + if (log.isDebugEnabled()) { + log.debug("Initiating the DynamicClientRegistration service for web-apps"); + } + while (enumeration.hasMoreElements()){ + webAppName = (String) enumeration.nextElement(); + servletContext = DynamicClientWebAppRegistrationManager.webAppContexts.get(webAppName); + requiredDynamicClientRegistration = servletContext.getInitParameter( + DynamicClientWebAppRegistrationConstants.DYNAMIC_CLIENT_REQUIRED_FLAG); + //Java web-app section + if ((requiredDynamicClientRegistration != null) && + (Boolean.parseBoolean(requiredDynamicClientRegistration))) { + //Check whether this is an already registered application if (!dynamicClientWebAppRegistrationManager.isRegisteredOAuthApplication(webAppName)) { - registrationProfile = DynamicClientWebAppRegistrationUtil - .constructRegistrationProfile(oAuthSettings, webAppName); - oAuthApp = dynamicClientWebAppRegistrationManager - .registerOAuthApplication(registrationProfile); + //Construct the RegistrationProfile + registrationProfile = DynamicClientWebAppRegistrationUtil. + constructRegistrationProfile(servletContext, + webAppName); + //Register the OAuth application + oAuthAppDetails = dynamicClientWebAppRegistrationManager.registerOAuthApplication( + registrationProfile); + } else { - oAuthApp = dynamicClientWebAppRegistrationManager.getOAuthApplicationData(webAppName); + oAuthAppDetails = + dynamicClientWebAppRegistrationManager.getOAuthApplicationData(webAppName); + } + } else if (requiredDynamicClientRegistration == null) { + //Jaggery apps + JaggeryOAuthConfigurationSettings jaggeryOAuthConfigurationSettings = DynamicClientWebAppRegistrationUtil + .getJaggeryAppOAuthSettings(servletContext); + if (jaggeryOAuthConfigurationSettings.isRequireDynamicClientRegistration()) { + if (!dynamicClientWebAppRegistrationManager + .isRegisteredOAuthApplication(webAppName)) { + registrationProfile = DynamicClientWebAppRegistrationUtil + .constructRegistrationProfile(jaggeryOAuthConfigurationSettings, webAppName); + oAuthAppDetails = dynamicClientWebAppRegistrationManager + .registerOAuthApplication(registrationProfile); + } else { + oAuthAppDetails = dynamicClientWebAppRegistrationManager + .getOAuthApplicationData(webAppName); + } } } + //Add client credentials to the web-context + if (oAuthAppDetails.getClientKey() != null) { + DynamicClientWebAppRegistrationUtil.addClientCredentialsToWebContext(oAuthAppDetails, + servletContext); + log.info("Added OAuth application credentials to webapp context of webapp : " + webAppName); + } } - DynamicClientWebAppRegistrationUtil.addClientCredentialsToWebContext(oAuthApp, - servletContext); } - -} +} \ No newline at end of file diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/WebAppRegistrationServerStartupObserver.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/WebAppRegistrationServerStartupObserver.java new file mode 100644 index 00000000000..6ed87bc28d0 --- /dev/null +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/WebAppRegistrationServerStartupObserver.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.dynamic.client.web.app.registration; + +import org.wso2.carbon.core.ServerStartupObserver; + +/** + * ServerStartupObserver implementation to initiate the DynamicClientRegistration process for web + * apps after the Carbon server is up and ready. + */ +public class WebAppRegistrationServerStartupObserver implements ServerStartupObserver { + + @Override + public void completingServerStartup() { + + } + + @Override + public void completedServerStartup() { + DynamicClientWebAppRegistrationManager.getInstance().initiateDynamicClientRegistration(); + } +} diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/OAuthSettings.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/JaggeryOAuthConfigurationSettings.java similarity index 95% rename from components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/OAuthSettings.java rename to components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/JaggeryOAuthConfigurationSettings.java index 42ee098f28c..8b9849175c3 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/OAuthSettings.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/JaggeryOAuthConfigurationSettings.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.dynamic.client.web.app.registration; +package org.wso2.carbon.dynamic.client.web.app.registration.dto; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @@ -25,7 +25,7 @@ import javax.xml.bind.annotation.XmlRootElement; * Represents OAuthConfiguration data. */ @XmlRootElement(name = "OAuthSettings") -public class OAuthSettings { +public class JaggeryOAuthConfigurationSettings { private String grantType; private boolean saasApp; diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/OAuthApp.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/OAuthAppDetails.java similarity index 93% rename from components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/OAuthApp.java rename to components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/OAuthAppDetails.java index 7195f55706f..9fc1b359e81 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/OAuthApp.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/OAuthAppDetails.java @@ -16,7 +16,7 @@ * under the License. */ -package org.wso2.carbon.dynamic.client.web.app.registration; +package org.wso2.carbon.dynamic.client.web.app.registration.dto; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @@ -24,8 +24,8 @@ import javax.xml.bind.annotation.XmlRootElement; /** * Represents an OAuth application with basic data. */ -@XmlRootElement(name = "OAuthApp") -public class OAuthApp { +@XmlRootElement(name = "OAuthAppDetails") +public class OAuthAppDetails { private String clientName; private String clientKey; diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/internal/DynamicClientWebAppRegistrationServiceComponent.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/internal/DynamicClientWebAppRegistrationServiceComponent.java index 7950a4dbb87..8ecfc33b2de 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/internal/DynamicClientWebAppRegistrationServiceComponent.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/internal/DynamicClientWebAppRegistrationServiceComponent.java @@ -21,7 +21,10 @@ package org.wso2.carbon.dynamic.client.web.app.registration.internal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; +import org.osgi.util.tracker.ServiceTracker; +import org.wso2.carbon.core.ServerStartupObserver; import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService; +import org.wso2.carbon.dynamic.client.web.app.registration.WebAppRegistrationServerStartupObserver; import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.utils.ConfigurationContextService; @@ -55,16 +58,18 @@ import org.wso2.carbon.utils.ConfigurationContextService; */ public class DynamicClientWebAppRegistrationServiceComponent { + private ServiceTracker serviceTracker; private static Log log = LogFactory.getLog(DynamicClientWebAppRegistrationServiceComponent.class); @SuppressWarnings("unused") protected void activate(ComponentContext componentContext) { - + componentContext.getBundleContext().registerService(ServerStartupObserver.class.getName(), + new WebAppRegistrationServerStartupObserver(), null) ; } @SuppressWarnings("unused") protected void deactivate(ComponentContext componentContext) { - //do nothing + } /** @@ -163,5 +168,4 @@ public class DynamicClientWebAppRegistrationServiceComponent { } DynamicClientWebAppRegistrationDataHolder.getInstance().setConfigurationContextService(null); } - -} +} \ No newline at end of file diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/listner/DynamicClientWebAppDeploymentLifecycleListener.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/listner/DynamicClientWebAppDeploymentLifecycleListener.java index ce8e452a829..aeff85c2a61 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/listner/DynamicClientWebAppDeploymentLifecycleListener.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/listner/DynamicClientWebAppDeploymentLifecycleListener.java @@ -40,7 +40,7 @@ public class DynamicClientWebAppDeploymentLifecycleListener implements Lifecycle public void lifecycleEvent(LifecycleEvent lifecycleEvent) { if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) { StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); - DynamicClientWebAppRegistrationManager.getInstance().initiateDynamicClientRegistrationProcess( + DynamicClientWebAppRegistrationManager.getInstance().saveServletContextToCache( context); } } diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java index 1dd54c40f1f..765b0191e3f 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java @@ -24,8 +24,8 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationException; import org.wso2.carbon.dynamic.client.registration.profile.RegistrationProfile; -import org.wso2.carbon.dynamic.client.web.app.registration.OAuthApp; -import org.wso2.carbon.dynamic.client.web.app.registration.OAuthSettings; +import org.wso2.carbon.dynamic.client.web.app.registration.dto.OAuthAppDetails; +import org.wso2.carbon.dynamic.client.web.app.registration.dto.JaggeryOAuthConfigurationSettings; import org.wso2.carbon.dynamic.client.web.app.registration.internal.DynamicClientWebAppRegistrationDataHolder; import org.wso2.carbon.registry.api.RegistryException; import org.wso2.carbon.registry.api.Resource; @@ -72,7 +72,7 @@ public class DynamicClientWebAppRegistrationUtil { } } - public static OAuthApp getOAuthApplicationData(String appName) + public static OAuthAppDetails getOAuthApplicationData(String appName) throws DynamicClientRegistrationException { Resource resource; String resourcePath = @@ -83,14 +83,14 @@ public class DynamicClientWebAppRegistrationUtil { } resource = DynamicClientWebAppRegistrationUtil.getRegistryResource(resourcePath); if (resource != null) { - JAXBContext context = JAXBContext.newInstance(OAuthApp.class); + JAXBContext context = JAXBContext.newInstance(OAuthAppDetails.class); Unmarshaller unmarshaller = context.createUnmarshaller(); - return (OAuthApp) unmarshaller.unmarshal( + return (OAuthAppDetails) unmarshaller.unmarshal( new StringReader(new String((byte[]) resource.getContent(), Charset .forName( DynamicClientWebAppRegistrationConstants.CharSets.CHARSET_UTF8)))); } - return new OAuthApp(); + return new OAuthAppDetails(); } catch (JAXBException e) { throw new DynamicClientRegistrationException( "Error occurred while parsing the OAuth application data : " + appName, e); @@ -101,7 +101,7 @@ public class DynamicClientWebAppRegistrationUtil { } } - public static boolean putOAuthApplicationData(OAuthApp oAuthApp) + public static boolean putOAuthApplicationData(OAuthAppDetails oAuthAppDetails) throws DynamicClientRegistrationException { boolean status; try { @@ -109,9 +109,9 @@ public class DynamicClientWebAppRegistrationUtil { log.debug("Persisting OAuth application data in Registry"); } StringWriter writer = new StringWriter(); - JAXBContext context = JAXBContext.newInstance(OAuthApp.class); + JAXBContext context = JAXBContext.newInstance(OAuthAppDetails.class); Marshaller marshaller = context.createMarshaller(); - marshaller.marshal(oAuthApp, writer); + marshaller.marshal(oAuthAppDetails, writer); Resource resource = DynamicClientWebAppRegistrationUtil.getGovernanceRegistry().newResource(); @@ -119,17 +119,17 @@ public class DynamicClientWebAppRegistrationUtil { resource.setMediaType(DynamicClientWebAppRegistrationConstants.ContentTypes.MEDIA_TYPE_XML); String resourcePath = DynamicClientWebAppRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH + "/" + - oAuthApp.getWebAppName(); + oAuthAppDetails.getWebAppName(); status = DynamicClientWebAppRegistrationUtil.putRegistryResource(resourcePath, resource); } catch (RegistryException e) { throw new DynamicClientRegistrationException( "Error occurred while persisting OAuth application data : " + - oAuthApp.getClientName(), e); + oAuthAppDetails.getClientName(), e); } catch (JAXBException e) { throw new DynamicClientRegistrationException( "Error occurred while parsing the OAuth application data : " + - oAuthApp.getWebAppName(), e); + oAuthAppDetails.getWebAppName(), e); } return status; } @@ -204,16 +204,16 @@ public class DynamicClientWebAppRegistrationUtil { } public static RegistrationProfile constructRegistrationProfile( - OAuthSettings oAuthSettings, String webAppName) { + JaggeryOAuthConfigurationSettings jaggeryOAuthConfigurationSettings, String webAppName) { RegistrationProfile registrationProfile = new RegistrationProfile(); - if (oAuthSettings != null) { - registrationProfile.setGrantType(oAuthSettings.getGrantType()); - registrationProfile.setTokenScope(oAuthSettings.getTokenScope()); + if (jaggeryOAuthConfigurationSettings != null) { + registrationProfile.setGrantType(jaggeryOAuthConfigurationSettings.getGrantType()); + registrationProfile.setTokenScope(jaggeryOAuthConfigurationSettings.getTokenScope()); registrationProfile.setClientName(webAppName); - registrationProfile.setSaasApp(oAuthSettings.isSaasApp()); + registrationProfile.setSaasApp(jaggeryOAuthConfigurationSettings.isSaasApp()); registrationProfile.setOwner(DynamicClientWebAppRegistrationUtil.getUserName()); - if (oAuthSettings.getCallbackURL() != null) { - registrationProfile.setCallbackUrl(oAuthSettings.getCallbackURL()); + if (jaggeryOAuthConfigurationSettings.getCallbackURL() != null) { + registrationProfile.setCallbackUrl(jaggeryOAuthConfigurationSettings.getCallbackURL()); } else { registrationProfile.setCallbackUrl( DynamicClientWebAppRegistrationUtil.getCallbackUrl(webAppName)); @@ -240,8 +240,9 @@ public class DynamicClientWebAppRegistrationUtil { return status; } - public static OAuthSettings getJaggeryAppOAuthSettings(ServletContext servletContext) { - OAuthSettings oAuthSettings = new OAuthSettings(); + public static JaggeryOAuthConfigurationSettings getJaggeryAppOAuthSettings(ServletContext servletContext) { + JaggeryOAuthConfigurationSettings + jaggeryOAuthConfigurationSettings = new JaggeryOAuthConfigurationSettings(); try { InputStream inputStream = servletContext.getResourceAsStream(JAGGERY_APP_OAUTH_CONFIG_PATH); @@ -253,30 +254,30 @@ public class DynamicClientWebAppRegistrationUtil { String key = reader.nextName(); switch (key) { case DynamicClientWebAppRegistrationConstants.DYNAMIC_CLIENT_REQUIRED_FLAG: - oAuthSettings.setRequireDynamicClientRegistration(reader.nextBoolean()); + jaggeryOAuthConfigurationSettings.setRequireDynamicClientRegistration(reader.nextBoolean()); break; case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_GRANT_TYPE: - oAuthSettings.setGrantType(reader.nextString()); + jaggeryOAuthConfigurationSettings.setGrantType(reader.nextString()); break; case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_TOKEN_SCOPE: - oAuthSettings.setTokenScope(reader.nextString()); + jaggeryOAuthConfigurationSettings.setTokenScope(reader.nextString()); break; case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_SAAS_APP: - oAuthSettings.setSaasApp(reader.nextBoolean()); + jaggeryOAuthConfigurationSettings.setSaasApp(reader.nextBoolean()); break; case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_CALLBACK_URL: - oAuthSettings.setCallbackURL(reader.nextString()); + jaggeryOAuthConfigurationSettings.setCallbackURL(reader.nextString()); break; } } - return oAuthSettings; + return jaggeryOAuthConfigurationSettings; } } catch (UnsupportedEncodingException e) { log.error("Error occurred while initializing OAuth settings for the Jaggery app.", e); } catch (IOException e) { log.error("Error occurred while initializing OAuth settings for the Jaggery app.", e); } - return oAuthSettings; + return jaggeryOAuthConfigurationSettings; } public static String getServerBaseUrl() { @@ -304,18 +305,18 @@ public class DynamicClientWebAppRegistrationUtil { return getServerBaseUrl() + "/" + context; } - public static void addClientCredentialsToWebContext(OAuthApp oAuthApp, + public static void addClientCredentialsToWebContext(OAuthAppDetails oAuthAppDetails, ServletContext servletContext) { - if(oAuthApp != null){ + if(oAuthAppDetails != null){ //Check for client credentials - if ((oAuthApp.getClientKey() != null && !oAuthApp.getClientKey().isEmpty()) && - (oAuthApp.getClientSecret() != null && !oAuthApp.getClientSecret().isEmpty())) { + if ((oAuthAppDetails.getClientKey() != null && !oAuthAppDetails.getClientKey().isEmpty()) && + (oAuthAppDetails.getClientSecret() != null && !oAuthAppDetails.getClientSecret().isEmpty())) { servletContext.setAttribute(DynamicClientWebAppRegistrationConstants.OAUTH_CLIENT_KEY, - oAuthApp.getClientKey()); + oAuthAppDetails.getClientKey()); servletContext.setAttribute(DynamicClientWebAppRegistrationConstants.OAUTH_CLIENT_SECRET, - oAuthApp.getClientSecret()); + oAuthAppDetails.getClientSecret()); } else { - log.warn("Client credentials not found for web app : " + oAuthApp.getWebAppName()); + log.warn("Client credentials not found for web app : " + oAuthAppDetails.getWebAppName()); } } } diff --git a/pom.xml b/pom.xml index 26df26d760a..d3b520e7bbd 100644 --- a/pom.xml +++ b/pom.xml @@ -152,10 +152,6 @@ org.eclipse.osgi org.eclipse.osgi - - org.eclipse.osgi - org.eclipse.osgi.services - @@ -410,6 +406,11 @@ org.eclipse.osgi.services 3.3.100.v20120522-1822 + + org.osgi.ut + org.eclipse.osgi + 3.3.100.v20120522-1822 + From 45ce4dbe4e11ac25318087c9013967cee1e6e7f9 Mon Sep 17 00:00:00 2001 From: Dulitha Wijewantha Date: Mon, 12 Oct 2015 12:09:21 +0530 Subject: [PATCH 05/23] Policy Updating * Fixed issues regarding roles updating for policy * Fixed the relevent test cases JIRA:- https://wso2.org/jira/browse/EMM-812 --- .../carbon/policy/mgt/core/dao/PolicyDAO.java | 9 +++- .../mgt/core/dao/impl/PolicyDAOImpl.java | 44 +++++++++++++------ .../mgt/core/mgt/impl/PolicyManagerImpl.java | 13 +++--- .../mgt/core/util/PolicyManagerUtil.java | 5 +-- .../core/util/SetReferenceTransformer.java | 42 ++++++++++++++++++ .../policy/mgt/core/PolicyDAOTestCase.java | 8 ++-- 6 files changed, 93 insertions(+), 28 deletions(-) create mode 100644 components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/SetReferenceTransformer.java diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java index 9f5ba5b2550..d684525148e 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java @@ -19,11 +19,9 @@ package org.wso2.carbon.policy.mgt.core.dao; import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.policy.mgt.common.Criterion; import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.PolicyCriterion; -import org.wso2.carbon.policy.mgt.common.ProfileFeature; import java.util.HashMap; import java.util.List; @@ -34,6 +32,13 @@ public interface PolicyDAO { Policy addPolicy(String deviceType, Policy policy) throws PolicyManagerDAOException; + /** + * This method is used to add/update the roles associated with the policy. + * @param roleNames - List of the roles that needs to be applied + * @param policy - policy object with the current role list + * @return + * @throws PolicyManagerDAOException + */ Policy addPolicyToRole(List roleNames, Policy policy) throws PolicyManagerDAOException; Policy addPolicyToUser(List usernameList, Policy policy) throws PolicyManagerDAOException; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java index e1921f1aaca..b33b71289e2 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java @@ -22,17 +22,15 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.policy.mgt.common.Criterion; import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.PolicyCriterion; -import org.wso2.carbon.policy.mgt.common.ProfileFeature; -import org.wso2.carbon.policy.mgt.core.dao.FeatureManagerDAOException; import org.wso2.carbon.policy.mgt.core.dao.PolicyDAO; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException; import org.wso2.carbon.policy.mgt.core.dao.util.PolicyManagementDAOUtil; import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; +import org.wso2.carbon.policy.mgt.core.util.SetReferenceTransformer; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -70,23 +68,43 @@ public class PolicyDAOImpl implements PolicyDAO { } @Override - public Policy addPolicyToRole(List roleNames, Policy policy) throws PolicyManagerDAOException { + public Policy addPolicyToRole(List rolesToAdd, Policy policy) throws PolicyManagerDAOException { Connection conn; - PreparedStatement stmt = null; + PreparedStatement insertStmt = null; + PreparedStatement deleteStmt = null; + final List currentRoles = policy.getRoles(); + + SetReferenceTransformer transformer = new SetReferenceTransformer(); + + transformer.transform(currentRoles, rolesToAdd); + rolesToAdd = transformer.getObjectsToAdd(); + List rolesToDelete = transformer.getObjectsToRemove(); try { conn = this.getConnection(); - String query = "INSERT INTO DM_ROLE_POLICY (ROLE_NAME, POLICY_ID) VALUES (?, ?)"; - stmt = conn.prepareStatement(query); - for (String role : roleNames) { - stmt.setString(1, role); - stmt.setInt(2, policy.getId()); - stmt.addBatch(); + if (rolesToAdd.size() > 0){ + String query = "INSERT INTO DM_ROLE_POLICY (ROLE_NAME, POLICY_ID) VALUES (?, ?)"; + insertStmt = conn.prepareStatement(query); + for (String role : rolesToAdd) { + insertStmt.setString(1, role); + insertStmt.setInt(2, policy.getId()); + insertStmt.addBatch(); + } + insertStmt.executeBatch(); + } + if (rolesToAdd.size() > 0){ + String deleteQuery = "DELETE FROM DM_ROLE_POLICY WHERE ROLE_NAME=? AND POLICY_ID=?"; + deleteStmt = conn.prepareStatement(deleteQuery); + for (String role : rolesToDelete) { + deleteStmt.setString(1, role); + deleteStmt.setInt(2, policy.getId()); + deleteStmt.addBatch(); + } + deleteStmt.executeBatch(); } - stmt.executeBatch(); } catch (SQLException e) { throw new PolicyManagerDAOException("Error occurred while adding the role name with policy to database", e); } finally { - PolicyManagementDAOUtil.cleanupResources(stmt, null); + PolicyManagementDAOUtil.cleanupResources(insertStmt, null); } return policy; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java index a9f1a10fd86..7474651d0d2 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java @@ -25,13 +25,11 @@ import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; -import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; import org.wso2.carbon.policy.mgt.common.*; -import org.wso2.carbon.policy.mgt.core.cache.PolicyCacheManager; import org.wso2.carbon.policy.mgt.core.cache.impl.PolicyCacheManagerImpl; import org.wso2.carbon.policy.mgt.core.dao.*; import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; @@ -136,6 +134,9 @@ public class PolicyManagerImpl implements PolicyManager { public Policy updatePolicy(Policy policy) throws PolicyManagementException { try { + // Previous policy needs to be obtained before begining the transaction + Policy previousPolicy = getPolicy(policy.getId()); + PolicyManagementDAOFactory.beginTransaction(); // This will keep track of the policies updated. policyDAO.recordUpdatedPolicy(policy); @@ -146,16 +147,18 @@ public class PolicyManagerImpl implements PolicyManager { .getProfileId()); policyDAO.deleteAllPolicyRelatedConfigs(policy.getId()); + + if (policy.getUsers() != null) { - policyDAO.addPolicyToUser(policy.getUsers(), policy); + policyDAO.addPolicyToUser(policy.getUsers(), previousPolicy); } if (policy.getRoles() != null) { - policyDAO.addPolicyToRole(policy.getRoles(), policy); + policyDAO.addPolicyToRole(policy.getRoles(), previousPolicy); } if (policy.getDevices() != null) { - policyDAO.addPolicyToDevice(policy.getDevices(), policy); + policyDAO.addPolicyToDevice(policy.getDevices(), previousPolicy); } if (policy.getPolicyCriterias() != null) { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java index 982b3859a79..a9d292c732d 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java @@ -41,10 +41,7 @@ import javax.xml.parsers.DocumentBuilderFactory; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.ObjectOutputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.List; +import java.util.*; public class PolicyManagerUtil { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/SetReferenceTransformer.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/SetReferenceTransformer.java new file mode 100644 index 00000000000..f9d78e05fc6 --- /dev/null +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/SetReferenceTransformer.java @@ -0,0 +1,42 @@ +package org.wso2.carbon.policy.mgt.core.util; + +import java.util.ArrayList; +import java.util.List; +import java.util.TreeSet; + +public class SetReferenceTransformer{ + private List objectsToRemove; + private List objectsToAdd; + + /** + * Use the Set theory to find the objects to delete and objects to add + + The difference of objects in existingSet and newSet needed to be deleted + + new roles to add = newSet - The intersection of roles in existingSet and newSet + * @param currentList + * @param nextList + */ + public void transform(List currentList, List nextList){ + TreeSet existingSet = new TreeSet(currentList); + TreeSet newSet = new TreeSet(nextList);; + + existingSet.removeAll(newSet); + + objectsToRemove = new ArrayList<>(existingSet); + + // Clearing and re-initializing the set + existingSet = new TreeSet(currentList); + + newSet.removeAll(existingSet); + objectsToAdd = new ArrayList(newSet); + } + + public List getObjectsToRemove() { + return objectsToRemove; + } + + public List getObjectsToAdd() { + return objectsToAdd; + } +} \ No newline at end of file diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java index ffc592b3351..730e02071cb 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java @@ -27,15 +27,12 @@ import org.wso2.carbon.device.mgt.core.dao.*; import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; -import org.wso2.carbon.policy.mgt.common.*; import org.wso2.carbon.policy.mgt.common.FeatureManagementException; -import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; -import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException; +import org.wso2.carbon.policy.mgt.common.*; import org.wso2.carbon.policy.mgt.core.impl.PolicyAdministratorPointImpl; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.util.*; -import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Properties; @@ -163,6 +160,8 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { roles.add("Test_ROLE_02"); roles.add("Test_ROLE_03"); + policy = pap.getPolicy(policy.getId()); + pap.addPolicyToRole(roles, policy); } @@ -312,6 +311,7 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { policy = pap.addPolicy(policy); pap.activatePolicy(policy.getId()); List users = new ArrayList<>(); + log.debug(policy.getRoles().size()); users.add("Udara"); users.add("Dileesha"); policy.setUsers(users); From 831fed6d3817332db640f6f3f0eed2232492a309 Mon Sep 17 00:00:00 2001 From: Kamidu Sachith Date: Mon, 12 Oct 2015 17:42:10 +0530 Subject: [PATCH 06/23] Resolving imports --- .../backend-oauth-authenticator/pom.xml | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/components/identity-extensions/backend-oauth-authenticator/pom.xml b/components/identity-extensions/backend-oauth-authenticator/pom.xml index 37cc5274f67..fdf8334f830 100644 --- a/components/identity-extensions/backend-oauth-authenticator/pom.xml +++ b/components/identity-extensions/backend-oauth-authenticator/pom.xml @@ -101,7 +101,17 @@ org.wso2.carbon.identity.oauth2, org.wso2.carbon.identity.oauth2.dto, org.wso2.carbon.user.core.service, - org.wso2.carbon.utils.multitenancy + org.wso2.carbon.utils.multitenancy, + org.apache.axis2.client, + org.apache.axis2.context, + org.apache.axis2.transport.http, + org.apache.commons.httpclient, + org.osgi.framework, + org.osgi.service.component, + org.wso2.carbon.core.security, + org.wso2.carbon.core.services.authentication, + org.wso2.carbon.identity.oauth2.stub, + org.wso2.carbon.identity.oauth2.stub.dto org.wso2.carbon.identity.authenticator.backend.oauth.*; From 8cc38c87f5b511443ec30cefb1d9d884899dbaa0 Mon Sep 17 00:00:00 2001 From: Kamidu Sachith Date: Mon, 12 Oct 2015 17:57:43 +0530 Subject: [PATCH 07/23] requested modification --- .../framework/authenticator/OAuthAuthenticator.java | 7 ++++--- pom.xml | 1 - 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java index 3fd3027592c..61867b9c9b7 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java @@ -84,9 +84,10 @@ public class OAuthAuthenticator implements WebappAuthenticator { return Status.CONTINUE; } String apiVersion = tokenizer.nextToken(); - String authLevel = authenticator.getResourceAuthenticationScheme(context, apiVersion, - requestUri, - requestMethod); + String authLevel = "any"; +// String authLevel = authenticator.getResourceAuthenticationScheme(context, apiVersion, +// requestUri, +// requestMethod); try { if (Constants.NO_MATCHING_AUTH_SCHEME.equals(authLevel)) { AuthenticationFrameworkUtil diff --git a/pom.xml b/pom.xml index fbfa9406f04..356b7883479 100644 --- a/pom.xml +++ b/pom.xml @@ -946,7 +946,6 @@ org.wso2.carbon.identity.application.authentication.framework ${carbon.identity.version} - org.wso2.carbon.identity org.wso2.carbon.identity.oauth From d932522d375a4cd3ef032a143ef9c0b4a43aee90 Mon Sep 17 00:00:00 2001 From: Kamidu Sachith Date: Mon, 12 Oct 2015 18:03:13 +0530 Subject: [PATCH 08/23] refactoring class --- .../authenticator/backend/oauth/OauthAuthenticator.java | 4 ++-- .../backend/oauth/validator/OAuth2TokenValidator.java | 4 ++-- ...alidationRespond.java => OAuthValidationResponse.java} | 4 ++-- .../oauth/validator/impl/ExternalOAuthValidator.java | 8 ++++---- .../backend/oauth/validator/impl/LocalOAuthValidator.java | 8 ++++---- 5 files changed, 14 insertions(+), 14 deletions(-) rename components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/{OAuthValidationRespond.java => OAuthValidationResponse.java} (92%) diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticator.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticator.java index adfcf71214a..beaf5c70b07 100755 --- a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticator.java +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticator.java @@ -24,9 +24,9 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.core.security.AuthenticatorsConfiguration; import org.wso2.carbon.core.services.authentication.CarbonServerAuthenticator; +import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationResponse; import org.wso2.carbon.utils.ServerConstants; import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator; -import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationRespond; import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidatorFactory; import javax.servlet.http.HttpServletRequest; @@ -94,7 +94,7 @@ public class OauthAuthenticator implements CarbonServerAuthenticator { String headerValue = httpServletRequest.getHeader(HTTPConstants.HEADER_AUTHORIZATION); String[] headerPart = headerValue.trim().split(OauthAuthenticatorConstants.SPLITING_CHARACTOR); String accessToken = headerPart[ACCESS_TOKEN_INDEX]; - OAuthValidationRespond response = null; + OAuthValidationResponse response = null; try { response = tokenValidator.validateToken(accessToken); } catch (RemoteException e) { diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuth2TokenValidator.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuth2TokenValidator.java index 7382fe1370d..c0c5c8662a6 100755 --- a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuth2TokenValidator.java +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuth2TokenValidator.java @@ -28,7 +28,7 @@ public interface OAuth2TokenValidator { * containing the validity and user details if valid. * * @param accessToken which need to be validated. - * @return OAuthValidationRespond with the validated results. + * @return OAuthValidationResponse with the validated results. */ - OAuthValidationRespond validateToken(String accessToken) throws RemoteException; + OAuthValidationResponse validateToken(String accessToken) throws RemoteException; } diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidationRespond.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidationResponse.java similarity index 92% rename from components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidationRespond.java rename to components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidationResponse.java index 346ac2ac303..b794a22424e 100755 --- a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidationRespond.java +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidationResponse.java @@ -21,12 +21,12 @@ package org.wso2.carbon.identity.authenticator.backend.oauth.validator; * This class hold the validation information which can be retrieve by both remote and in house IDPs */ @SuppressWarnings("unused") -public class OAuthValidationRespond { +public class OAuthValidationResponse { private String userName; private String tenantDomain; private boolean isValid; - public OAuthValidationRespond(String userName, String tenantDomain, boolean isValid) { + public OAuthValidationResponse(String userName, String tenantDomain, boolean isValid) { this.userName = userName; this.tenantDomain = tenantDomain; this.isValid = isValid; diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java index 0c0836165e2..be05c37fc8d 100755 --- a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java @@ -23,7 +23,7 @@ import org.apache.axis2.transport.http.HTTPConstants; import org.apache.commons.httpclient.Header; import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorConstants; import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator; -import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationRespond; +import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationResponse; import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2ClientApplicationDTO; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO; @@ -49,9 +49,9 @@ public class ExternalOAuthValidator implements OAuth2TokenValidator{ * containing the validity and user details if valid. * * @param token which need to be validated. - * @return OAuthValidationRespond with the validated results. + * @return OAuthValidationResponse with the validated results. */ - public OAuthValidationRespond validateToken(String token) throws RemoteException { + public OAuthValidationResponse validateToken(String token) throws RemoteException { OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO(); OAuth2TokenValidationRequestDTO_OAuth2AccessToken accessToken = new OAuth2TokenValidationRequestDTO_OAuth2AccessToken(); @@ -80,6 +80,6 @@ public class ExternalOAuthValidator implements OAuth2TokenValidator{ tenantDomain = MultitenantUtils.getTenantDomain(respond.getAccessTokenValidationResponse().getAuthorizedUser()); } - return new OAuthValidationRespond(userName,tenantDomain,isValid); + return new OAuthValidationResponse(userName,tenantDomain,isValid); } } diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java index ea7edf1d13a..fb6eb4b3b90 100755 --- a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java @@ -17,13 +17,13 @@ */ package org.wso2.carbon.identity.authenticator.backend.oauth.validator.impl; +import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationResponse; import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; import org.wso2.carbon.identity.oauth2.dto.OAuth2ClientApplicationDTO; import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorConstants; import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator; -import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationRespond; /** * Handles the authentication using the inbuilt IS features. @@ -34,9 +34,9 @@ public class LocalOAuthValidator implements OAuth2TokenValidator { * containing the validity and user details if valid. * * @param token which need to be validated. - * @return OAuthValidationRespond with the validated results. + * @return OAuthValidationResponse with the validated results. */ - public OAuthValidationRespond validateToken(String token) { + public OAuthValidationResponse validateToken(String token) { OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO(); OAuth2TokenValidationRequestDTO.OAuth2AccessToken accessToken = validationRequest.new OAuth2AccessToken(); @@ -55,6 +55,6 @@ public class LocalOAuthValidator implements OAuth2TokenValidator { tenantDomain = MultitenantUtils.getTenantDomain(respond.getAccessTokenValidationResponse().getAuthorizedUser()); } - return new OAuthValidationRespond(userName,tenantDomain,isValid); + return new OAuthValidationResponse(userName,tenantDomain,isValid); } } From 743f394fb98485840968a26fd4fdc49979c33f6e Mon Sep 17 00:00:00 2001 From: Kamidu Sachith Date: Mon, 12 Oct 2015 18:11:44 +0530 Subject: [PATCH 09/23] Requested Modifications --- .../impl/ExternalOAuthValidator.java | 20 +++++++++---------- .../validator/impl/LocalOAuthValidator.java | 8 ++++---- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java index be05c37fc8d..f05bd7dea06 100755 --- a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java @@ -58,27 +58,27 @@ public class ExternalOAuthValidator implements OAuth2TokenValidator{ accessToken.setTokenType(OauthAuthenticatorConstants.BEARER_TOKEN_TYPE); accessToken.setIdentifier(token); validationRequest.setAccessToken(accessToken); - OAuth2TokenValidationServiceStub validationService = + OAuth2TokenValidationServiceStub tokenValidationService = new OAuth2TokenValidationServiceStub(hostURL); - ServiceClient client = validationService._getServiceClient(); + ServiceClient client = tokenValidationService._getServiceClient(); Options options = client.getOptions(); - List
list = new ArrayList<>(); + List
headerList = new ArrayList<>(); Header header = new Header(); header.setName(HTTPConstants.HEADER_AUTHORIZATION); header.setValue(OauthAuthenticatorConstants.AUTHORIZATION_HEADER_PREFIX_BEARER+ " " + token); - list.add(header); - options.setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_HEADERS, list); + headerList.add(header); + options.setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_HEADERS, headerList); client.setOptions(options); - OAuth2ClientApplicationDTO respond = - validationService.findOAuthConsumerIfTokenIsValid(validationRequest); - boolean isValid = respond.getAccessTokenValidationResponse().getValid(); + OAuth2ClientApplicationDTO clientApplicationDTO = + tokenValidationService.findOAuthConsumerIfTokenIsValid(validationRequest); + boolean isValid = clientApplicationDTO.getAccessTokenValidationResponse().getValid(); String userName = null; String tenantDomain = null; if(isValid){ userName = MultitenantUtils.getTenantAwareUsername( - respond.getAccessTokenValidationResponse().getAuthorizedUser()); + clientApplicationDTO.getAccessTokenValidationResponse().getAuthorizedUser()); tenantDomain = - MultitenantUtils.getTenantDomain(respond.getAccessTokenValidationResponse().getAuthorizedUser()); + MultitenantUtils.getTenantDomain(clientApplicationDTO.getAccessTokenValidationResponse().getAuthorizedUser()); } return new OAuthValidationResponse(userName,tenantDomain,isValid); } diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java index fb6eb4b3b90..5595b19d434 100755 --- a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java @@ -44,16 +44,16 @@ public class LocalOAuthValidator implements OAuth2TokenValidator { accessToken.setIdentifier(token); validationRequest.setAccessToken(accessToken); OAuth2TokenValidationService validationService = new OAuth2TokenValidationService(); - OAuth2ClientApplicationDTO respond = validationService. + OAuth2ClientApplicationDTO clientApplicationDTO = validationService. findOAuthConsumerIfTokenIsValid(validationRequest); - boolean isValid = respond.getAccessTokenValidationResponse().isValid(); + boolean isValid = clientApplicationDTO.getAccessTokenValidationResponse().isValid(); String userName = null; String tenantDomain = null; if(isValid){ userName = MultitenantUtils.getTenantAwareUsername( - respond.getAccessTokenValidationResponse().getAuthorizedUser()); + clientApplicationDTO.getAccessTokenValidationResponse().getAuthorizedUser()); tenantDomain = - MultitenantUtils.getTenantDomain(respond.getAccessTokenValidationResponse().getAuthorizedUser()); + MultitenantUtils.getTenantDomain(clientApplicationDTO.getAccessTokenValidationResponse().getAuthorizedUser()); } return new OAuthValidationResponse(userName,tenantDomain,isValid); } From fe355b3184828d6c9f3932a00ee5d8b59f301778 Mon Sep 17 00:00:00 2001 From: Kamidu Sachith Date: Mon, 12 Oct 2015 18:13:46 +0530 Subject: [PATCH 10/23] Romoving Temporary Solutions --- .../framework/authenticator/OAuthAuthenticator.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java index 61867b9c9b7..3fd3027592c 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java @@ -84,10 +84,9 @@ public class OAuthAuthenticator implements WebappAuthenticator { return Status.CONTINUE; } String apiVersion = tokenizer.nextToken(); - String authLevel = "any"; -// String authLevel = authenticator.getResourceAuthenticationScheme(context, apiVersion, -// requestUri, -// requestMethod); + String authLevel = authenticator.getResourceAuthenticationScheme(context, apiVersion, + requestUri, + requestMethod); try { if (Constants.NO_MATCHING_AUTH_SCHEME.equals(authLevel)) { AuthenticationFrameworkUtil From 824f57b5d2491818edeea9960bb4941e5c0f86bc Mon Sep 17 00:00:00 2001 From: Kamidu Sachith Date: Mon, 12 Oct 2015 18:36:59 +0530 Subject: [PATCH 11/23] Change the code for better performance --- .../validator/impl/ExternalOAuthValidator.java | 14 +++++++------- .../validator/impl/LocalOAuthValidator.java | 16 ++++++++-------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java index f05bd7dea06..e68088fe63f 100755 --- a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java @@ -25,9 +25,9 @@ import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorCo import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator; import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationResponse; import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; -import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2ClientApplicationDTO; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_OAuth2AccessToken; +import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import java.rmi.RemoteException; @@ -69,16 +69,16 @@ public class ExternalOAuthValidator implements OAuth2TokenValidator{ headerList.add(header); options.setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_HEADERS, headerList); client.setOptions(options); - OAuth2ClientApplicationDTO clientApplicationDTO = - tokenValidationService.findOAuthConsumerIfTokenIsValid(validationRequest); - boolean isValid = clientApplicationDTO.getAccessTokenValidationResponse().getValid(); + OAuth2TokenValidationResponseDTO tokenValidationResponse = + tokenValidationService.findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse(); + boolean isValid = tokenValidationResponse.getValid(); String userName = null; String tenantDomain = null; if(isValid){ userName = MultitenantUtils.getTenantAwareUsername( - clientApplicationDTO.getAccessTokenValidationResponse().getAuthorizedUser()); - tenantDomain = - MultitenantUtils.getTenantDomain(clientApplicationDTO.getAccessTokenValidationResponse().getAuthorizedUser()); + tokenValidationResponse.getAuthorizedUser()); + tenantDomain = MultitenantUtils. + getTenantDomain(tokenValidationResponse.getAuthorizedUser()); } return new OAuthValidationResponse(userName,tenantDomain,isValid); } diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java index 5595b19d434..2deb2b3b36d 100755 --- a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/LocalOAuthValidator.java @@ -17,13 +17,13 @@ */ package org.wso2.carbon.identity.authenticator.backend.oauth.validator.impl; +import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorConstants; +import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator; import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuthValidationResponse; import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; -import org.wso2.carbon.identity.oauth2.dto.OAuth2ClientApplicationDTO; import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO; +import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import org.wso2.carbon.identity.authenticator.backend.oauth.OauthAuthenticatorConstants; -import org.wso2.carbon.identity.authenticator.backend.oauth.validator.OAuth2TokenValidator; /** * Handles the authentication using the inbuilt IS features. @@ -44,16 +44,16 @@ public class LocalOAuthValidator implements OAuth2TokenValidator { accessToken.setIdentifier(token); validationRequest.setAccessToken(accessToken); OAuth2TokenValidationService validationService = new OAuth2TokenValidationService(); - OAuth2ClientApplicationDTO clientApplicationDTO = validationService. - findOAuthConsumerIfTokenIsValid(validationRequest); - boolean isValid = clientApplicationDTO.getAccessTokenValidationResponse().isValid(); + OAuth2TokenValidationResponseDTO tokenValidationResponse = validationService. + findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse(); + boolean isValid = tokenValidationResponse.isValid(); String userName = null; String tenantDomain = null; if(isValid){ userName = MultitenantUtils.getTenantAwareUsername( - clientApplicationDTO.getAccessTokenValidationResponse().getAuthorizedUser()); + tokenValidationResponse.getAuthorizedUser()); tenantDomain = - MultitenantUtils.getTenantDomain(clientApplicationDTO.getAccessTokenValidationResponse().getAuthorizedUser()); + MultitenantUtils.getTenantDomain(tokenValidationResponse.getAuthorizedUser()); } return new OAuthValidationResponse(userName,tenantDomain,isValid); } From a66949c7e0f599dada46cf390fb9b0e399522da7 Mon Sep 17 00:00:00 2001 From: Kamidu Sachith Date: Mon, 12 Oct 2015 18:45:32 +0530 Subject: [PATCH 12/23] Code Fixing --- .../backend/oauth/validator/impl/ExternalOAuthValidator.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java index e68088fe63f..8d8a1015376 100755 --- a/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/impl/ExternalOAuthValidator.java @@ -69,8 +69,8 @@ public class ExternalOAuthValidator implements OAuth2TokenValidator{ headerList.add(header); options.setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_HEADERS, headerList); client.setOptions(options); - OAuth2TokenValidationResponseDTO tokenValidationResponse = - tokenValidationService.findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse(); + OAuth2TokenValidationResponseDTO tokenValidationResponse = tokenValidationService. + findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse(); boolean isValid = tokenValidationResponse.getValid(); String userName = null; String tenantDomain = null; From 81034c84f5bf3c08725191b35363196224b3f3d6 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Mon, 12 Oct 2015 18:59:41 +0530 Subject: [PATCH 13/23] Fixing the method name issue in policy manager service --- .../wso2/carbon/policy/mgt/core/PolicyManagerService.java | 2 +- .../carbon/policy/mgt/core/PolicyManagerServiceImpl.java | 5 +---- .../policy/mgt/core/service/PolicyManagementService.java | 4 ++-- 3 files changed, 4 insertions(+), 7 deletions(-) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerService.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerService.java index 15ed689e4b5..f4514a2c0d0 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerService.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerService.java @@ -69,7 +69,7 @@ public interface PolicyManagerService { Policy getAppliedPolicyToDevice(DeviceIdentifier deviceIdentifier) throws PolicyManagementException; - List CheckPolicyCompliance(DeviceIdentifier deviceIdentifier, Object + List checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Object deviceResponse) throws PolicyComplianceException; boolean checkCompliance(DeviceIdentifier deviceIdentifier, Object response) throws PolicyComplianceException; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImpl.java index 1ad71fa0f93..2027c10a7f8 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerServiceImpl.java @@ -22,10 +22,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.Feature; -import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; -import org.wso2.carbon.device.mgt.core.operation.mgt.PolicyOperation; -import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; import org.wso2.carbon.policy.mgt.common.*; import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData; import org.wso2.carbon.policy.mgt.common.monitor.ComplianceFeature; @@ -170,7 +167,7 @@ public class PolicyManagerServiceImpl implements PolicyManagerService { } @Override - public List CheckPolicyCompliance(DeviceIdentifier deviceIdentifier, Object + public List checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Object deviceResponse) throws PolicyComplianceException { return monitoringManager.checkPolicyCompliance(deviceIdentifier, deviceResponse); } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/service/PolicyManagementService.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/service/PolicyManagementService.java index 648fba4aeda..9be3b71b967 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/service/PolicyManagementService.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/service/PolicyManagementService.java @@ -122,9 +122,9 @@ public class PolicyManagementService implements PolicyManagerService { } @Override - public List CheckPolicyCompliance(DeviceIdentifier deviceIdentifier, Object + public List checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Object deviceResponse) throws PolicyComplianceException { - return policyManagerService.CheckPolicyCompliance(deviceIdentifier, deviceResponse); + return policyManagerService.checkPolicyCompliance(deviceIdentifier, deviceResponse); } @Override From d4eab9f86e9feaa20374662deace6e094494fa43 Mon Sep 17 00:00:00 2001 From: harshanl Date: Mon, 12 Oct 2015 19:48:35 +0530 Subject: [PATCH 14/23] Code refactored. --- .../mgt/core/permission/mgt/PermissionUtils.java | 10 +++++----- .../dynamic/client/web/DynamicClientUtil.java | 2 +- .../impl/DynamicClientRegistrationImpl.java | 13 ++++++------- .../DynamicClientRegistrationServiceComponent.java | 1 - 4 files changed, 12 insertions(+), 14 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionUtils.java index d81d7a157c6..3ed44c63b1a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionUtils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionUtils.java @@ -39,8 +39,8 @@ import java.util.StringTokenizer; */ public class PermissionUtils { - public static String ADMIN_PERMISSION_REGISTRY_PATH = "/permission/admin"; - public static String PERMISSION_PROPERTY_NAME = "name"; + public static final String ADMIN_PERMISSION_REGISTRY_PATH = "/permission/admin"; + public static final String PERMISSION_PROPERTY_NAME = "name"; public static Registry getGovernanceRegistry() throws PermissionManagementException { try { @@ -78,11 +78,11 @@ public class PermissionUtils { try { StringTokenizer tokenizer = new StringTokenizer(permission.getPath(), "/"); String lastToken = "", currentToken, tempPath; - while(tokenizer.hasMoreTokens()){ + while(tokenizer.hasMoreTokens()) { currentToken = tokenizer.nextToken(); tempPath = lastToken + "/" + currentToken; - if(!checkResourceExists(tempPath)){ - createRegistryCollection(tempPath, currentToken.substring(0)); + if(!checkResourceExists(tempPath)) { + createRegistryCollection(tempPath, currentToken); } lastToken = tempPath; } diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/DynamicClientUtil.java b/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/DynamicClientUtil.java index 21f2aec0181..5025a796bf3 100644 --- a/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/DynamicClientUtil.java +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/DynamicClientUtil.java @@ -22,7 +22,7 @@ import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService; /** - * Created by harshan on 9/8/15. + * Holds the utility methods used by Dynamic-Client web bundle. */ public class DynamicClientUtil { diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationImpl.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationImpl.java index 3c2c49f0028..fcd1c7c1330 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationImpl.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationImpl.java @@ -38,7 +38,6 @@ import org.wso2.carbon.identity.sso.saml.admin.SAMLSSOConfigAdmin; import org.wso2.carbon.identity.sso.saml.dto.SAMLSSOServiceProviderDTO; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; - import java.util.Arrays; /** @@ -95,16 +94,16 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS if (jsonObject.has(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS)) { oAuthApplicationInfo .addParameter(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS, - jsonObject - .get(ApplicationConstants.ClientMetadata. - OAUTH_REDIRECT_URIS)); + jsonObject + .get(ApplicationConstants.ClientMetadata. + OAUTH_REDIRECT_URIS)); } if (jsonObject.has(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT)) { oAuthApplicationInfo.addParameter(ApplicationConstants.ClientMetadata. - OAUTH_CLIENT_GRANT, jsonObject - .get(ApplicationConstants.ClientMetadata. - OAUTH_CLIENT_GRANT)); + OAUTH_CLIENT_GRANT, jsonObject + .get(ApplicationConstants.ClientMetadata. + OAUTH_CLIENT_GRANT)); } } catch (JSONException e) { throw new DynamicClientRegistrationException( diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java index d01b7fa5247..68d7ef02a07 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java @@ -24,7 +24,6 @@ import org.osgi.service.component.ComponentContext; import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService; import org.wso2.carbon.dynamic.client.registration.impl.DynamicClientRegistrationImpl; import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; -import org.wso2.carbon.identity.core.util.IdentityCoreInitializedEvent; /** * @scr.component name="org.wso2.carbon.dynamic.client.registration" immediate="true" From 5c215189d10e11ee3f12c9b8dc32e08f5357320e Mon Sep 17 00:00:00 2001 From: Kamidu Sachith Date: Tue, 13 Oct 2015 11:45:00 +0530 Subject: [PATCH 15/23] Enable java8 support --- .../backend-oauth-authenticator/pom.xml | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/components/identity-extensions/backend-oauth-authenticator/pom.xml b/components/identity-extensions/backend-oauth-authenticator/pom.xml index fdf8334f830..e148f5fdf3b 100644 --- a/components/identity-extensions/backend-oauth-authenticator/pom.xml +++ b/components/identity-extensions/backend-oauth-authenticator/pom.xml @@ -111,14 +111,13 @@ org.wso2.carbon.core.security, org.wso2.carbon.core.services.authentication, org.wso2.carbon.identity.oauth2.stub, - org.wso2.carbon.identity.oauth2.stub.dto + org.wso2.carbon.identity.oauth2.stub.dto, + org.wso2.carbon.base, + org.wso2.carbon.utils - - org.wso2.carbon.identity.authenticator.backend.oauth.*; - - + - \ No newline at end of file + From b0d6038b6969620e8723e1fe8451c8c740163096 Mon Sep 17 00:00:00 2001 From: harshanl Date: Tue, 13 Oct 2015 22:30:12 +0530 Subject: [PATCH 16/23] Refactored dynamic client code & add tenancy handling to authenticators --- .../dynamic/client/web/DynamicClientUtil.java | 11 +- .../web/impl/RegistrationServiceImpl.java | 40 ++-- .../registration/ApplicationConstants.java | 3 +- .../DynamicClientRegistrationException.java | 2 +- .../DynamicClientRegistrationService.java | 9 +- .../registration/OAuthApplicationInfo.java | 22 +- ...DynamicClientRegistrationServiceImpl.java} | 131 +++++------- .../DynamicClientRegistrationDataHolder.java | 4 +- ...micClientRegistrationServiceComponent.java | 9 +- .../profile/RegistrationProfile.java | 4 +- ...ynamicClientWebAppRegistrationManager.java | 78 ++++--- .../JaggeryOAuthConfigurationSettings.java | 2 +- .../app/registration/dto/OAuthAppDetails.java | 2 +- ...micClientWebAppRegistrationDataHolder.java | 14 +- ...entWebAppRegistrationServiceComponent.java | 201 +++++++++--------- ...ientWebAppDeploymentLifecycleListener.java | 3 +- .../DynamicClientWebAppRegistrationUtil.java | 88 +++----- .../PermissionBasedScopeValidator.java | 10 +- .../AuthenticationFrameworkUtil.java | 4 +- .../framework/AuthenticationInfo.java | 65 ++++++ ... => AuthenticatorFrameworkDataHolder.java} | 9 +- ...er.java => WebappAuthenticationValve.java} | 41 ++-- .../framework/WebappAuthenticatorFactory.java | 4 +- .../WebappAuthenticatorFrameworkValve.java | 71 ------- .../authenticator/BasicAuthAuthenticator.java | 5 +- .../CertificateAuthenticator.java | 48 ++--- .../authenticator/JWTAuthenticator.java | 52 +++-- .../authenticator/OAuthAuthenticator.java | 56 ++--- .../authenticator/WebappAuthenticator.java | 3 +- .../PermissionAuthorizationValve.java | 5 +- .../authorizer/PermissionAuthorizer.java | 6 +- ...uthenticatorFrameworkServiceComponent.java | 29 ++- 32 files changed, 489 insertions(+), 542 deletions(-) rename components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/{DynamicClientRegistrationImpl.java => DynamicClientRegistrationServiceImpl.java} (79%) create mode 100644 components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationInfo.java rename components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/{DataHolder.java => AuthenticatorFrameworkDataHolder.java} (91%) rename components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/{WebappAuthenticationHandler.java => WebappAuthenticationValve.java} (71%) delete mode 100644 components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFrameworkValve.java diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/DynamicClientUtil.java b/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/DynamicClientUtil.java index 5025a796bf3..d72736f3623 100644 --- a/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/DynamicClientUtil.java +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/DynamicClientUtil.java @@ -26,11 +26,8 @@ import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationServ */ public class DynamicClientUtil { - public static DynamicClientRegistrationService getDynamicClientRegistrationService() { - DynamicClientRegistrationService dynamicClientRegistrationService; - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - dynamicClientRegistrationService = - (DynamicClientRegistrationService) ctx.getOSGiService(DynamicClientRegistrationService.class, null); - return dynamicClientRegistrationService; - } + public static DynamicClientRegistrationService getDynamicClientRegistrationService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + return (DynamicClientRegistrationService) ctx.getOSGiService(DynamicClientRegistrationService.class, null); + } } diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/impl/RegistrationServiceImpl.java b/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/impl/RegistrationServiceImpl.java index ac5eab14b20..5d8e7bc5fb1 100644 --- a/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/impl/RegistrationServiceImpl.java +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/impl/RegistrationServiceImpl.java @@ -46,30 +46,30 @@ public class RegistrationServiceImpl implements RegistrationService { @POST @Override public Response register(RegistrationProfile profile) { + Response response; try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); PrivilegedCarbonContext.getThreadLocalCarbonContext(). setTenantId(MultitenantConstants.SUPER_TENANT_ID); - DynamicClientRegistrationService dynamicClientRegistrationService = DynamicClientUtil. - getDynamicClientRegistrationService(); - if(dynamicClientRegistrationService != null){ - OAuthApplicationInfo info = dynamicClientRegistrationService. - registerOAuthApplication(profile); + getDynamicClientRegistrationService(); + if (dynamicClientRegistrationService != null) { + OAuthApplicationInfo info = dynamicClientRegistrationService.registerOAuthApplication(profile); return Response.status(Response.Status.CREATED).entity(info.toString()).build(); } - return Response.status(Response.Status.INTERNAL_SERVER_ERROR). - entity("Dynamic Client Registration Service not available.").build(); + response = Response.status(Response.Status.INTERNAL_SERVER_ERROR). + entity("Dynamic Client Registration Service not available.").build(); } catch (DynamicClientRegistrationException e) { String msg = "Error occurred while registering client '" + profile.getClientName() + "'"; log.error(msg, e); - return Response.status(Response.Status.BAD_REQUEST).entity( + response = Response.status(Response.Status.BAD_REQUEST).entity( new FaultResponse(ErrorCode.INVALID_CLIENT_METADATA, msg)).build(); } finally { PrivilegedCarbonContext.endTenantFlow(); } + return response; } @DELETE @@ -77,26 +77,32 @@ public class RegistrationServiceImpl implements RegistrationService { public Response unregister(@QueryParam("applicationName") String applicationName, @QueryParam("userId") String userId, @QueryParam("consumerKey") String consumerKey) { + Response response; try { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID); DynamicClientRegistrationService dynamicClientRegistrationService = DynamicClientUtil. - getDynamicClientRegistrationService(); - if(dynamicClientRegistrationService != null){ - boolean status = dynamicClientRegistrationService.unregisterOAuthApplication(userId, - applicationName, - consumerKey); - if(status){ + getDynamicClientRegistrationService(); + if (dynamicClientRegistrationService != null) { + boolean status = dynamicClientRegistrationService.unregisterOAuthApplication(userId, applicationName, + consumerKey); + if (status) { return Response.status(Response.Status.ACCEPTED).build(); } return Response.status(Response.Status.BAD_REQUEST).build(); } - return Response.status(Response.Status.INTERNAL_SERVER_ERROR). + response = Response.status(Response.Status.INTERNAL_SERVER_ERROR). entity("Dynamic Client Registration Service not available.").build(); } catch (DynamicClientRegistrationException e) { String msg = "Error occurred while un-registering client '" + applicationName + "'"; log.error(msg, e); - return Response.serverError(). - entity(new FaultResponse(ErrorCode.INVALID_CLIENT_METADATA, msg)).build(); + response = Response.serverError().entity(new FaultResponse(ErrorCode.INVALID_CLIENT_METADATA, msg)).build(); + } finally { + PrivilegedCarbonContext.endTenantFlow(); } + return response; } } diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/ApplicationConstants.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/ApplicationConstants.java index c326ee6af81..d9f26334c33 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/ApplicationConstants.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/ApplicationConstants.java @@ -26,6 +26,7 @@ public final class ApplicationConstants { private ClientMetadata() { throw new AssertionError(); } + //todo refactor names public static final String OAUTH_CLIENT_ID = "client_id"; //this means consumer key public static final String OAUTH_CLIENT_SECRET = "client_secret"; public static final String OAUTH_REDIRECT_URIS = "redirect_uris"; @@ -36,7 +37,7 @@ public final class ApplicationConstants { public static final String APP_CALLBACK_URL = "callback_url"; public static final String APP_HOME_PAGE = "homepage"; public static final String OAUTH_CLIENT_CONTACT = "contact"; - public static final String APP_LOGOURI = "logouri"; + public static final String APP_LOGO_URI = "logo_uri"; public static final String OAUTH_CLIENT_SCOPE = "scope"; public static final String OAUTH_CLIENT_GRANT = "grant_types"; public static final String OAUTH_CLIENT_RESPONSETYPE = "response_types"; diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/DynamicClientRegistrationException.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/DynamicClientRegistrationException.java index f01d817d710..9798200f6fc 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/DynamicClientRegistrationException.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/DynamicClientRegistrationException.java @@ -19,7 +19,7 @@ package org.wso2.carbon.dynamic.client.registration; /** - * Custom exception to be thrown inside DynamicClientRegistration related functionalities. + * Custom exception to be thrown inside DynamicClientRegistration related functionality. */ public class DynamicClientRegistrationException extends Exception { diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/DynamicClientRegistrationService.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/DynamicClientRegistrationService.java index 7346ac1f69a..7abbb8eeee2 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/DynamicClientRegistrationService.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/DynamicClientRegistrationService.java @@ -21,7 +21,8 @@ package org.wso2.carbon.dynamic.client.registration; import org.wso2.carbon.dynamic.client.registration.profile.RegistrationProfile; /** - * This class represents the interface to be implemented by DynamicClientRegistrationService. + * This class represents the interface to be implemented by DynamicClientRegistrationService which + * is used to support the Dynamic-client-authentication protocol. */ public interface DynamicClientRegistrationService { @@ -34,7 +35,7 @@ public interface DynamicClientRegistrationService { * @throws DynamicClientRegistrationException * */ - public OAuthApplicationInfo registerOAuthApplication( + OAuthApplicationInfo registerOAuthApplication( RegistrationProfile profile) throws DynamicClientRegistrationException; /** @@ -47,7 +48,7 @@ public interface DynamicClientRegistrationService { * @throws DynamicClientRegistrationException * */ - public boolean unregisterOAuthApplication(String userName, String applicationName, + boolean unregisterOAuthApplication(String userName, String applicationName, String consumerKey) throws DynamicClientRegistrationException; /** @@ -58,6 +59,6 @@ public interface DynamicClientRegistrationService { * @throws DynamicClientRegistrationException * */ - public boolean isOAuthApplicationExists(String applicationName) throws DynamicClientRegistrationException; + boolean isOAuthApplicationAvailable(String applicationName) throws DynamicClientRegistrationException; } diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/OAuthApplicationInfo.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/OAuthApplicationInfo.java index 379194a3bfd..547844869ab 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/OAuthApplicationInfo.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/OAuthApplicationInfo.java @@ -31,7 +31,7 @@ public class OAuthApplicationInfo { private String clientName; private String callBackURL; private String clientSecret; - private Map parameters = new HashMap(); + private Map parameters = new HashMap(); public String getClientId() { return clientId; @@ -49,39 +49,39 @@ public class OAuthApplicationInfo { this.clientSecret = clientSecret; } - public void setClientName(String clientName){ + public void setClientName(String clientName) { this.clientName = clientName; } - public void setCallBackURL(String callBackURL){ + public void setCallBackURL(String callBackURL) { this.callBackURL = callBackURL; } - public void addParameter(String name,Object value){ - parameters.put(name,value); + public void addParameter(String name, Object value) { + parameters.put(name, value); } - public Object getParameter(String name){ + public Object getParameter(String name) { return parameters.get(name); } - public String getJsonString(){ + public String getJsonString() { return JSONObject.toJSONString(parameters); } - public String getClientName(){ + public String getClientName() { return clientName; } - public String getCallBackURL(){ + public String getCallBackURL() { return callBackURL; } - public void putAll(Map parameters){ + public void putAll(Map parameters) { this.parameters.putAll(parameters); } - public void removeParameter(String key){ + public void removeParameter(String key) { this.parameters.remove(key); } diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationImpl.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationServiceImpl.java similarity index 79% rename from components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationImpl.java rename to components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationServiceImpl.java index fcd1c7c1330..31aa091c267 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationImpl.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationServiceImpl.java @@ -38,12 +38,13 @@ import org.wso2.carbon.identity.sso.saml.admin.SAMLSSOConfigAdmin; import org.wso2.carbon.identity.sso.saml.dto.SAMLSSOServiceProviderDTO; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; + import java.util.Arrays; /** * Implementation of DynamicClientRegistrationService. */ -public class DynamicClientRegistrationImpl implements DynamicClientRegistrationService { +public class DynamicClientRegistrationServiceImpl implements DynamicClientRegistrationService { private static final String TOKEN_SCOPE = "tokenScope"; private static final String MDM = "mdm"; @@ -54,12 +55,14 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS private static final String ASSERTION_CONSUMER_URI = "https://localhost:9443/mdm/sso/acs"; private static final String AUDIENCE = "https://null:9443/oauth2/token"; private static final Log log = LogFactory.getLog(DynamicClientRegistrationService.class); + private static final String AUTH_TYPE_OAUTH_2 = "oauth2"; + private static final String OAUTH_CONSUMER_SECRET = "oauthConsumerSecret"; + private static final int STEP_ORDER = 1; @Override - public OAuthApplicationInfo registerOAuthApplication(RegistrationProfile profile) - throws DynamicClientRegistrationException { + public OAuthApplicationInfo registerOAuthApplication(RegistrationProfile profile) throws + DynamicClientRegistrationException { OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo(); - String applicationName = profile.getClientName(); if (log.isDebugEnabled()) { @@ -74,9 +77,10 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS OAuthApplicationInfo info; try { info = this.createOAuthApplication(profile); - } catch (Exception e) { - throw new DynamicClientRegistrationException( - "Can not create OAuth application : " + applicationName, e); + } catch (DynamicClientRegistrationException e) { + throw new DynamicClientRegistrationException("Can not create OAuth application : " + applicationName, e); + } catch (IdentityException e) { + throw new DynamicClientRegistrationException("Can not create OAuth application : " + applicationName, e); } if (info == null || info.getJsonString() == null) { @@ -92,18 +96,14 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS try { JSONObject jsonObject = new JSONObject(info.getJsonString()); if (jsonObject.has(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS)) { - oAuthApplicationInfo - .addParameter(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS, - jsonObject - .get(ApplicationConstants.ClientMetadata. - OAUTH_REDIRECT_URIS)); + oAuthApplicationInfo.addParameter(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS, + jsonObject + .get(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS)); } if (jsonObject.has(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT)) { - oAuthApplicationInfo.addParameter(ApplicationConstants.ClientMetadata. - OAUTH_CLIENT_GRANT, jsonObject - .get(ApplicationConstants.ClientMetadata. - OAUTH_CLIENT_GRANT)); + oAuthApplicationInfo.addParameter(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT, jsonObject + .get(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT)); } } catch (JSONException e) { throw new DynamicClientRegistrationException( @@ -113,8 +113,7 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS } private OAuthApplicationInfo createOAuthApplication( - RegistrationProfile profile) - throws DynamicClientRegistrationException, IdentityException { + RegistrationProfile profile) throws DynamicClientRegistrationException, IdentityException { //Subscriber's name should be passed as a parameter, since it's under the subscriber //the OAuth App is created. @@ -152,27 +151,22 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS serviceProvider.setOwner(user); serviceProvider.setDescription("Service Provider for application " + applicationName); - - ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder. - getInstance().getApplicationManagementService(); + ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder.getInstance(). + getApplicationManagementService(); if (appMgtService == null) { - throw new IllegalStateException( - "Error occurred while retrieving Application Management" + - "Service"); + throw new IllegalStateException("Error occurred while retrieving Application Management" + "Service"); } - ServiceProvider existingServiceProvider = appMgtService.getServiceProvider( - applicationName, tenantDomain); + ServiceProvider existingServiceProvider = appMgtService.getServiceProvider(applicationName, tenantDomain); if (existingServiceProvider == null) { appMgtService.createApplication(serviceProvider, tenantDomain, userName); } - ServiceProvider createdServiceProvider = appMgtService.getServiceProvider( - applicationName, tenantDomain); + ServiceProvider createdServiceProvider = appMgtService.getServiceProvider(applicationName, tenantDomain); if (createdServiceProvider == null) { - throw new DynamicClientRegistrationException( - "Couldn't create Service Provider Application " + applicationName); + throw new DynamicClientRegistrationException("Couldn't create Service Provider Application " + + applicationName); } //Set SaaS app option createdServiceProvider.setSaasApp(isSaaSApp); @@ -187,8 +181,8 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS log.debug("Creating OAuth App " + applicationName); } - if ((existingServiceProvider == null) || (existingServiceProvider. - getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs().length == 0)) { + if ((existingServiceProvider == null) || (existingServiceProvider.getInboundAuthenticationConfig(). + getInboundAuthenticationRequestConfigs().length == 0)) { oAuthAdminService.registerOAuthApplicationData(oAuthConsumerApp); } @@ -210,14 +204,13 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS InboundAuthenticationRequestConfig inboundAuthenticationRequestConfig = new InboundAuthenticationRequestConfig(); inboundAuthenticationRequestConfig.setInboundAuthKey(createdApp.getOauthConsumerKey()); - inboundAuthenticationRequestConfig.setInboundAuthType("oauth2"); - if (createdApp.getOauthConsumerSecret() != null && !createdApp. - getOauthConsumerSecret() - .isEmpty()) { + inboundAuthenticationRequestConfig.setInboundAuthType(AUTH_TYPE_OAUTH_2); + String oauthConsumerSecret = createdApp.getOauthConsumerSecret(); + if (oauthConsumerSecret != null && !oauthConsumerSecret.isEmpty()) { Property property = new Property(); - property.setName("oauthConsumerSecret"); - property.setValue(createdApp.getOauthConsumerSecret()); - Property[] properties = {property}; + property.setName(OAUTH_CONSUMER_SECRET); + property.setValue(oauthConsumerSecret); + Property[] properties = { property }; inboundAuthenticationRequestConfig.setProperties(properties); } @@ -225,7 +218,7 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS samlssoServiceProviderDTO.setIssuer(MDM); samlssoServiceProviderDTO.setAssertionConsumerUrl(ASSERTION_CONSUMER_URI); samlssoServiceProviderDTO.setDoSignResponse(true); - samlssoServiceProviderDTO.setRequestedAudiences(new String[]{AUDIENCE}); + samlssoServiceProviderDTO.setRequestedAudiences(new String[] { AUDIENCE }); SAMLSSOConfigAdmin configAdmin = new SAMLSSOConfigAdmin(getConfigSystemRegistry()); configAdmin.addRelyingPartyServiceProvider(samlssoServiceProviderDTO); @@ -240,15 +233,15 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS localAuth.setEnabled(true); AuthenticationStep authStep = new AuthenticationStep(); - authStep.setStepOrder(1); + authStep.setStepOrder(STEP_ORDER); authStep.setSubjectStep(true); authStep.setAttributeStep(true); - authStep.setLocalAuthenticatorConfigs(new LocalAuthenticatorConfig[]{localAuth}); + authStep.setLocalAuthenticatorConfigs(new LocalAuthenticatorConfig[] { localAuth }); LocalAndOutboundAuthenticationConfig localOutboundAuthConfig = new LocalAndOutboundAuthenticationConfig(); localOutboundAuthConfig.setAuthenticationType(LOCAL); - localOutboundAuthConfig.setAuthenticationSteps(new AuthenticationStep[]{authStep}); + localOutboundAuthConfig.setAuthenticationSteps(new AuthenticationStep[] { authStep }); inboundAuthenticationRequestConfigs[0] = inboundAuthenticationRequestConfig; inboundAuthenticationRequestConfigs[1] = samlAuthenticationRequest; @@ -263,15 +256,13 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo(); oAuthApplicationInfo.setClientId(createdApp.getOauthConsumerKey()); oAuthApplicationInfo.setCallBackURL(createdApp.getCallbackUrl()); - oAuthApplicationInfo.setClientSecret(createdApp.getOauthConsumerSecret()); + oAuthApplicationInfo.setClientSecret(oauthConsumerSecret); oAuthApplicationInfo.setClientName(createdApp.getApplicationName()); oAuthApplicationInfo.addParameter( - ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS, - createdApp.getCallbackUrl()); + ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS, createdApp.getCallbackUrl()); oAuthApplicationInfo.addParameter( - ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT, - createdApp.getGrantTypes()); + ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT, createdApp.getGrantTypes()); return oAuthApplicationInfo; } catch (IdentityApplicationManagementException e) { @@ -287,20 +278,19 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS } protected Registry getConfigSystemRegistry() { - return (Registry) PrivilegedCarbonContext.getThreadLocalCarbonContext(). - getRegistry(RegistryType.SYSTEM_CONFIGURATION); + return (Registry) PrivilegedCarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType. + SYSTEM_CONFIGURATION); } @Override - public boolean unregisterOAuthApplication(String userId, String applicationName, - String consumerKey) throws DynamicClientRegistrationException { + public boolean unregisterOAuthApplication(String userId, String applicationName, String consumerKey) throws + DynamicClientRegistrationException { DynamicClientRegistrationUtil.validateUsername(userId); DynamicClientRegistrationUtil.validateApplicationName(applicationName); DynamicClientRegistrationUtil.validateConsumerKey(consumerKey); boolean status = false; String tenantDomain = MultitenantUtils.getTenantDomain(userId); - String baseUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); String userName = MultitenantUtils.getTenantAwareUsername(userId); PrivilegedCarbonContext.startTenantFlow(); @@ -312,9 +302,9 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS try { oAuthAdminService = new OAuthAdminService(); oAuthConsumerApp = oAuthAdminService.getOAuthApplicationData(consumerKey); - } catch (IdentityOAuthAdminException e) { - throw new DynamicClientRegistrationException("Error occurred while retrieving application data", e); } catch (Exception e) { + //We had to catch Exception here because getOAuthApplicationData can throw exceptions of java.lang.Exception + // class. throw new DynamicClientRegistrationException("Error occurred while retrieving application data", e); } @@ -325,17 +315,15 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS try { oAuthAdminService.removeOAuthApplicationData(consumerKey); - - ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder. - getInstance().getApplicationManagementService(); + ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder.getInstance(). + getApplicationManagementService(); if (appMgtService == null) { throw new IllegalStateException( "Error occurred while retrieving Application Management" + - "Service"); + "Service"); } - ServiceProvider createdServiceProvider = appMgtService.getServiceProvider( - applicationName, tenantDomain); + ServiceProvider createdServiceProvider = appMgtService.getServiceProvider(applicationName, tenantDomain); if (createdServiceProvider == null) { throw new DynamicClientRegistrationException( "Couldn't retrieve Service Provider Application " + applicationName); @@ -346,38 +334,31 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS throw new DynamicClientRegistrationException( "Error occurred while removing ServiceProvider for application '" + applicationName + "'", e); } catch (IdentityOAuthAdminException e) { - throw new DynamicClientRegistrationException("Error occurred while removing application '" + - applicationName + "'", e); - } catch (Exception e) { throw new DynamicClientRegistrationException("Error occurred while removing application '" + applicationName + "'", e); } finally { PrivilegedCarbonContext.endTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(baseUser); } return status; } @Override - public boolean isOAuthApplicationExists(String applicationName) throws DynamicClientRegistrationException { - ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder. - getInstance().getApplicationManagementService(); + public boolean isOAuthApplicationAvailable(String applicationName) throws DynamicClientRegistrationException { + ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder.getInstance(). + getApplicationManagementService(); if (appMgtService == null) { throw new IllegalStateException( "Error occurred while retrieving Application Management" + - "Service"); + "Service"); } try { - if (appMgtService.getServiceProvider(applicationName, - CarbonContext.getThreadLocalCarbonContext() - .getTenantDomain()) != null) { - return true; - } + return appMgtService.getServiceProvider(applicationName, + CarbonContext.getThreadLocalCarbonContext().getTenantDomain()) != + null; } catch (IdentityApplicationManagementException e) { throw new DynamicClientRegistrationException( "Error occurred while retrieving information of OAuthApp " + applicationName, e); } - return false; } } diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationDataHolder.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationDataHolder.java index 63bda3e3379..9d105608e03 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationDataHolder.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationDataHolder.java @@ -45,7 +45,7 @@ public class DynamicClientRegistrationDataHolder { return applicationManagementService; } - public void setApplicationManagementService(ApplicationManagementService realmService) { - this.applicationManagementService = realmService; + public void setApplicationManagementService(ApplicationManagementService applicationManagementService) { + this.applicationManagementService = applicationManagementService; } } diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java index 68d7ef02a07..6717742ac39 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java @@ -20,9 +20,10 @@ package org.wso2.carbon.dynamic.client.registration.internal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.ComponentContext; import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService; -import org.wso2.carbon.dynamic.client.registration.impl.DynamicClientRegistrationImpl; +import org.wso2.carbon.dynamic.client.registration.impl.DynamicClientRegistrationServiceImpl; import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; /** @@ -44,9 +45,9 @@ public class DynamicClientRegistrationServiceComponent { log.debug("Starting DynamicClientRegistrationServiceComponent"); } DynamicClientRegistrationService dynamicClientRegistrationService = - new DynamicClientRegistrationImpl(); - componentContext.getBundleContext().registerService(DynamicClientRegistrationService.class.getName(), - dynamicClientRegistrationService, null); + new DynamicClientRegistrationServiceImpl(); + componentContext.getBundleContext().registerService( + DynamicClientRegistrationService.class.getName(), dynamicClientRegistrationService, null); } @SuppressWarnings("unused") diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/profile/RegistrationProfile.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/profile/RegistrationProfile.java index 8f8286ba681..f755e9ed23f 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/profile/RegistrationProfile.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/profile/RegistrationProfile.java @@ -19,11 +19,11 @@ package org.wso2.carbon.dynamic.client.registration.profile; /** * - * DTO class to be used when registering a OAuth application. + * DTO class to be used when registering an OAuth application. * * */ public class RegistrationProfile { - +//todo mark mandatory fields private String applicationType; private String[] redirectUris; private String clientName; diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/DynamicClientWebAppRegistrationManager.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/DynamicClientWebAppRegistrationManager.java index b159a3515c2..d7456f4f8eb 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/DynamicClientWebAppRegistrationManager.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/DynamicClientWebAppRegistrationManager.java @@ -41,11 +41,9 @@ import java.util.*; public class DynamicClientWebAppRegistrationManager { private static DynamicClientWebAppRegistrationManager dynamicClientWebAppRegistrationManager; - private static List registrationProfileList = new ArrayList<>(); private static Map webAppContexts = new HashMap<>(); - private static final Log log = - LogFactory.getLog(DynamicClientWebAppRegistrationManager.class); + private static final Log log = LogFactory.getLog(DynamicClientWebAppRegistrationManager.class); private DynamicClientWebAppRegistrationManager() { } @@ -64,17 +62,14 @@ public class DynamicClientWebAppRegistrationManager { public OAuthAppDetails registerOAuthApplication(RegistrationProfile registrationProfile) { if (log.isDebugEnabled()) { - log.debug("Registering OAuth application for web app : " + - registrationProfile.getClientName()); + log.debug("Registering OAuth application for web app : " + registrationProfile.getClientName()); } if (DynamicClientWebAppRegistrationUtil.validateRegistrationProfile(registrationProfile)) { DynamicClientRegistrationService dynamicClientRegistrationService = - DynamicClientWebAppRegistrationDataHolder.getInstance() - .getDynamicClientRegistrationService(); + DynamicClientWebAppRegistrationDataHolder.getInstance().getDynamicClientRegistrationService(); try { OAuthApplicationInfo oAuthApplicationInfo = - dynamicClientRegistrationService - .registerOAuthApplication(registrationProfile); + dynamicClientRegistrationService.registerOAuthApplication(registrationProfile); OAuthAppDetails oAuthAppDetails = new OAuthAppDetails(); oAuthAppDetails.setWebAppName(registrationProfile.getClientName()); oAuthAppDetails.setClientName(oAuthApplicationInfo.getClientName()); @@ -84,19 +79,17 @@ public class DynamicClientWebAppRegistrationManager { if (DynamicClientWebAppRegistrationUtil.putOAuthApplicationData(oAuthAppDetails)) { return oAuthAppDetails; } else { - dynamicClientRegistrationService - .unregisterOAuthApplication(registrationProfile.getOwner(), + dynamicClientRegistrationService.unregisterOAuthApplication(registrationProfile.getOwner(), oAuthApplicationInfo.getClientName(), oAuthApplicationInfo.getClientId()); - log.warn( - "Error occurred while persisting the OAuth application data in registry."); + log.warn("Error occurred while persisting the OAuth application data in registry."); } } catch (DynamicClientRegistrationException e) { log.error("Error occurred while registering the OAuth application : " + registrationProfile.getClientName(), e); } } - return new OAuthAppDetails(); + return null; } public OAuthAppDetails getOAuthApplicationData(String clientName) { @@ -106,12 +99,13 @@ public class DynamicClientWebAppRegistrationManager { log.error("Error occurred while fetching the OAuth application data for web app : " + clientName, e); } - return new OAuthAppDetails(); + return null; } public boolean isRegisteredOAuthApplication(String clientName) { OAuthAppDetails oAuthAppDetails = this.getOAuthApplicationData(clientName); - if (oAuthAppDetails.getClientKey() != null && oAuthAppDetails.getClientSecret() != null) { + if (oAuthAppDetails != null && (oAuthAppDetails.getClientKey() != null && oAuthAppDetails.getClientSecret() != + null)) { return true; } return false; @@ -119,66 +113,66 @@ public class DynamicClientWebAppRegistrationManager { public void saveServletContextToCache(StandardContext context) { DynamicClientWebAppRegistrationManager.webAppContexts.put(context.getBaseName(), - context.getServletContext()); + context.getServletContext()); } public void initiateDynamicClientRegistration() { String requiredDynamicClientRegistration, webAppName; ServletContext servletContext; RegistrationProfile registrationProfile; - OAuthAppDetails oAuthAppDetails = new OAuthAppDetails(); + OAuthAppDetails oAuthAppDetails = null; DynamicClientWebAppRegistrationManager dynamicClientWebAppRegistrationManager = DynamicClientWebAppRegistrationManager.getInstance(); - + //todo move enumeration to while loop Enumeration enumeration = new IteratorEnumeration(DynamicClientWebAppRegistrationManager. - webAppContexts.keySet().iterator()); + webAppContexts.keySet().iterator()); if (log.isDebugEnabled()) { log.debug("Initiating the DynamicClientRegistration service for web-apps"); } - while (enumeration.hasMoreElements()){ + while (enumeration.hasMoreElements()) { + oAuthAppDetails = new OAuthAppDetails(); webAppName = (String) enumeration.nextElement(); servletContext = DynamicClientWebAppRegistrationManager.webAppContexts.get(webAppName); requiredDynamicClientRegistration = servletContext.getInitParameter( DynamicClientWebAppRegistrationConstants.DYNAMIC_CLIENT_REQUIRED_FLAG); //Java web-app section - if ((requiredDynamicClientRegistration != null) && - (Boolean.parseBoolean(requiredDynamicClientRegistration))) { + if ((requiredDynamicClientRegistration != null) && (Boolean. + parseBoolean( + requiredDynamicClientRegistration))) { //Check whether this is an already registered application if (!dynamicClientWebAppRegistrationManager.isRegisteredOAuthApplication(webAppName)) { //Construct the RegistrationProfile registrationProfile = DynamicClientWebAppRegistrationUtil. - constructRegistrationProfile(servletContext, - webAppName); + constructRegistrationProfile(servletContext, webAppName); //Register the OAuth application - oAuthAppDetails = dynamicClientWebAppRegistrationManager.registerOAuthApplication( - registrationProfile); + oAuthAppDetails = + dynamicClientWebAppRegistrationManager.registerOAuthApplication(registrationProfile); } else { - oAuthAppDetails = - dynamicClientWebAppRegistrationManager.getOAuthApplicationData(webAppName); + oAuthAppDetails = dynamicClientWebAppRegistrationManager.getOAuthApplicationData(webAppName); } } else if (requiredDynamicClientRegistration == null) { //Jaggery apps - JaggeryOAuthConfigurationSettings jaggeryOAuthConfigurationSettings = DynamicClientWebAppRegistrationUtil - .getJaggeryAppOAuthSettings(servletContext); + JaggeryOAuthConfigurationSettings jaggeryOAuthConfigurationSettings = + DynamicClientWebAppRegistrationUtil.getJaggeryAppOAuthSettings(servletContext); if (jaggeryOAuthConfigurationSettings.isRequireDynamicClientRegistration()) { - if (!dynamicClientWebAppRegistrationManager - .isRegisteredOAuthApplication(webAppName)) { - registrationProfile = DynamicClientWebAppRegistrationUtil - .constructRegistrationProfile(jaggeryOAuthConfigurationSettings, webAppName); - oAuthAppDetails = dynamicClientWebAppRegistrationManager - .registerOAuthApplication(registrationProfile); + if (!dynamicClientWebAppRegistrationManager.isRegisteredOAuthApplication(webAppName)) { + registrationProfile = DynamicClientWebAppRegistrationUtil. + constructRegistrationProfile(jaggeryOAuthConfigurationSettings, + webAppName); + oAuthAppDetails = dynamicClientWebAppRegistrationManager. + registerOAuthApplication(registrationProfile); } else { - oAuthAppDetails = dynamicClientWebAppRegistrationManager - .getOAuthApplicationData(webAppName); + oAuthAppDetails = dynamicClientWebAppRegistrationManager.getOAuthApplicationData(webAppName); } } } //Add client credentials to the web-context - if (oAuthAppDetails.getClientKey() != null) { + if ((oAuthAppDetails != null && oAuthAppDetails.getClientKey() != null) && !oAuthAppDetails.getClientKey().isEmpty()) { DynamicClientWebAppRegistrationUtil.addClientCredentialsToWebContext(oAuthAppDetails, - servletContext); - log.info("Added OAuth application credentials to webapp context of webapp : " + webAppName); + servletContext); + log.info("Added OAuth application credentials to webapp context of webapp : " + + webAppName); } } } diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/JaggeryOAuthConfigurationSettings.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/JaggeryOAuthConfigurationSettings.java index 8b9849175c3..32f8b9bcc96 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/JaggeryOAuthConfigurationSettings.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/JaggeryOAuthConfigurationSettings.java @@ -22,7 +22,7 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** - * Represents OAuthConfiguration data. + * Represents OAuthConfiguration data required to create OAuth service provider for Jaggery apps. */ @XmlRootElement(name = "OAuthSettings") public class JaggeryOAuthConfigurationSettings { diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/OAuthAppDetails.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/OAuthAppDetails.java index 9fc1b359e81..9ae885c67b1 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/OAuthAppDetails.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/OAuthAppDetails.java @@ -22,7 +22,7 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** - * Represents an OAuth application with basic data. + * Represents an OAuth application with basic necessary data. */ @XmlRootElement(name = "OAuthAppDetails") public class OAuthAppDetails { diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/internal/DynamicClientWebAppRegistrationDataHolder.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/internal/DynamicClientWebAppRegistrationDataHolder.java index af96d2a37da..b40e9a55046 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/internal/DynamicClientWebAppRegistrationDataHolder.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/internal/DynamicClientWebAppRegistrationDataHolder.java @@ -44,10 +44,11 @@ public class DynamicClientWebAppRegistrationDataHolder { } public ConfigurationContextService getConfigurationContextService() { - if(configurationContextService != null){ + if (configurationContextService != null) { return configurationContextService; } else { - throw new IllegalStateException("ConfigurationContext service has not initialized properly"); + throw new IllegalStateException( + "ConfigurationContext service has not initialized properly"); } } @@ -57,10 +58,11 @@ public class DynamicClientWebAppRegistrationDataHolder { } public DynamicClientRegistrationService getDynamicClientRegistrationService() { - if(dynamicClientRegistrationService != null){ + if (dynamicClientRegistrationService != null) { return dynamicClientRegistrationService; } else { - throw new IllegalStateException("DynamicClientRegistration service has not initialized properly"); + throw new IllegalStateException( + "DynamicClientRegistration service has not initialized properly"); } } @@ -70,7 +72,7 @@ public class DynamicClientWebAppRegistrationDataHolder { } public RealmService getRealmService() { - if(realmService != null){ + if (realmService != null) { return realmService; } else { throw new IllegalStateException("RealmService has not initialized properly"); @@ -82,7 +84,7 @@ public class DynamicClientWebAppRegistrationDataHolder { } public RegistryService getRegistryService() { - if(registryService != null){ + if (registryService != null) { return registryService; } else { throw new IllegalStateException("Registry Service has not initialized properly"); diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/internal/DynamicClientWebAppRegistrationServiceComponent.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/internal/DynamicClientWebAppRegistrationServiceComponent.java index 8ecfc33b2de..3707e9ef5c1 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/internal/DynamicClientWebAppRegistrationServiceComponent.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/internal/DynamicClientWebAppRegistrationServiceComponent.java @@ -58,114 +58,119 @@ import org.wso2.carbon.utils.ConfigurationContextService; */ public class DynamicClientWebAppRegistrationServiceComponent { - private ServiceTracker serviceTracker; - private static Log log = LogFactory.getLog(DynamicClientWebAppRegistrationServiceComponent.class); + private static Log log = + LogFactory.getLog(DynamicClientWebAppRegistrationServiceComponent.class); - @SuppressWarnings("unused") - protected void activate(ComponentContext componentContext) { + @SuppressWarnings("unused") + protected void activate(ComponentContext componentContext) { componentContext.getBundleContext().registerService(ServerStartupObserver.class.getName(), - new WebAppRegistrationServerStartupObserver(), null) ; - } + new WebAppRegistrationServerStartupObserver(), null); + } - @SuppressWarnings("unused") - protected void deactivate(ComponentContext componentContext) { + @SuppressWarnings("unused") + protected void deactivate(ComponentContext componentContext) { - } + } - /** - * Sets Realm Service. - * - * @param realmService An instance of RealmService - */ - protected void setRealmService(RealmService realmService) { - if (log.isDebugEnabled()) { - log.debug("Setting Realm Service"); - } - DynamicClientWebAppRegistrationDataHolder.getInstance().setRealmService(realmService); - } + /** + * Sets Realm Service. + * + * @param realmService An instance of RealmService + */ + protected void setRealmService(RealmService realmService) { + if (log.isDebugEnabled()) { + log.debug("Setting Realm Service"); + } + DynamicClientWebAppRegistrationDataHolder.getInstance().setRealmService(realmService); + } - /** - * Unsets Realm Service. - * - * @param realmService An instance of RealmService - */ - protected void unsetRealmService(RealmService realmService) { - if (log.isDebugEnabled()) { - log.debug("Unsetting Realm Service"); - } - DynamicClientWebAppRegistrationDataHolder.getInstance().setRealmService(null); - } + /** + * Unsets Realm Service. + * + * @param realmService An instance of RealmService + */ + protected void unsetRealmService(RealmService realmService) { + if (log.isDebugEnabled()) { + log.debug("Unsetting Realm Service"); + } + DynamicClientWebAppRegistrationDataHolder.getInstance().setRealmService(null); + } - /** - * Sets Registry Service. - * - * @param registryService An instance of RegistryService - */ - protected void setRegistryService(RegistryService registryService) { - if (log.isDebugEnabled()) { - log.debug("Setting Registry Service"); - } - DynamicClientWebAppRegistrationDataHolder.getInstance().setRegistryService(registryService); - } + /** + * Sets Registry Service. + * + * @param registryService An instance of RegistryService + */ + protected void setRegistryService(RegistryService registryService) { + if (log.isDebugEnabled()) { + log.debug("Setting Registry Service"); + } + DynamicClientWebAppRegistrationDataHolder.getInstance().setRegistryService(registryService); + } - /** - * Unsets Registry Service. - * - * @param registryService An instance of RegistryService - */ - protected void unsetRegistryService(RegistryService registryService) { - if (log.isDebugEnabled()) { - log.debug("Un setting Registry Service"); - } - DynamicClientWebAppRegistrationDataHolder.getInstance().setRegistryService(null); - } + /** + * Unsets Registry Service. + * + * @param registryService An instance of RegistryService + */ + protected void unsetRegistryService(RegistryService registryService) { + if (log.isDebugEnabled()) { + log.debug("Un setting Registry Service"); + } + DynamicClientWebAppRegistrationDataHolder.getInstance().setRegistryService(null); + } - /** - * Sets Dynamic Client Registration Service. - * - * @param dynamicClientRegistrationService An instance of DynamicClientRegistrationService - */ - protected void setDynamicClientService(DynamicClientRegistrationService dynamicClientRegistrationService) { - if (log.isDebugEnabled()) { - log.debug("Setting Dynamic Client Registration Service"); - } - DynamicClientWebAppRegistrationDataHolder.getInstance().setDynamicClientRegistrationService( - dynamicClientRegistrationService); - } + /** + * Sets Dynamic Client Registration Service. + * + * @param dynamicClientRegistrationService An instance of DynamicClientRegistrationService + */ + protected void setDynamicClientService( + DynamicClientRegistrationService dynamicClientRegistrationService) { + if (log.isDebugEnabled()) { + log.debug("Setting Dynamic Client Registration Service"); + } + DynamicClientWebAppRegistrationDataHolder.getInstance().setDynamicClientRegistrationService( + dynamicClientRegistrationService); + } - /** - * Unsets Dynamic Client Registration Service. - * - * @param dynamicClientRegistrationService An instance of DynamicClientRegistrationService - */ - protected void unsetDynamicClientService(DynamicClientRegistrationService dynamicClientRegistrationService) { - if (log.isDebugEnabled()) { - log.debug("Un setting Dynamic Client Registration Service"); - } - DynamicClientWebAppRegistrationDataHolder.getInstance().setDynamicClientRegistrationService(null); - } + /** + * Unsets Dynamic Client Registration Service. + * + * @param dynamicClientRegistrationService An instance of DynamicClientRegistrationService + */ + protected void unsetDynamicClientService( + DynamicClientRegistrationService dynamicClientRegistrationService) { + if (log.isDebugEnabled()) { + log.debug("Un setting Dynamic Client Registration Service"); + } + DynamicClientWebAppRegistrationDataHolder.getInstance().setDynamicClientRegistrationService(null); + } - /** - * Sets ConfigurationContext Service. - * - * @param configurationContextService An instance of ConfigurationContextService - */ - protected void setConfigurationContextService(ConfigurationContextService configurationContextService) { - if (log.isDebugEnabled()) { - log.debug("Setting ConfigurationContextService"); - } - DynamicClientWebAppRegistrationDataHolder.getInstance().setConfigurationContextService(configurationContextService); - } + /** + * Sets ConfigurationContext Service. + * + * @param configurationContextService An instance of ConfigurationContextService + */ + protected void setConfigurationContextService( + ConfigurationContextService configurationContextService) { + if (log.isDebugEnabled()) { + log.debug("Setting ConfigurationContextService"); + } + DynamicClientWebAppRegistrationDataHolder.getInstance().setConfigurationContextService( + configurationContextService); + } - /** - * Unsets ConfigurationContext Service. - * - * @param configurationContextService An instance of ConfigurationContextService - */ - protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) { - if (log.isDebugEnabled()) { - log.debug("Un-setting ConfigurationContextService"); - } - DynamicClientWebAppRegistrationDataHolder.getInstance().setConfigurationContextService(null); - } + /** + * Unsets ConfigurationContext Service. + * + * @param configurationContextService An instance of ConfigurationContextService + */ + protected void unsetConfigurationContextService( + ConfigurationContextService configurationContextService) { + if (log.isDebugEnabled()) { + log.debug("Un-setting ConfigurationContextService"); + } + DynamicClientWebAppRegistrationDataHolder.getInstance().setConfigurationContextService(null); + } } \ No newline at end of file diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/listner/DynamicClientWebAppDeploymentLifecycleListener.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/listner/DynamicClientWebAppDeploymentLifecycleListener.java index aeff85c2a61..29d1f1ae0b1 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/listner/DynamicClientWebAppDeploymentLifecycleListener.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/listner/DynamicClientWebAppDeploymentLifecycleListener.java @@ -40,8 +40,7 @@ public class DynamicClientWebAppDeploymentLifecycleListener implements Lifecycle public void lifecycleEvent(LifecycleEvent lifecycleEvent) { if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) { StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); - DynamicClientWebAppRegistrationManager.getInstance().saveServletContextToCache( - context); + DynamicClientWebAppRegistrationManager.getInstance().saveServletContextToCache(context); } } } diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java index 765b0191e3f..5c826b338bc 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java @@ -62,9 +62,8 @@ public class DynamicClientWebAppRegistrationUtil { public static Registry getGovernanceRegistry() throws DynamicClientRegistrationException { try { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - return DynamicClientWebAppRegistrationDataHolder.getInstance().getRegistryService() - .getGovernanceSystemRegistry( - tenantId); + return DynamicClientWebAppRegistrationDataHolder.getInstance().getRegistryService(). + getGovernanceSystemRegistry(tenantId); } catch (RegistryException e) { throw new DynamicClientRegistrationException( "Error in retrieving governance registry instance: " + @@ -75,8 +74,7 @@ public class DynamicClientWebAppRegistrationUtil { public static OAuthAppDetails getOAuthApplicationData(String appName) throws DynamicClientRegistrationException { Resource resource; - String resourcePath = - DynamicClientWebAppRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH + "/" + appName; + String resourcePath = DynamicClientWebAppRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH + "/" + appName; try { if (log.isDebugEnabled()) { log.debug("Retrieving OAuth application " + appName + " data from Registry"); @@ -86,9 +84,8 @@ public class DynamicClientWebAppRegistrationUtil { JAXBContext context = JAXBContext.newInstance(OAuthAppDetails.class); Unmarshaller unmarshaller = context.createUnmarshaller(); return (OAuthAppDetails) unmarshaller.unmarshal( - new StringReader(new String((byte[]) resource.getContent(), Charset - .forName( - DynamicClientWebAppRegistrationConstants.CharSets.CHARSET_UTF8)))); + new StringReader(new String((byte[]) resource.getContent(), Charset.forName( + DynamicClientWebAppRegistrationConstants.CharSets.CHARSET_UTF8)))); } return new OAuthAppDetails(); } catch (JAXBException e) { @@ -96,13 +93,12 @@ public class DynamicClientWebAppRegistrationUtil { "Error occurred while parsing the OAuth application data : " + appName, e); } catch (RegistryException e) { throw new DynamicClientRegistrationException( - "Error occurred while retrieving the Registry resource of OAuth application : " + - appName, e); + "Error occurred while retrieving the Registry resource of OAuth application : " + appName, e); } } - public static boolean putOAuthApplicationData(OAuthAppDetails oAuthAppDetails) - throws DynamicClientRegistrationException { + public static boolean putOAuthApplicationData(OAuthAppDetails oAuthAppDetails) throws + DynamicClientRegistrationException { boolean status; try { if (log.isDebugEnabled()) { @@ -113,15 +109,12 @@ public class DynamicClientWebAppRegistrationUtil { Marshaller marshaller = context.createMarshaller(); marshaller.marshal(oAuthAppDetails, writer); - Resource resource = - DynamicClientWebAppRegistrationUtil.getGovernanceRegistry().newResource(); + Resource resource = DynamicClientWebAppRegistrationUtil.getGovernanceRegistry().newResource(); resource.setContent(writer.toString()); resource.setMediaType(DynamicClientWebAppRegistrationConstants.ContentTypes.MEDIA_TYPE_XML); - String resourcePath = - DynamicClientWebAppRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH + "/" + + String resourcePath = DynamicClientWebAppRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH + "/" + oAuthAppDetails.getWebAppName(); - status = - DynamicClientWebAppRegistrationUtil.putRegistryResource(resourcePath, resource); + status = DynamicClientWebAppRegistrationUtil.putRegistryResource(resourcePath, resource); } catch (RegistryException e) { throw new DynamicClientRegistrationException( "Error occurred while persisting OAuth application data : " + @@ -134,53 +127,42 @@ public class DynamicClientWebAppRegistrationUtil { return status; } - public static boolean putRegistryResource(String path, - Resource resource) - throws DynamicClientRegistrationException { - boolean status; + public static boolean putRegistryResource(String path, Resource resource) throws DynamicClientRegistrationException { try { - Registry governanceRegistry = DynamicClientWebAppRegistrationUtil - .getGovernanceRegistry(); + Registry governanceRegistry = DynamicClientWebAppRegistrationUtil.getGovernanceRegistry(); governanceRegistry.beginTransaction(); governanceRegistry.put(path, resource); governanceRegistry.commitTransaction(); - status = true; + return true; } catch (RegistryException e) { - throw new DynamicClientRegistrationException( - "Error occurred while persisting registry resource : " + - e.getMessage(), e); + throw new DynamicClientRegistrationException("Error occurred while persisting registry resource : " + + e.getMessage(), e); } - return status; } - public static Resource getRegistryResource(String path) - throws DynamicClientRegistrationException { + public static Resource getRegistryResource(String path) throws DynamicClientRegistrationException { try { - Registry governanceRegistry = DynamicClientWebAppRegistrationUtil - .getGovernanceRegistry(); + Registry governanceRegistry = DynamicClientWebAppRegistrationUtil.getGovernanceRegistry(); if (governanceRegistry.resourceExists(path)) { return governanceRegistry.get(path); } return null; } catch (RegistryException e) { - throw new DynamicClientRegistrationException( - "Error in retrieving registry resource : " + - e.getMessage(), e); + throw new DynamicClientRegistrationException("Error in retrieving registry resource : " + + e.getMessage(), e); } } public static String getUserName() { String username = ""; - RealmService realmService = - DynamicClientWebAppRegistrationDataHolder.getInstance().getRealmService(); + RealmService realmService = DynamicClientWebAppRegistrationDataHolder.getInstance().getRealmService(); if (realmService != null) { username = realmService.getBootstrapRealmConfiguration().getAdminUserName(); } return username; } - public static RegistrationProfile constructRegistrationProfile(ServletContext servletContext, - String webAppName) { + public static RegistrationProfile constructRegistrationProfile(ServletContext servletContext, String webAppName) { RegistrationProfile registrationProfile; registrationProfile = new RegistrationProfile(); registrationProfile.setGrantType(servletContext.getInitParameter( @@ -193,18 +175,16 @@ public class DynamicClientWebAppRegistrationUtil { if ((callbackURL != null) && !callbackURL.isEmpty()) { registrationProfile.setCallbackUrl(callbackURL); } else { - registrationProfile.setCallbackUrl(DynamicClientWebAppRegistrationUtil.getCallbackUrl( - webAppName)); + registrationProfile.setCallbackUrl(DynamicClientWebAppRegistrationUtil.getCallbackUrl(webAppName)); } registrationProfile.setClientName(webAppName); registrationProfile.setSaasApp(Boolean.parseBoolean(servletContext.getInitParameter( DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_SAAS_APP))); - return registrationProfile; } - public static RegistrationProfile constructRegistrationProfile( - JaggeryOAuthConfigurationSettings jaggeryOAuthConfigurationSettings, String webAppName) { + public static RegistrationProfile constructRegistrationProfile(JaggeryOAuthConfigurationSettings + jaggeryOAuthConfigurationSettings, String webAppName) { RegistrationProfile registrationProfile = new RegistrationProfile(); if (jaggeryOAuthConfigurationSettings != null) { registrationProfile.setGrantType(jaggeryOAuthConfigurationSettings.getGrantType()); @@ -215,18 +195,17 @@ public class DynamicClientWebAppRegistrationUtil { if (jaggeryOAuthConfigurationSettings.getCallbackURL() != null) { registrationProfile.setCallbackUrl(jaggeryOAuthConfigurationSettings.getCallbackURL()); } else { - registrationProfile.setCallbackUrl( - DynamicClientWebAppRegistrationUtil.getCallbackUrl(webAppName)); + registrationProfile.setCallbackUrl(DynamicClientWebAppRegistrationUtil.getCallbackUrl(webAppName)); } } else { - log.warn( - "Please configure OAuth settings properly for jaggery app : " + webAppName); + log.warn("Please configure OAuth settings properly for jaggery app : " + webAppName); } return registrationProfile; } public static boolean validateRegistrationProfile(RegistrationProfile registrationProfile) { boolean status = true; + //todo fix this if (registrationProfile.getGrantType() == null) { status = false; log.warn("Required parameter 'grantType' is missing for initiating Dynamic-Client " + @@ -241,14 +220,11 @@ public class DynamicClientWebAppRegistrationUtil { } public static JaggeryOAuthConfigurationSettings getJaggeryAppOAuthSettings(ServletContext servletContext) { - JaggeryOAuthConfigurationSettings - jaggeryOAuthConfigurationSettings = new JaggeryOAuthConfigurationSettings(); + JaggeryOAuthConfigurationSettings jaggeryOAuthConfigurationSettings = new JaggeryOAuthConfigurationSettings(); try { - InputStream inputStream = - servletContext.getResourceAsStream(JAGGERY_APP_OAUTH_CONFIG_PATH); + InputStream inputStream = servletContext.getResourceAsStream(JAGGERY_APP_OAUTH_CONFIG_PATH); if (inputStream != null) { - JsonReader reader = - new JsonReader(new InputStreamReader(inputStream, CHARSET_UTF_8)); + JsonReader reader = new JsonReader(new InputStreamReader(inputStream, CHARSET_UTF_8)); reader.beginObject(); while (reader.hasNext()) { String key = reader.nextName(); @@ -307,7 +283,7 @@ public class DynamicClientWebAppRegistrationUtil { public static void addClientCredentialsToWebContext(OAuthAppDetails oAuthAppDetails, ServletContext servletContext) { - if(oAuthAppDetails != null){ + if (oAuthAppDetails != null) { //Check for client credentials if ((oAuthAppDetails.getClientKey() != null && !oAuthAppDetails.getClientKey().isEmpty()) && (oAuthAppDetails.getClientSecret() != null && !oAuthAppDetails.getClientSecret().isEmpty())) { diff --git a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java index 39d62f00637..ba561436688 100644 --- a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java +++ b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java @@ -46,6 +46,7 @@ public class PermissionBasedScopeValidator extends OAuth2ScopeValidator { private PermissionMethod() { throw new AssertionError(); } + public static final String READ = "read"; public static final String WRITE = "write"; public static final String DELETE = "delete"; @@ -70,12 +71,13 @@ public class PermissionBasedScopeValidator extends OAuth2ScopeValidator { getPermissionManagerService(); try { Permission permission = permissionManagerService.getPermission(properties); - if((permission != null) && (accessTokenDO.getAuthzUser() != null)) { + if ((permission != null) && (accessTokenDO.getAuthzUser() != null)) { String username = accessTokenDO.getAuthzUser().getUserName(); UserRealm userRealm = CarbonContext.getThreadLocalCarbonContext().getUserRealm(); - if(userRealm != null && userRealm.getAuthorizationManager() != null){ - status = userRealm.getAuthorizationManager().isUserAuthorized(username, permission.getPath(), - PermissionMethod.READ); + if (userRealm != null && userRealm.getAuthorizationManager() != null) { + status = userRealm.getAuthorizationManager() + .isUserAuthorized(username, permission.getPath(), + PermissionMethod.READ); } } } catch (PermissionManagementException e) { diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationFrameworkUtil.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationFrameworkUtil.java index e66f9a1cd53..6ca33feb7ac 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationFrameworkUtil.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationFrameworkUtil.java @@ -62,8 +62,8 @@ public class AuthenticationFrameworkUtil { String username = apiKeyValidationDTO.getEndUserName(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username); try { - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId( - IdentityUtil.getTenantIdOFUser(username)); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(IdentityUtil. + getTenantIdOFUser(username)); } catch (IdentityException e) { throw new AuthenticationException("Error occurred while retrieving the tenant ID of user '" + username + "'", e); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationInfo.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationInfo.java new file mode 100644 index 00000000000..a65c99fa39c --- /dev/null +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationInfo.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.webapp.authenticator.framework; + +import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator; + +/** + * DTO class to hold the information of authenticated user AND STATUS. + */ +public class AuthenticationInfo { + + private WebappAuthenticator.Status status = WebappAuthenticator.Status.FAILURE; + private String username; + private String tenantDomain; + private int tenantId = -1; + + public WebappAuthenticator.Status getStatus() { + return status; + } + + public void setStatus( + WebappAuthenticator.Status status) { + this.status = status; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getTenantDomain() { + return tenantDomain; + } + + public void setTenantDomain(String tenantDomain) { + this.tenantDomain = tenantDomain; + } + + public int getTenantId() { + return tenantId; + } + + public void setTenantId(int tenantId) { + this.tenantId = tenantId; + } +} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/DataHolder.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticatorFrameworkDataHolder.java similarity index 91% rename from components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/DataHolder.java rename to components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticatorFrameworkDataHolder.java index 6bc406b27c2..547cda44a50 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/DataHolder.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticatorFrameworkDataHolder.java @@ -23,7 +23,7 @@ import org.wso2.carbon.device.mgt.core.scep.SCEPManager; import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; import org.wso2.carbon.user.core.service.RealmService; -public class DataHolder { +public class AuthenticatorFrameworkDataHolder { private WebappAuthenticatorRepository repository; private RealmService realmService; @@ -31,11 +31,12 @@ public class DataHolder { private SCEPManager scepManager; private OAuth2TokenValidationService oAuth2TokenValidationService; - private static DataHolder thisInstance = new DataHolder(); + private static AuthenticatorFrameworkDataHolder + thisInstance = new AuthenticatorFrameworkDataHolder(); - private DataHolder() {} + private AuthenticatorFrameworkDataHolder() {} - public static DataHolder getInstance() { + public static AuthenticatorFrameworkDataHolder getInstance() { return thisInstance; } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationHandler.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java similarity index 71% rename from components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationHandler.java rename to components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java index 7eb98c0d55a..c416444682c 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationHandler.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java @@ -22,6 +22,7 @@ import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve; import org.wso2.carbon.tomcat.ext.valves.CompositeValve; import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator; @@ -31,9 +32,9 @@ import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; -public class WebappAuthenticationHandler extends CarbonTomcatValve { +public class WebappAuthenticationValve extends CarbonTomcatValve { - private static final Log log = LogFactory.getLog(WebappAuthenticationHandler.class); + private static final Log log = LogFactory.getLog(WebappAuthenticationValve.class); private static final String BYPASS_URIS = "bypass-uris"; @Override @@ -44,16 +45,13 @@ public class WebappAuthenticationHandler extends CarbonTomcatValve { return; } - String byPassURIs = request.getContext().findParameter(WebappAuthenticationHandler.BYPASS_URIS); - - if(byPassURIs != null && !byPassURIs.isEmpty()) { + String byPassURIs = request.getContext().findParameter(WebappAuthenticationValve.BYPASS_URIS); + if (byPassURIs != null && !byPassURIs.isEmpty()) { List requestURI = Arrays.asList(byPassURIs.split(",")); - - if(requestURI != null && requestURI.size() > 0) { + if (requestURI != null && requestURI.size() > 0) { for (String pathURI : requestURI) { pathURI = pathURI.replace("\n", "").replace("\r", "").trim(); - if (request.getRequestURI().equals(pathURI)) { this.getNext().invoke(request, response, compositeValve); return; @@ -68,8 +66,21 @@ public class WebappAuthenticationHandler extends CarbonTomcatValve { AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg); return; } - WebappAuthenticator.Status status = authenticator.authenticate(request, response); - this.processResponse(request, response, compositeValve, status); + AuthenticationInfo authenticationInfo = authenticator.authenticate(request, response); + if (authenticationInfo.getTenantId() != -1) { + try { + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext privilegedCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + privilegedCarbonContext.setTenantId(authenticationInfo.getTenantId()); + privilegedCarbonContext.setTenantDomain(authenticationInfo.getTenantDomain()); + privilegedCarbonContext.setUsername(authenticationInfo.getUsername()); + this.processRequest(request, response, compositeValve, authenticationInfo.getStatus()); + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + } else { + this.processRequest(request, response, compositeValve, authenticationInfo.getStatus()); + } } private boolean isAdminService(Request request) { @@ -93,7 +104,7 @@ public class WebappAuthenticationHandler extends CarbonTomcatValve { } StringTokenizer tokenizer = new StringTokenizer(request.getRequestURI(), "/"); if (!tokenizer.hasMoreTokens()) { - return false; + return false; } ctx = tokenizer.nextToken(); } @@ -101,8 +112,8 @@ public class WebappAuthenticationHandler extends CarbonTomcatValve { return (ctx.equalsIgnoreCase("carbon") || ctx.equalsIgnoreCase("services")); } - private void processResponse(Request request, Response response, CompositeValve compositeValve, - WebappAuthenticator.Status status) { + private void processRequest(Request request, Response response, CompositeValve compositeValve, + WebappAuthenticator.Status status) { switch (status) { case SUCCESS: case CONTINUE: @@ -111,7 +122,9 @@ public class WebappAuthenticationHandler extends CarbonTomcatValve { case FAILURE: String msg = "Failed to authorize incoming request"; log.error(msg); - AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg); + AuthenticationFrameworkUtil + .handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, + msg); break; } } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java index c0e0e68a495..9613b18c00e 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFactory.java @@ -26,12 +26,12 @@ import java.util.Map; public class WebappAuthenticatorFactory { public static WebappAuthenticator getAuthenticator(String authScheme) { - return DataHolder.getInstance().getWebappAuthenticatorRepository().getAuthenticator(authScheme); + return AuthenticatorFrameworkDataHolder.getInstance().getWebappAuthenticatorRepository().getAuthenticator(authScheme); } public static WebappAuthenticator getAuthenticator(Request request) { Map authenticators = - DataHolder.getInstance().getWebappAuthenticatorRepository().getAuthenticators(); + AuthenticatorFrameworkDataHolder.getInstance().getWebappAuthenticatorRepository().getAuthenticators(); for (WebappAuthenticator authenticator : authenticators.values()) { if (authenticator.canHandle(request)) { return authenticator; diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFrameworkValve.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFrameworkValve.java deleted file mode 100644 index 02b94941cd7..00000000000 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticatorFrameworkValve.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.webapp.authenticator.framework; - -import org.apache.catalina.connector.Request; -import org.apache.catalina.connector.Response; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve; -import org.wso2.carbon.tomcat.ext.valves.CompositeValve; -import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator; - -import javax.servlet.http.HttpServletResponse; - -public class WebappAuthenticatorFrameworkValve extends CarbonTomcatValve { - - private static final String AUTHENTICATION_SCHEME = "authentication-scheme"; - private static final Log log = LogFactory.getLog(WebappAuthenticatorFrameworkValve.class); - - @Override - public void invoke(Request request, Response response, CompositeValve compositeValve) { - - String authScheme = request.getContext().findParameter(WebappAuthenticatorFrameworkValve.AUTHENTICATION_SCHEME); - - if (authScheme == null || authScheme.isEmpty()) { - this.getNext().invoke(request, response, compositeValve); - return; - } - - WebappAuthenticator authenticator = WebappAuthenticatorFactory.getAuthenticator(authScheme); - if (authenticator == null) { - String msg = "Failed to load an appropriate authenticator to authenticate the request"; - AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg); - return; - } - WebappAuthenticator.Status status = authenticator.authenticate(request, response); - this.processResponse(request, response, compositeValve, status); - } - - private void processResponse(Request request, Response response, CompositeValve compositeValve, - WebappAuthenticator.Status status) { - switch (status) { - case SUCCESS: - case CONTINUE: - this.getNext().invoke(request, response, compositeValve); - break; - case FAILURE: - String msg = "Failed to authorize incoming request"; - log.error(msg); - AuthenticationFrameworkUtil.handleResponse(request, response, HttpServletResponse.SC_UNAUTHORIZED, msg); - break; - } - } - -} diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java index 74396ab9c52..902c796b557 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java @@ -25,6 +25,7 @@ import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.CharChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.wso2.carbon.webapp.authenticator.framework.Constants; +import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; public class BasicAuthAuthenticator implements WebappAuthenticator { @@ -45,8 +46,8 @@ public class BasicAuthAuthenticator implements WebappAuthenticator { } @Override - public Status authenticate(Request request, Response response) { - return Status.CONTINUE; + public AuthenticationInfo authenticate(Request request, Response response) { + return new AuthenticationInfo(); } @Override diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java index 77edaadbae0..83631d49fd8 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java @@ -5,13 +5,13 @@ import org.apache.catalina.connector.Response; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; -import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.scep.SCEPException; import org.wso2.carbon.device.mgt.core.scep.SCEPManager; import org.wso2.carbon.device.mgt.core.scep.TenantedDeviceWrapper; -import org.wso2.carbon.webapp.authenticator.framework.DataHolder; +import org.wso2.carbon.webapp.authenticator.framework.AuthenticatorFrameworkDataHolder; +import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; import java.security.cert.X509Certificate; @@ -27,56 +27,47 @@ public class CertificateAuthenticator implements WebappAuthenticator { @Override public boolean canHandle(Request request) { String certVerificationHeader = request.getContext().findParameter(CERTIFICATE_VERIFICATION_HEADER); - if (certVerificationHeader != null && !certVerificationHeader.isEmpty()) { - String certHeader = request.getHeader(certVerificationHeader); - return certHeader != null; } - return false; } @Override - public Status authenticate(Request request, Response response) { + public AuthenticationInfo authenticate(Request request, Response response) { + AuthenticationInfo authenticationInfo = new AuthenticationInfo(); String requestUri = request.getRequestURI(); if (requestUri == null || requestUri.isEmpty()) { - return Status.CONTINUE; + authenticationInfo.setStatus(Status.CONTINUE); } String certVerificationHeader = request.getContext().findParameter(CERTIFICATE_VERIFICATION_HEADER); - try { if (certVerificationHeader != null && !certVerificationHeader.isEmpty()) { String certHeader = request.getHeader(certVerificationHeader); + if (certHeader != null && + AuthenticatorFrameworkDataHolder.getInstance().getCertificateManagementService(). + verifySignature(certHeader)) { - if (certHeader != null && DataHolder.getInstance().getCertificateManagementService(). - verifySignature(certHeader)) { - - X509Certificate certificate = DataHolder.getInstance().getCertificateManagementService(). - extractCertificateFromSignature(certHeader); - String challengeToken = DataHolder.getInstance().getCertificateManagementService(). - extractChallengeToken(certificate); - - if(challengeToken != null) { + X509Certificate certificate = + AuthenticatorFrameworkDataHolder.getInstance().getCertificateManagementService(). + extractCertificateFromSignature(certHeader); + String challengeToken = AuthenticatorFrameworkDataHolder.getInstance(). + getCertificateManagementService().extractChallengeToken(certificate); + if (challengeToken != null) { challengeToken = challengeToken.substring(challengeToken.indexOf("(") + 1).trim(); - - SCEPManager scepManager = DataHolder.getInstance().getScepManager(); + SCEPManager scepManager = AuthenticatorFrameworkDataHolder.getInstance().getScepManager(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(challengeToken); deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS); - TenantedDeviceWrapper tenantedDeviceWrapper = scepManager.getValidatedDevice(deviceIdentifier); - - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - ctx.setTenantId(tenantedDeviceWrapper.getTenantId()); - ctx.setTenantDomain(tenantedDeviceWrapper.getTenantDomain()); - - return Status.SUCCESS; + authenticationInfo.setTenantDomain(tenantedDeviceWrapper.getTenantDomain()); + authenticationInfo.setTenantId(tenantedDeviceWrapper.getTenantId()); + authenticationInfo.setStatus(Status.CONTINUE); } } } @@ -85,8 +76,7 @@ public class CertificateAuthenticator implements WebappAuthenticator { } catch (SCEPException e) { log.error("SCEPException occurred ", e); } - - return Status.FAILURE; + return authenticationInfo; } @Override diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java index cb71da9fcd4..6e8439368ad 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java @@ -28,14 +28,14 @@ import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.core.util.KeyStoreManager; import org.wso2.carbon.user.api.TenantManager; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import org.wso2.carbon.webapp.authenticator.framework.DataHolder; +import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; +import org.wso2.carbon.webapp.authenticator.framework.AuthenticatorFrameworkDataHolder; import java.security.interfaces.RSAPublicKey; import java.text.ParseException; @@ -49,26 +49,28 @@ public class JWTAuthenticator implements WebappAuthenticator { private static final Log log = LogFactory.getLog(JWTAuthenticator.class); public static final String SIGNED_JWT_AUTH_USERNAME = "Username"; private static final String JWT_AUTHENTICATOR = "JWT"; + private static final String JWT_ASSERTION_HEADER = "X-JWT-Assertion"; @Override public boolean canHandle(Request request) { - String authorizationHeader = request.getHeader(HTTPConstants.HEADER_AUTHORIZATION); - if(decodeAuthorizationHeader(authorizationHeader) != null){ + String authorizationHeader = request.getHeader(JWTAuthenticator.JWT_ASSERTION_HEADER); + if((authorizationHeader != null) && !authorizationHeader.isEmpty()){ return true; } return false; } @Override - public Status authenticate(Request request, Response response) { + public AuthenticationInfo authenticate(Request request, Response response) { String requestUri = request.getRequestURI(); + AuthenticationInfo authenticationInfo = new AuthenticationInfo(); if (requestUri == null || "".equals(requestUri)) { - return Status.CONTINUE; + authenticationInfo.setStatus(Status.CONTINUE); } StringTokenizer tokenizer = new StringTokenizer(requestUri, "/"); String context = tokenizer.nextToken(); if (context == null || "".equals(context)) { - return Status.CONTINUE; + authenticationInfo.setStatus(Status.CONTINUE); } if (log.isDebugEnabled()) { @@ -76,8 +78,7 @@ public class JWTAuthenticator implements WebappAuthenticator { } //Get the filesystem keystore default primary certificate - KeyStoreManager keyStoreManager = KeyStoreManager.getInstance( - MultitenantConstants.SUPER_TENANT_ID); + KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID); try { keyStoreManager.getDefaultPrimaryCertificate(); String authorizationHeader = request.getHeader(HTTPConstants.HEADER_AUTHORIZATION); @@ -89,38 +90,33 @@ public class JWTAuthenticator implements WebappAuthenticator { String username = jwsObject.getJWTClaimsSet().getStringClaim(SIGNED_JWT_AUTH_USERNAME); String tenantDomain = MultitenantUtils.getTenantDomain(username); username = MultitenantUtils.getTenantAwareUsername(username); - TenantManager tenantManager = DataHolder.getInstance().getRealmService().getTenantManager(); + TenantManager tenantManager = AuthenticatorFrameworkDataHolder.getInstance().getRealmService(). + getTenantManager(); int tenantId = tenantManager.getTenantId(tenantDomain); - if (tenantId == -1) { log.error("tenantDomain is not valid. username : " + username + ", tenantDomain " + ": " + tenantDomain); - return Status.FAILURE; - } - - UserStoreManager userStore = DataHolder.getInstance().getRealmService(). - getTenantUserRealm(tenantId).getUserStoreManager(); - if (userStore.isExistingUser(username)) { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - ctx.setTenantId(tenantId); - ctx.setUsername(username); - return Status.SUCCESS; - } - } + } else { + UserStoreManager userStore = AuthenticatorFrameworkDataHolder.getInstance().getRealmService(). + getTenantUserRealm(tenantId).getUserStoreManager(); + if (userStore.isExistingUser(username)) { + authenticationInfo.setTenantId(tenantId); + authenticationInfo.setUsername(username); + authenticationInfo.setTenantDomain(tenantDomain); + authenticationInfo.setStatus(Status.CONTINUE); + } + } + } } catch (UserStoreException e) { log.error("Error occurred while obtaining the user.", e); - return Status.FAILURE; } catch (ParseException e) { log.error("Error occurred while parsing the JWT header.", e); - return Status.FAILURE; } catch (JOSEException e) { log.error("Error occurred while verifying the JWT header.", e); - return Status.FAILURE; } catch (Exception e) { log.error("Error occurred while verifying the JWT header.", e); - return Status.FAILURE; } - return Status.CONTINUE; + return authenticationInfo; } private String decodeAuthorizationHeader(String authorizationHeader) { diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java index 3fd3027592c..241e7de9b49 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java @@ -25,16 +25,12 @@ import org.apache.commons.logging.LogFactory; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.wso2.carbon.apimgt.core.gateway.APITokenAuthenticator; -import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.identity.base.IdentityException; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO; import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import org.wso2.carbon.webapp.authenticator.framework.AuthenticationException; -import org.wso2.carbon.webapp.authenticator.framework.AuthenticationFrameworkUtil; -import org.wso2.carbon.webapp.authenticator.framework.Constants; -import org.wso2.carbon.webapp.authenticator.framework.DataHolder; +import org.wso2.carbon.webapp.authenticator.framework.*; import java.util.StringTokenizer; import java.util.regex.Matcher; @@ -55,8 +51,7 @@ public class OAuthAuthenticator implements WebappAuthenticator { @Override public boolean canHandle(Request request) { MessageBytes authorization = - request.getCoyoteRequest().getMimeHeaders(). - getValue(Constants.HTTPHeaders.HEADER_HTTP_AUTHORIZATION); + request.getCoyoteRequest().getMimeHeaders().getValue(Constants.HTTPHeaders.HEADER_HTTP_AUTHORIZATION); String tokenValue; if (authorization != null) { authorization.toBytes(); @@ -71,35 +66,34 @@ public class OAuthAuthenticator implements WebappAuthenticator { } @Override - public Status authenticate(Request request, Response response) { + public AuthenticationInfo authenticate(Request request, Response response) { String requestUri = request.getRequestURI(); String requestMethod = request.getMethod(); + AuthenticationInfo authenticationInfo = new AuthenticationInfo(); if (requestUri == null || "".equals(requestUri)) { - return Status.CONTINUE; + authenticationInfo.setStatus(Status.CONTINUE); + return authenticationInfo; } StringTokenizer tokenizer = new StringTokenizer(requestUri, "/"); String context = tokenizer.nextToken(); if (context == null || "".equals(context)) { - return Status.CONTINUE; + authenticationInfo.setStatus(Status.CONTINUE); } String apiVersion = tokenizer.nextToken(); - String authLevel = authenticator.getResourceAuthenticationScheme(context, apiVersion, - requestUri, - requestMethod); + String authLevel = authenticator.getResourceAuthenticationScheme(context, apiVersion, requestUri, requestMethod); + //String authLevel = "any"; try { if (Constants.NO_MATCHING_AUTH_SCHEME.equals(authLevel)) { - AuthenticationFrameworkUtil - .handleNoMatchAuthScheme(request, response, requestMethod, - apiVersion, context); - return Status.CONTINUE; + AuthenticationFrameworkUtil.handleNoMatchAuthScheme(request, response, requestMethod, apiVersion, + context); + authenticationInfo.setStatus(Status.CONTINUE); } else { String bearerToken = this.getBearerToken(request); // Create a OAuth2TokenValidationRequestDTO object for validating access token OAuth2TokenValidationRequestDTO dto = new OAuth2TokenValidationRequestDTO(); //Set the access token info - OAuth2TokenValidationRequestDTO.OAuth2AccessToken oAuth2AccessToken = - dto.new OAuth2AccessToken(); + OAuth2TokenValidationRequestDTO.OAuth2AccessToken oAuth2AccessToken = dto.new OAuth2AccessToken(); oAuth2AccessToken.setTokenType(OAuthAuthenticator.BEARER_TOKEN_TYPE); oAuth2AccessToken.setIdentifier(bearerToken); dto.setAccessToken(oAuth2AccessToken); @@ -109,36 +103,32 @@ public class OAuthAuthenticator implements WebappAuthenticator { resourceContextParam.setKey(OAuthAuthenticator.RESOURCE_KEY); resourceContextParam.setValue(requestUri + ":" + requestMethod); - OAuth2TokenValidationRequestDTO.TokenValidationContextParam [] + OAuth2TokenValidationRequestDTO.TokenValidationContextParam[] tokenValidationContextParams = new OAuth2TokenValidationRequestDTO.TokenValidationContextParam[1]; tokenValidationContextParams[0] = resourceContextParam; dto.setContext(tokenValidationContextParams); OAuth2TokenValidationResponseDTO oAuth2TokenValidationResponseDTO = - DataHolder.getInstance(). - getoAuth2TokenValidationService().validate(dto); + AuthenticatorFrameworkDataHolder.getInstance().getoAuth2TokenValidationService().validate(dto); if (oAuth2TokenValidationResponseDTO.isValid()) { String username = oAuth2TokenValidationResponseDTO.getAuthorizedUser(); try { - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId( - IdentityUtil.getTenantIdOFUser(username)); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( - MultitenantUtils.getTenantDomain(username)); + authenticationInfo.setUsername(username); + authenticationInfo.setTenantDomain(MultitenantUtils.getTenantDomain(username)); + authenticationInfo.setTenantId(IdentityUtil.getTenantIdOFUser(username)); } catch (IdentityException e) { throw new AuthenticationException( - "Error occurred while retrieving the tenant ID of user '" + - username + "'", e); + "Error occurred while retrieving the tenant ID of user '" + username + "'", e); + } + if (oAuth2TokenValidationResponseDTO.isValid()) { + authenticationInfo.setStatus(Status.CONTINUE); } - boolean isAuthenticated = oAuth2TokenValidationResponseDTO.isValid(); - return (isAuthenticated) ? Status.SUCCESS : Status.FAILURE; } } } catch (AuthenticationException e) { log.error("Failed to authenticate the incoming request", e); - return Status.FAILURE; } - return Status.FAILURE; + return authenticationInfo; } @Override diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java index 18e49cb2125..d3493e329d5 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/WebappAuthenticator.java @@ -20,6 +20,7 @@ package org.wso2.carbon.webapp.authenticator.framework.authenticator; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; +import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; public interface WebappAuthenticator { @@ -29,7 +30,7 @@ public interface WebappAuthenticator { boolean canHandle(Request request); - Status authenticate(Request request, Response response); + AuthenticationInfo authenticate(Request request, Response response); String getName(); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizationValve.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizationValve.java index 27042131a5b..c8abdab4449 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizationValve.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizationValve.java @@ -38,14 +38,13 @@ public class PermissionAuthorizationValve extends CarbonTomcatValve { @Override public void invoke(Request request, Response response, CompositeValve compositeValve) { - String permissionStatus = - request.getContext().findParameter(AUTHORIZATION_ENABLED); + String permissionStatus = request.getContext().findParameter(AUTHORIZATION_ENABLED); if (permissionStatus == null || permissionStatus.isEmpty()) { this.processResponse(request, response, compositeValve, WebappAuthenticator.Status.CONTINUE); return; } // check whether the permission checking function is enabled in web.xml - boolean isEnabled = new Boolean(permissionStatus); + boolean isEnabled = Boolean.valueOf(permissionStatus); if (!isEnabled) { this.processResponse(request, response, compositeValve, WebappAuthenticator.Status.CONTINUE); return; diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java index ce4623b4cba..29230f4bb68 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java @@ -44,13 +44,11 @@ public class PermissionAuthorizer { String requestUri = request.getRequestURI(); String requestMethod = request.getMethod(); - if (requestUri == null || requestUri.isEmpty() || - requestMethod == null || requestMethod.isEmpty()) { + if (requestUri == null || requestUri.isEmpty() || requestMethod == null || requestMethod.isEmpty()) { return WebappAuthenticator.Status.CONTINUE; } - PermissionManagerServiceImpl - registryBasedPermissionManager = PermissionManagerServiceImpl.getInstance(); + PermissionManagerServiceImpl registryBasedPermissionManager = PermissionManagerServiceImpl.getInstance(); Properties properties = new Properties(); properties.put("",requestUri); properties.put("",requestMethod); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java index d00164ea9a3..e09acd59ca2 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/internal/WebappAuthenticatorFrameworkServiceComponent.java @@ -27,8 +27,8 @@ import org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService; import org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve; import org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer; import org.wso2.carbon.user.core.service.RealmService; -import org.wso2.carbon.webapp.authenticator.framework.DataHolder; -import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticationHandler; +import org.wso2.carbon.webapp.authenticator.framework.AuthenticatorFrameworkDataHolder; +import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticationValve; import org.wso2.carbon.webapp.authenticator.framework.authenticator.WebappAuthenticator; import org.wso2.carbon.webapp.authenticator.framework.WebappAuthenticatorRepository; import org.wso2.carbon.webapp.authenticator.framework.config.AuthenticatorConfig; @@ -77,15 +77,14 @@ public class WebappAuthenticatorFrameworkServiceComponent { WebappAuthenticatorConfig.init(); WebappAuthenticatorRepository repository = new WebappAuthenticatorRepository(); for (AuthenticatorConfig config : WebappAuthenticatorConfig.getInstance().getAuthenticators()) { - WebappAuthenticator authenticator = - (WebappAuthenticator) Class.forName(config.getClassName()).newInstance(); + WebappAuthenticator authenticator = (WebappAuthenticator) Class.forName(config.getClassName()). + newInstance(); repository.addAuthenticator(authenticator); } - DataHolder.getInstance().setWebappAuthenticatorRepository(repository); + AuthenticatorFrameworkDataHolder.getInstance().setWebappAuthenticatorRepository(repository); List valves = new ArrayList(); - valves.add(new WebappAuthenticationHandler()); - //valves.add(new PermissionAuthorizationValve()); + valves.add(new WebappAuthenticationValve()); TomcatValveContainer.addValves(valves); if (log.isDebugEnabled()) { @@ -105,18 +104,18 @@ public class WebappAuthenticatorFrameworkServiceComponent { if (log.isDebugEnabled()) { log.debug("RealmService acquired"); } - DataHolder.getInstance().setRealmService(realmService); + AuthenticatorFrameworkDataHolder.getInstance().setRealmService(realmService); } protected void unsetRealmService(RealmService realmService) { - DataHolder.getInstance().setRealmService(null); + AuthenticatorFrameworkDataHolder.getInstance().setRealmService(null); } protected void setCertificateManagementService(CertificateManagementService certificateManagementService) { if (log.isDebugEnabled()) { log.debug("Setting certificate management service"); } - DataHolder.getInstance().setCertificateManagementService(certificateManagementService); + AuthenticatorFrameworkDataHolder.getInstance().setCertificateManagementService(certificateManagementService); } protected void unsetCertificateManagementService(CertificateManagementService certificateManagementService) { @@ -124,14 +123,14 @@ public class WebappAuthenticatorFrameworkServiceComponent { log.debug("Removing certificate management service"); } - DataHolder.getInstance().setCertificateManagementService(null); + AuthenticatorFrameworkDataHolder.getInstance().setCertificateManagementService(null); } protected void setSCEPManagementService(SCEPManager scepManager) { if (log.isDebugEnabled()) { log.debug("Setting SCEP management service"); } - DataHolder.getInstance().setScepManager(scepManager); + AuthenticatorFrameworkDataHolder.getInstance().setScepManager(scepManager); } protected void unsetSCEPManagementService(SCEPManager scepManager) { @@ -139,7 +138,7 @@ public class WebappAuthenticatorFrameworkServiceComponent { log.debug("Removing SCEP management service"); } - DataHolder.getInstance().setScepManager(null); + AuthenticatorFrameworkDataHolder.getInstance().setScepManager(null); } /** @@ -151,7 +150,7 @@ public class WebappAuthenticatorFrameworkServiceComponent { if (log.isDebugEnabled()) { log.debug("Setting OAuth2TokenValidationService Service"); } - DataHolder.getInstance().setoAuth2TokenValidationService(tokenValidationService); + AuthenticatorFrameworkDataHolder.getInstance().setoAuth2TokenValidationService(tokenValidationService); } /** @@ -163,6 +162,6 @@ public class WebappAuthenticatorFrameworkServiceComponent { if (log.isDebugEnabled()) { log.debug("Unsetting OAuth2TokenValidationService Service"); } - DataHolder.getInstance().setoAuth2TokenValidationService(null); + AuthenticatorFrameworkDataHolder.getInstance().setoAuth2TokenValidationService(null); } } From 9fca18ae906779e41ff3e084629faf65b4e7e571 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Wed, 14 Oct 2015 18:54:39 +0530 Subject: [PATCH 17/23] Fixing the monitoring issue --- .../carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java index e72b1d25fa2..75350b3fdcc 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java @@ -27,9 +27,7 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; -import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfigRepository; import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration; -import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO; import org.wso2.carbon.device.mgt.core.dto.DeviceType; @@ -320,6 +318,7 @@ public class MonitoringManagerImpl implements MonitoringManager { if (!deviceIdsToAddOperation.isEmpty()) { // monitoringDAO.addComplianceDetails(firstTimeDeviceIdsWithPolicyIds); monitoringDAO.addComplianceDetails(firstTimeDevices); + monitoringDAO.updateAttempts(new ArrayList<>(deviceIdsToAddOperation.keySet()), false); } if (!deviceIdsWithExistingOperation.isEmpty()) { From d52df2474e98a17704877451cc0c76aff45aaa24 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Thu, 15 Oct 2015 13:01:53 +0530 Subject: [PATCH 18/23] Fixing policy descriptions --- .../org/wso2/carbon/policy/mgt/common/Policy.java | 15 ++++++++++++--- .../policy/mgt/core/dao/impl/PolicyDAOImpl.java | 14 +++++++++----- .../policy/mgt/core/util/PolicyCreator.java | 6 +++++- .../src/test/resources/sql/CreateH2TestDB.sql | 1 + .../src/main/resources/dbscripts/cdm/h2.sql | 1 + 5 files changed, 28 insertions(+), 9 deletions(-) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java index 6087207db1d..4299549f96d 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java @@ -44,10 +44,11 @@ public class Policy implements Comparable, Serializable { private List users; private boolean active; private boolean updated; + private String description; /* Compliance data*/ - private String Compliance; + private String compliance; /*Dynamic policy attributes*/ @@ -170,6 +171,14 @@ public class Policy implements Comparable, Serializable { this.updated = updated; } + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + @XmlElement public List getPolicyCriterias() { return policyCriterias; @@ -181,11 +190,11 @@ public class Policy implements Comparable, Serializable { @XmlElement public String getCompliance() { - return Compliance; + return compliance; } public void setCompliance(String compliance) { - Compliance = compliance; + this.compliance = compliance; } @XmlElement diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java index b33b71289e2..8513540ea4c 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java @@ -629,15 +629,16 @@ public class PolicyDAOImpl implements PolicyDAO { try { conn = this.getConnection(); String query = "UPDATE DM_POLICY SET NAME = ?, PROFILE_ID = ?, PRIORITY = ?, COMPLIANCE = ?," + - " UPDATED = ? WHERE ID = ? AND TENANT_ID = ?"; + " UPDATED = ?, DESCRIPTION = ? WHERE ID = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(query); stmt.setString(1, policy.getPolicyName()); stmt.setInt(2, policy.getProfile().getProfileId()); stmt.setInt(3, policy.getPriorityId()); stmt.setString(4, policy.getCompliance()); stmt.setInt(5, 1); - stmt.setInt(6, policy.getId()); - stmt.setInt(7, tenantId); + stmt.setString(6, policy.getDescription()); + stmt.setInt(7, policy.getId()); + stmt.setInt(8, tenantId); stmt.executeUpdate(); } catch (SQLException e) { @@ -742,6 +743,7 @@ public class PolicyDAOImpl implements PolicyDAO { policy.setPriorityId(resultSet.getInt("PRIORITY")); policy.setProfileId(resultSet.getInt("PROFILE_ID")); policy.setCompliance(resultSet.getString("COMPLIANCE")); + policy.setDescription(resultSet.getString("DESCRIPTION")); } return policy; @@ -775,6 +777,7 @@ public class PolicyDAOImpl implements PolicyDAO { policy.setTenantId(resultSet.getInt("TENANT_ID")); policy.setPriorityId(resultSet.getInt("PRIORITY")); policy.setCompliance(resultSet.getString("COMPLIANCE")); + policy.setDescription(resultSet.getString("DESCRIPTION")); } return policy; } catch (SQLException e) { @@ -810,6 +813,7 @@ public class PolicyDAOImpl implements PolicyDAO { policy.setOwnershipType(resultSet.getString("OWNERSHIP_TYPE")); policy.setUpdated(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("UPDATED"))); policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE"))); + policy.setDescription(resultSet.getString("DESCRIPTION")); policies.add(policy); } return policies; @@ -1185,8 +1189,7 @@ public class PolicyDAOImpl implements PolicyDAO { try { conn = this.getConnection(); String query = "INSERT INTO DM_POLICY (NAME, PROFILE_ID, TENANT_ID, PRIORITY, COMPLIANCE, OWNERSHIP_TYPE," + - " " + - "UPDATED, ACTIVE) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; + "UPDATED, ACTIVE, DESCRIPTION) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; stmt = conn.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS); stmt.setString(1, policy.getPolicyName()); @@ -1197,6 +1200,7 @@ public class PolicyDAOImpl implements PolicyDAO { stmt.setString(6, policy.getOwnershipType()); stmt.setInt(7, 0); stmt.setInt(8, 0); + stmt.setString(9, policy.getDescription()); int affectedRows = stmt.executeUpdate(); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/PolicyCreator.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/PolicyCreator.java index a7dbe5c4a6f..2b86282aafb 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/PolicyCreator.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/util/PolicyCreator.java @@ -39,6 +39,7 @@ public class PolicyCreator { policy.setUsers(users); policy.setCompliance("NOTIFY"); policy.setOwnershipType("COPE"); + policy.setDescription("This is the first policy."); return policy; } @@ -87,6 +88,7 @@ public class PolicyCreator { policy.setOwnershipType("COPE"); policy.setPolicyCriterias(criteria); + policy.setDescription("This is the second policy."); return policy; @@ -126,7 +128,7 @@ public class PolicyCreator { criteria.add(criterion); policy.setPolicyCriterias(criteria); - + policy.setDescription("This is the third policy."); return policy; } @@ -175,6 +177,8 @@ public class PolicyCreator { policy.setPolicyCriterias(criteria); + policy.setDescription("This is the fourth policy."); + return policy; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql index f221ba0e780..6af5c860314 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/resources/sql/CreateH2TestDB.sql @@ -139,6 +139,7 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE ( CREATE TABLE IF NOT EXISTS DM_POLICY ( ID INT(11) NOT NULL AUTO_INCREMENT , NAME VARCHAR(45) NULL DEFAULT NULL , + DESCRIPTION VARCHAR(1000) NULL, TENANT_ID INT(11) NOT NULL , PROFILE_ID INT(11) NOT NULL , OWNERSHIP_TYPE VARCHAR(45) NULL, diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql index 4e337ef6a39..95a32302b15 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -124,6 +124,7 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE ( CREATE TABLE IF NOT EXISTS DM_POLICY ( ID INT(11) NOT NULL AUTO_INCREMENT , NAME VARCHAR(45) DEFAULT NULL , + DESCRIPTION VARCHAR(1000) NULL, TENANT_ID INT(11) NOT NULL , PROFILE_ID INT(11) NOT NULL , OWNERSHIP_TYPE VARCHAR(45) NULL, From 1025e9a4259e8fbdaf6798796f01884b43aaad1a Mon Sep 17 00:00:00 2001 From: Dulitha Wijewantha Date: Fri, 16 Oct 2015 21:05:51 +0530 Subject: [PATCH 19/23] Fixes to user api --- .../carbon/policy/mgt/core/dao/PolicyDAO.java | 7 ++++ .../mgt/core/dao/impl/PolicyDAOImpl.java | 42 ++++++++++++++----- .../mgt/core/mgt/impl/PolicyManagerImpl.java | 5 ++- .../policy/mgt/core/PolicyDAOTestCase.java | 1 - 4 files changed, 42 insertions(+), 13 deletions(-) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java index d684525148e..9fa1259b313 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java @@ -41,6 +41,13 @@ public interface PolicyDAO { */ Policy addPolicyToRole(List roleNames, Policy policy) throws PolicyManagerDAOException; + /** + * This method is used to add/update the users associated with the policy. + * @param usernameList - List of the users that needs to be applied + * @param policy - policy object with the current role list + * @return + * @throws PolicyManagerDAOException + */ Policy addPolicyToUser(List usernameList, Policy policy) throws PolicyManagerDAOException; Policy addPolicyToDevice(List devices, Policy policy) throws PolicyManagerDAOException; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java index b33b71289e2..7df06e8fe60 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java @@ -110,23 +110,45 @@ public class PolicyDAOImpl implements PolicyDAO { } @Override - public Policy addPolicyToUser(List usernameList, Policy policy) throws PolicyManagerDAOException { + public Policy addPolicyToUser(List usersToAdd, Policy policy) throws PolicyManagerDAOException { Connection conn; - PreparedStatement stmt = null; + PreparedStatement insertStmt = null; + PreparedStatement deleteStmt = null; + final List currentUsers = policy.getUsers(); + + SetReferenceTransformer transformer = new SetReferenceTransformer(); + + transformer.transform(currentUsers, usersToAdd); + usersToAdd = transformer.getObjectsToAdd(); + List usersToDelete = transformer.getObjectsToRemove(); try { conn = this.getConnection(); - String query = "INSERT INTO DM_USER_POLICY (POLICY_ID, USERNAME) VALUES (?, ?)"; - stmt = conn.prepareStatement(query); - for (String username : usernameList) { - stmt.setInt(1, policy.getId()); - stmt.setString(2, username); - stmt.addBatch(); + if (usersToAdd.size() > 0){ + String query = "INSERT INTO DM_USER_POLICY (POLICY_ID, USERNAME) VALUES (?, ?)"; + insertStmt = conn.prepareStatement(query); + for (String username : usersToAdd) { + insertStmt.setInt(1, policy.getId()); + insertStmt.setString(2, username); + insertStmt.addBatch(); + } + insertStmt.executeBatch(); } - stmt.executeBatch(); + if (usersToDelete.size() > 0){ + String deleteQuery = "DELETE FROM DM_USER_POLICY WHERE USERNAME=? AND POLICY_ID=?"; + deleteStmt = conn.prepareStatement(deleteQuery); + for (String username : usersToDelete) { + deleteStmt.setString(1, username); + deleteStmt.setInt(2, policy.getId()); + deleteStmt.addBatch(); + } + deleteStmt.executeBatch(); + } + } catch (SQLException e) { throw new PolicyManagerDAOException("Error occurred while adding the user name with policy to database", e); } finally { - PolicyManagementDAOUtil.cleanupResources(stmt, null); + PolicyManagementDAOUtil.cleanupResources(insertStmt, null); + PolicyManagementDAOUtil.cleanupResources(deleteStmt, null); } return policy; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java index 7474651d0d2..263817802bc 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java @@ -471,17 +471,18 @@ public class PolicyManagerImpl implements PolicyManager { Policy policy; List deviceList; List roleNames; - + List userNames; try { PolicyManagementDAOFactory.openConnection(); policy = policyDAO.getPolicy(policyId); roleNames = policyDAO.getPolicyAppliedRoles(policyId); + userNames = policyDAO.getPolicyAppliedUsers(policyId); Profile profile = profileDAO.getProfile(policy.getProfileId()); policy.setProfile(profile); policy.setRoles(roleNames); - + policy.setUsers(userNames); } catch (PolicyManagerDAOException e) { throw new PolicyManagementException("Error occurred while getting the policy related to policy ID (" + diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java index 730e02071cb..b17fda051c9 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/test/java/org/wso2/carbon/policy/mgt/core/PolicyDAOTestCase.java @@ -311,7 +311,6 @@ public class PolicyDAOTestCase extends BasePolicyManagementDAOTest { policy = pap.addPolicy(policy); pap.activatePolicy(policy.getId()); List users = new ArrayList<>(); - log.debug(policy.getRoles().size()); users.add("Udara"); users.add("Dileesha"); policy.setUsers(users); From 5962694ec2f920cb00aaa1ab31fa01509db39e8d Mon Sep 17 00:00:00 2001 From: Dulitha Wijewantha Date: Fri, 16 Oct 2015 23:37:58 +0530 Subject: [PATCH 20/23] Adding annotation for the description --- .../src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java | 1 + 1 file changed, 1 insertion(+) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java index 4299549f96d..c5b8ed303d9 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Policy.java @@ -171,6 +171,7 @@ public class Policy implements Comparable, Serializable { this.updated = updated; } + @XmlElement public String getDescription() { return description; } From 8a8a152d363c4d63bfd548c2d88128ad50087df4 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Fri, 16 Oct 2015 23:47:16 +0530 Subject: [PATCH 21/23] Adding the policy task config --- .../mgt/core/dao/impl/PolicyDAOImpl.java | 4 ++ .../PolicyManagementServiceComponent.java | 5 ++- .../mgt/core/util/PolicyManagerUtil.java | 44 ++++++++++++++++++- 3 files changed, 50 insertions(+), 3 deletions(-) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java index 8513540ea4c..7f87b93a7bb 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java @@ -744,6 +744,8 @@ public class PolicyDAOImpl implements PolicyDAO { policy.setProfileId(resultSet.getInt("PROFILE_ID")); policy.setCompliance(resultSet.getString("COMPLIANCE")); policy.setDescription(resultSet.getString("DESCRIPTION")); + policy.setUpdated(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("UPDATED"))); + policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE"))); } return policy; @@ -778,6 +780,8 @@ public class PolicyDAOImpl implements PolicyDAO { policy.setPriorityId(resultSet.getInt("PRIORITY")); policy.setCompliance(resultSet.getString("COMPLIANCE")); policy.setDescription(resultSet.getString("DESCRIPTION")); + policy.setUpdated(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("UPDATED"))); + policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE"))); } return policy; } catch (SQLException e) { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java index 1b6f10c1623..c7fb6a3251b 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/internal/PolicyManagementServiceComponent.java @@ -35,6 +35,7 @@ import org.wso2.carbon.policy.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService; import org.wso2.carbon.policy.mgt.core.task.TaskScheduleServiceImpl; +import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; import org.wso2.carbon.user.core.service.RealmService; /** @@ -86,11 +87,13 @@ public class PolicyManagementServiceComponent { componentContext.getBundleContext().registerService( PolicyManagerService.class.getName(), new PolicyManagerServiceImpl(), null); + + PolicyConfiguration policyConfiguration = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(). getDeviceManagementConfigRepository().getPolicyConfiguration(); if(policyConfiguration.getMonitoringEnable()) { TaskScheduleService taskScheduleService = new TaskScheduleServiceImpl(); - taskScheduleService.startTask(policyConfiguration.getMonitoringFrequency()); + taskScheduleService.startTask(PolicyManagerUtil.getMonitoringFequency()); } } catch (Throwable t) { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java index a9d292c732d..502740018b0 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java @@ -22,7 +22,14 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; +import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; +import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration; +import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfigurationManagementService; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; +import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration; +import org.wso2.carbon.device.mgt.core.config.tenant.TenantConfigurationManagementServiceImpl; import org.wso2.carbon.device.mgt.core.operation.mgt.PolicyOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; import org.wso2.carbon.policy.mgt.common.Policy; @@ -47,6 +54,10 @@ public class PolicyManagerUtil { private static final Log log = LogFactory.getLog(PolicyManagerUtil.class); + public static final String GENERAL_CONFIG_RESOURCE_PATH = "general"; + public static final String MONITORING_FREQUENCY = "notifierFrequency"; + + public static Document convertToDocument(File file) throws PolicyManagementException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); @@ -156,13 +167,13 @@ public class PolicyManagerUtil { // } - public static Cache getPolicyCache(String name){ + public static Cache getPolicyCache(String name) { CacheManager manager = getCacheManager(); return (manager != null) ? manager.getCache(name) : Caching.getCacheManager().getCache(name); } - public static Cache> getPolicyListCache(String name){ + public static Cache> getPolicyListCache(String name) { CacheManager manager = getCacheManager(); return (manager != null) ? manager.>getCache(name) : Caching.getCacheManager().>getCache(name); @@ -182,4 +193,33 @@ public class PolicyManagerUtil { } return deviceHashMap; } + + + public static int getMonitoringFequency() { + + TenantConfigurationManagementService configMgtService = new TenantConfigurationManagementServiceImpl(); + TenantConfiguration tenantConfiguration = null; + int monitoringFrequency = 0; + try { + tenantConfiguration = configMgtService.getConfiguration(GENERAL_CONFIG_RESOURCE_PATH); + List configuration = tenantConfiguration.getConfiguration(); + + for (ConfigurationEntry cEntry : configuration) { + if (cEntry.getName().equalsIgnoreCase(MONITORING_FREQUENCY)) { + monitoringFrequency = (int) cEntry.getValue(); + } + } + + } catch (ConfigurationManagementException e) { + log.error("Error while getting the configurations from registry.", e); + } + + if (monitoringFrequency == 0) { + PolicyConfiguration policyConfiguration = DeviceConfigurationManager.getInstance(). + getDeviceManagementConfig().getDeviceManagementConfigRepository().getPolicyConfiguration(); + monitoringFrequency = policyConfiguration.getMonitoringFrequency(); + } + + return monitoringFrequency; + } } From d15eb10636ece6e60dd8bc80cf7507013ca3bb69 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Sat, 17 Oct 2015 17:08:12 +0530 Subject: [PATCH 22/23] Adding the null check to monitiring frequncy and fixing the servlet-api issue which is caused a compilation error --- .../policy/mgt/core/util/PolicyManagerUtil.java | 8 +++++--- pom.xml | 12 ++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java index 502740018b0..990cb24875d 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java @@ -204,9 +204,11 @@ public class PolicyManagerUtil { tenantConfiguration = configMgtService.getConfiguration(GENERAL_CONFIG_RESOURCE_PATH); List configuration = tenantConfiguration.getConfiguration(); - for (ConfigurationEntry cEntry : configuration) { - if (cEntry.getName().equalsIgnoreCase(MONITORING_FREQUENCY)) { - monitoringFrequency = (int) cEntry.getValue(); + if (configuration != null && !configuration.isEmpty()) { + for (ConfigurationEntry cEntry : configuration) { + if (cEntry.getName().equalsIgnoreCase(MONITORING_FREQUENCY)) { + monitoringFrequency = (int) cEntry.getValue(); + } } } diff --git a/pom.xml b/pom.xml index 12b522c5bbb..770dffd2c4a 100644 --- a/pom.xml +++ b/pom.xml @@ -312,6 +312,10 @@ commons-pool.wso2 commons-pool + + javax.servlet + servlet-api + @@ -386,6 +390,10 @@ org.wso2.carbon.registry org.wso2.carbon.registry.extensions + + javax.servlet + servlet-api + @@ -808,6 +816,10 @@ org.wso2.carbon.registry org.wso2.carbon.registry.ws.client + + javax.servlet + servlet-api + From cab888d3211b55ef2c321170aba0b4e6c62b9866 Mon Sep 17 00:00:00 2001 From: inosh-perera Date: Sun, 18 Oct 2015 17:26:32 +0530 Subject: [PATCH 23/23] fixing issues in oauth app creation, SAML. Moving service provider configuratiions to config files --- .../DynamicClientRegistrationServiceImpl.java | 15 +++++++--- .../profile/RegistrationProfile.java | 28 +++++++++++++++++ .../JaggeryOAuthConfigurationSettings.java | 30 +++++++++++++++++++ .../DynamicClientWebAppRegistrationUtil.java | 17 ++++++++++- 4 files changed, 85 insertions(+), 5 deletions(-) diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationServiceImpl.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationServiceImpl.java index 31aa091c267..0679b5f1e28 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationServiceImpl.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationServiceImpl.java @@ -52,12 +52,11 @@ public class DynamicClientRegistrationServiceImpl implements DynamicClientRegist private static final String BASIC_AUTHENTICATOR = "BasicAuthenticator"; private static final String BASIC = "basic"; private static final String LOCAL = "local"; - private static final String ASSERTION_CONSUMER_URI = "https://localhost:9443/mdm/sso/acs"; - private static final String AUDIENCE = "https://null:9443/oauth2/token"; private static final Log log = LogFactory.getLog(DynamicClientRegistrationService.class); private static final String AUTH_TYPE_OAUTH_2 = "oauth2"; private static final String OAUTH_CONSUMER_SECRET = "oauthConsumerSecret"; private static final int STEP_ORDER = 1; + private static final String OAUTH_VERSION = "OAuth-2.0"; @Override public OAuthApplicationInfo registerOAuthApplication(RegistrationProfile profile) throws @@ -122,6 +121,9 @@ public class DynamicClientRegistrationServiceImpl implements DynamicClientRegist String grantType = profile.getGrantType(); String callbackUrl = profile.getCallbackUrl(); boolean isSaaSApp = profile.isSaasApp(); + String audience = profile.getAudience(); + String assertionConsumerURL = profile.getAssertionConsumerURL(); + String recepientValidationURL = profile.getRecepientValidationURL(); if (userId == null || userId.isEmpty()) { return null; @@ -177,6 +179,7 @@ public class DynamicClientRegistrationServiceImpl implements DynamicClientRegist oAuthConsumerApp.setApplicationName(applicationName); oAuthConsumerApp.setCallbackUrl(callbackUrl); oAuthConsumerApp.setGrantTypes(grantType); + oAuthConsumerApp.setOAuthVersion(OAUTH_VERSION); if (log.isDebugEnabled()) { log.debug("Creating OAuth App " + applicationName); } @@ -216,9 +219,13 @@ public class DynamicClientRegistrationServiceImpl implements DynamicClientRegist SAMLSSOServiceProviderDTO samlssoServiceProviderDTO = new SAMLSSOServiceProviderDTO(); samlssoServiceProviderDTO.setIssuer(MDM); - samlssoServiceProviderDTO.setAssertionConsumerUrl(ASSERTION_CONSUMER_URI); + samlssoServiceProviderDTO.setAssertionConsumerUrls(new String[] {assertionConsumerURL}); samlssoServiceProviderDTO.setDoSignResponse(true); - samlssoServiceProviderDTO.setRequestedAudiences(new String[] { AUDIENCE }); + samlssoServiceProviderDTO.setRequestedAudiences(new String[] { audience }); + samlssoServiceProviderDTO.setDefaultAssertionConsumerUrl(assertionConsumerURL); + samlssoServiceProviderDTO.setRequestedRecipients(new String[] {recepientValidationURL}); + samlssoServiceProviderDTO.setDoSignAssertions(true); + SAMLSSOConfigAdmin configAdmin = new SAMLSSOConfigAdmin(getConfigSystemRegistry()); configAdmin.addRelyingPartyServiceProvider(samlssoServiceProviderDTO); diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/profile/RegistrationProfile.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/profile/RegistrationProfile.java index f755e9ed23f..2cc1cce5a42 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/profile/RegistrationProfile.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/profile/RegistrationProfile.java @@ -41,6 +41,34 @@ public class RegistrationProfile { private String tokenScope; private String grantType; private boolean saasApp; + private String audience; + + public String getRecepientValidationURL() { + return recepientValidationURL; + } + + public void setRecepientValidationURL(String recepientValidationURL) { + this.recepientValidationURL = recepientValidationURL; + } + + public String getAssertionConsumerURL() { + return assertionConsumerURL; + } + + public void setAssertionConsumerURL(String assertionConsumerURL) { + this.assertionConsumerURL = assertionConsumerURL; + } + + private String recepientValidationURL; + private String assertionConsumerURL; + + public String getAudience() { + return audience; + } + + public void setAudience(String audience) { + this.audience = audience; + } public boolean isSaasApp() { return saasApp; diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/JaggeryOAuthConfigurationSettings.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/JaggeryOAuthConfigurationSettings.java index 32f8b9bcc96..c46e82e0136 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/JaggeryOAuthConfigurationSettings.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/JaggeryOAuthConfigurationSettings.java @@ -32,6 +32,36 @@ public class JaggeryOAuthConfigurationSettings { private String callbackURL; private String tokenScope; private boolean requireDynamicClientRegistration; + private String audience; + private String assertionConsumerURL; + private String recepientValidationURL; + + @XmlElement(name = "assertionConsumerURL", required = true) + public String getAssertionConsumerURL() { + return assertionConsumerURL; + } + + public void setAssertionConsumerURL(String assertionConsumerURL) { + this.assertionConsumerURL = assertionConsumerURL; + } + + @XmlElement(name = "recepientValidationURL", required = true) + public String getRecepientValidationURL() { + return recepientValidationURL; + } + + public void setRecepientValidationURL(String recepientValidationURL) { + this.recepientValidationURL = recepientValidationURL; + } + + @XmlElement(name = "audience", required = true) + public String getAudience() { + return audience; + } + + public void setAudience(String audience) { + this.audience = audience; + } @XmlElement(name = "saasApp", required = true) public boolean isSaasApp() { diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java index 5c826b338bc..9540d0e9e8e 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java @@ -52,8 +52,11 @@ public class DynamicClientWebAppRegistrationUtil { private final static String OAUTH_PARAM_TOKEN_SCOPE = "tokenScope"; private final static String OAUTH_PARAM_SAAS_APP = "saasApp"; private final static String OAUTH_PARAM_CALLBACK_URL = "callbackURL"; + private final static String AUDIENCE = "audience"; + private final static String ASSERTION_CONSUMER_URL = "assertionConsumerURL"; + private final static String RECEPIENT_VALIDATION_URL = "recepientValidationURL"; private static final String JAGGERY_APP_OAUTH_CONFIG_PATH = - "config" + File.separator + "oauth.json"; + "config" + File.separator + "service-provider.json"; private static final Log log = LogFactory.getLog(DynamicClientWebAppRegistrationUtil.class); @@ -192,6 +195,9 @@ public class DynamicClientWebAppRegistrationUtil { registrationProfile.setClientName(webAppName); registrationProfile.setSaasApp(jaggeryOAuthConfigurationSettings.isSaasApp()); registrationProfile.setOwner(DynamicClientWebAppRegistrationUtil.getUserName()); + registrationProfile.setAudience(jaggeryOAuthConfigurationSettings.getAudience()); + registrationProfile.setAssertionConsumerURL(jaggeryOAuthConfigurationSettings.getAssertionConsumerURL()); + registrationProfile.setRecepientValidationURL(jaggeryOAuthConfigurationSettings.getRecepientValidationURL()); if (jaggeryOAuthConfigurationSettings.getCallbackURL() != null) { registrationProfile.setCallbackUrl(jaggeryOAuthConfigurationSettings.getCallbackURL()); } else { @@ -244,6 +250,15 @@ public class DynamicClientWebAppRegistrationUtil { case DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_CALLBACK_URL: jaggeryOAuthConfigurationSettings.setCallbackURL(reader.nextString()); break; + case DynamicClientWebAppRegistrationUtil.AUDIENCE: + jaggeryOAuthConfigurationSettings.setAudience(reader.nextString()); + break; + case DynamicClientWebAppRegistrationUtil.ASSERTION_CONSUMER_URL: + jaggeryOAuthConfigurationSettings.setAssertionConsumerURL(reader.nextString()); + break; + case DynamicClientWebAppRegistrationUtil.RECEPIENT_VALIDATION_URL: + jaggeryOAuthConfigurationSettings.setRecepientValidationURL(reader.nextString()); + break; } } return jaggeryOAuthConfigurationSettings;