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 8a2f782da5..533a7fc2dc 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/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 d81d7a157c..3ed44c63b1 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/backend-oauth-authenticator/pom.xml b/components/identity-extensions/backend-oauth-authenticator/pom.xml new file mode 100644 index 0000000000..e148f5fdf3 --- /dev/null +++ b/components/identity-extensions/backend-oauth-authenticator/pom.xml @@ -0,0 +1,123 @@ + + + + + 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 + + + org.wso2.carbon.identity + org.wso2.carbon.identity.base + + + org.wso2.carbon.identity + org.wso2.carbon.identity.core + + + org.wso2.carbon + org.wso2.carbon.core + + + org.wso2.carbon + org.wso2.carbon.logging + + + org.wso2.carbon.identity + org.wso2.carbon.identity.application.authentication.framework + + + org.wso2.carbon + org.wso2.carbon.core.services + + + org.wso2.carbon.identity + org.wso2.carbon.identity.oauth + + + org.wso2.carbon.identity + org.wso2.carbon.identity.application.common + + + 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.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.base, + org.wso2.carbon.utils + + + + + + + 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 0000000000..42eafd7888 --- /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 0000000000..beaf5c70b0 --- /dev/null +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/OauthAuthenticator.java @@ -0,0 +1,161 @@ +/* + * 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.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.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 OAuth2TokenValidator tokenValidator; + + public OauthAuthenticator() { + AuthenticatorsConfiguration authenticatorsConfiguration = AuthenticatorsConfiguration.getInstance(); + 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); + } + } + + /** + * 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); + String[] headerPart = headerValue.trim().split(OauthAuthenticatorConstants.SPLITING_CHARACTOR); + String accessToken = headerPart[ACCESS_TOKEN_INDEX]; + OAuthValidationResponse response = null; + try { + response = tokenValidator.validateToken(accessToken); + } catch (RemoteException e) { + log.error("Failed to validate the OAuth token provided.", e); + } + if (response != null && response.isValid()) { + HttpSession session; + if ((session = httpServletRequest.getSession(false)) != null) { + 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()); + } + 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 0000000000..badaf8dbed --- /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 0000000000..59577ac633 --- /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 0000000000..c0c5c8662a --- /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 OAuthValidationResponse with the validated results. + */ + 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/OAuthValidationResponse.java b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidationResponse.java new file mode 100755 index 0000000000..b794a22424 --- /dev/null +++ b/components/identity-extensions/backend-oauth-authenticator/src/main/java/org/wso2/carbon/identity/authenticator/backend/oauth/validator/OAuthValidationResponse.java @@ -0,0 +1,58 @@ +/* +* 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 + */ +@SuppressWarnings("unused") +public class OAuthValidationResponse { + private String userName; + private String tenantDomain; + private boolean isValid; + + public OAuthValidationResponse(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 0000000000..bb88d98f7e --- /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,46 @@ +/* +* 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.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 { + + /** + * The method check the configuration and provide the appropriate implementation for OAuth2TokenValidator + * @return OAuth2TokenValidator + */ + 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 { + 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 new file mode 100755 index 0000000000..8d8a101537 --- /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,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.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.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.stub.OAuth2TokenValidationServiceStub; +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; +import java.util.ArrayList; +import java.util.List; + +/** + * Handles the Authentication form external IDP servers. + * Currently only supports WSO@ IS + */ +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 OAuthValidationResponse with the validated results. + */ + public OAuthValidationResponse validateToken(String token) throws RemoteException { + OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO(); + OAuth2TokenValidationRequestDTO_OAuth2AccessToken accessToken = + new OAuth2TokenValidationRequestDTO_OAuth2AccessToken(); + accessToken.setTokenType(OauthAuthenticatorConstants.BEARER_TOKEN_TYPE); + accessToken.setIdentifier(token); + validationRequest.setAccessToken(accessToken); + OAuth2TokenValidationServiceStub tokenValidationService = + new OAuth2TokenValidationServiceStub(hostURL); + ServiceClient client = tokenValidationService._getServiceClient(); + Options options = client.getOptions(); + List
headerList = new ArrayList<>(); + Header header = new Header(); + header.setName(HTTPConstants.HEADER_AUTHORIZATION); + header.setValue(OauthAuthenticatorConstants.AUTHORIZATION_HEADER_PREFIX_BEARER+ " " + token); + headerList.add(header); + options.setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_HEADERS, headerList); + client.setOptions(options); + OAuth2TokenValidationResponseDTO tokenValidationResponse = tokenValidationService. + findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse(); + boolean isValid = tokenValidationResponse.getValid(); + String userName = null; + String tenantDomain = null; + if(isValid){ + userName = MultitenantUtils.getTenantAwareUsername( + 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 new file mode 100755 index 0000000000..2deb2b3b36 --- /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,60 @@ +/* +* 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.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.OAuth2TokenValidationRequestDTO; +import org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; + +/** + * 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 OAuthValidationResponse with the validated results. + */ + public OAuthValidationResponse validateToken(String token) { + OAuth2TokenValidationRequestDTO validationRequest = new OAuth2TokenValidationRequestDTO(); + OAuth2TokenValidationRequestDTO.OAuth2AccessToken accessToken = + validationRequest.new OAuth2AccessToken(); + accessToken.setTokenType(OauthAuthenticatorConstants.BEARER_TOKEN_TYPE); + accessToken.setIdentifier(token); + validationRequest.setAccessToken(accessToken); + OAuth2TokenValidationService validationService = new OAuth2TokenValidationService(); + OAuth2TokenValidationResponseDTO tokenValidationResponse = validationService. + findOAuthConsumerIfTokenIsValid(validationRequest).getAccessTokenValidationResponse(); + boolean isValid = tokenValidationResponse.isValid(); + String userName = null; + String tenantDomain = null; + if(isValid){ + userName = MultitenantUtils.getTenantAwareUsername( + tokenValidationResponse.getAuthorizedUser()); + tenantDomain = + MultitenantUtils.getTenantDomain(tokenValidationResponse.getAuthorizedUser()); + } + return new OAuthValidationResponse(userName,tenantDomain,isValid); + } +} 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 21f2aec018..d72736f362 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,15 +22,12 @@ 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 { - 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 ac5eab14b2..5d8e7bc5fb 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/pom.xml b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/pom.xml index 51bce89c19..9b44329b6b 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,13 +51,30 @@ ${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, 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/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 c326ee6af8..d9f26334c3 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 f01d817d71..9798200f6f 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 7346ac1f69..7abbb8eeee 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 2eb570cb59..547844869a 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); } @@ -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/DynamicClientRegistrationServiceImpl.java similarity index 75% 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 fa8c10d1c6..0679b5f1e2 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 @@ -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.*; @@ -43,7 +44,7 @@ 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"; @@ -51,15 +52,16 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS 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 DynamicClientRegistrationException { + public OAuthApplicationInfo registerOAuthApplication(RegistrationProfile profile) throws + DynamicClientRegistrationException { OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo(); - String applicationName = profile.getClientName(); if (log.isDebugEnabled()) { @@ -74,9 +76,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 +95,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 +112,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. @@ -123,6 +121,9 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS 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; @@ -152,26 +153,22 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS serviceProvider.setOwner(user); 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" + - "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, userName, tenantDomain); + 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); @@ -182,11 +179,13 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS oAuthConsumerApp.setApplicationName(applicationName); oAuthConsumerApp.setCallbackUrl(callbackUrl); oAuthConsumerApp.setGrantTypes(grantType); + oAuthConsumerApp.setOAuthVersion(OAUTH_VERSION); if (log.isDebugEnabled()) { log.debug("Creating OAuth App " + applicationName); } - if (existingServiceProvider == null) { + if ((existingServiceProvider == null) || (existingServiceProvider.getInboundAuthenticationConfig(). + getInboundAuthenticationRequestConfigs().length == 0)) { oAuthAdminService.registerOAuthApplicationData(oAuthConsumerApp); } @@ -208,22 +207,25 @@ 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); } 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); @@ -238,15 +240,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; @@ -261,15 +263,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) { @@ -285,20 +285,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(); @@ -310,9 +309,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); } @@ -323,16 +322,15 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS try { oAuthAdminService.removeOAuthApplicationData(consumerKey); - - ApplicationManagementService appMgtService = ApplicationManagementService.getInstance(); + 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); @@ -343,36 +341,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 = ApplicationManagementService.getInstance(); + 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 (ApplicationManagementService.getInstance().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/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 a5ba8ecb2b..0000000000 --- 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 0000000000..9d105608e0 --- /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 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 new file mode 100644 index 0000000000..6717742ac3 --- /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,87 @@ +/* + * 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.ServiceRegistration; +import org.osgi.service.component.ComponentContext; +import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService; +import org.wso2.carbon.dynamic.client.registration.impl.DynamicClientRegistrationServiceImpl; +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 DynamicClientRegistrationServiceImpl(); + 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/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 8f8286ba68..2cc1cce5a4 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; @@ -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/pom.xml b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/pom.xml index 79be0e0b4f..438dbcefd9 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 a5f2453f11..d7456f4f8e 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,8 +41,9 @@ import javax.servlet.ServletContext; public class DynamicClientWebAppRegistrationManager { private static DynamicClientWebAppRegistrationManager dynamicClientWebAppRegistrationManager; - private static final Log log = - LogFactory.getLog(DynamicClientWebAppRegistrationManager.class); + private static Map webAppContexts = new HashMap<>(); + + private static final Log log = LogFactory.getLog(DynamicClientWebAppRegistrationManager.class); private DynamicClientWebAppRegistrationManager() { } @@ -47,36 +52,34 @@ 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()); } if (DynamicClientWebAppRegistrationUtil.validateRegistrationProfile(registrationProfile)) { DynamicClientRegistrationService dynamicClientRegistrationService = - DynamicClientWebAppRegistrationDataHolder.getInstance() - .getDynamicClientRegistrationService(); + DynamicClientWebAppRegistrationDataHolder.getInstance().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()); + dynamicClientRegistrationService.registerOAuthApplication(registrationProfile); + 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(), + dynamicClientRegistrationService.unregisterOAuthApplication(registrationProfile.getOwner(), oAuthApplicationInfo.getClientName(), oAuthApplicationInfo.getClientId()); log.warn("Error occurred while persisting the OAuth application data in registry."); @@ -86,69 +89,91 @@ public class DynamicClientWebAppRegistrationManager { registrationProfile.getClientName(), e); } } - return new OAuthApp(); + return null; } - 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 null; } public boolean isRegisteredOAuthApplication(String clientName) { - OAuthApp oAuthApp = this.getOAuthApplicationData(clientName); - if (oAuthApp.getClientKey() != null && oAuthApp.getClientSecret() != null) { + OAuthAppDetails oAuthAppDetails = this.getOAuthApplicationData(clientName); + if (oAuthAppDetails != null && (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); - 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()) { - if (!dynamicClientWebAppRegistrationManager.isRegisteredOAuthApplication(webAppName)) { - registrationProfile = DynamicClientWebAppRegistrationUtil - .constructRegistrationProfile(oAuthSettings, webAppName); - oAuthApp = dynamicClientWebAppRegistrationManager - .registerOAuthApplication(registrationProfile); - } else { - oAuthApp = dynamicClientWebAppRegistrationManager.getOAuthApplicationData(webAppName); - } - } - } - DynamicClientWebAppRegistrationUtil.addClientCredentialsToWebContext(oAuthApp, - servletContext); + public void saveServletContextToCache(StandardContext context) { + DynamicClientWebAppRegistrationManager.webAppContexts.put(context.getBaseName(), + context.getServletContext()); } -} + public void initiateDynamicClientRegistration() { + String requiredDynamicClientRegistration, webAppName; + ServletContext servletContext; + RegistrationProfile registrationProfile; + OAuthAppDetails oAuthAppDetails = null; + DynamicClientWebAppRegistrationManager dynamicClientWebAppRegistrationManager = + DynamicClientWebAppRegistrationManager.getInstance(); + //todo move enumeration to while loop + Enumeration enumeration = new IteratorEnumeration(DynamicClientWebAppRegistrationManager. + webAppContexts.keySet().iterator()); + if (log.isDebugEnabled()) { + log.debug("Initiating the DynamicClientRegistration service for web-apps"); + } + 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))) { + //Check whether this is an already registered application + if (!dynamicClientWebAppRegistrationManager.isRegisteredOAuthApplication(webAppName)) { + //Construct the RegistrationProfile + registrationProfile = DynamicClientWebAppRegistrationUtil. + constructRegistrationProfile(servletContext, webAppName); + //Register the OAuth application + oAuthAppDetails = + dynamicClientWebAppRegistrationManager.registerOAuthApplication(registrationProfile); + + } else { + 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 != null && oAuthAppDetails.getClientKey() != null) && !oAuthAppDetails.getClientKey().isEmpty()) { + DynamicClientWebAppRegistrationUtil.addClientCredentialsToWebContext(oAuthAppDetails, + servletContext); + log.info("Added OAuth application credentials to webapp context of webapp : " + + webAppName); + } + } + } +} \ 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 0000000000..6ed87bc28d --- /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 66% 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 42ee098f28..c46e82e013 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,22 +16,52 @@ * 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; /** - * Represents OAuthConfiguration data. + * Represents OAuthConfiguration data required to create OAuth service provider for Jaggery apps. */ @XmlRootElement(name = "OAuthSettings") -public class OAuthSettings { +public class JaggeryOAuthConfigurationSettings { private String grantType; private boolean saasApp; 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/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 89% 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 7195f55706..9ae885c67b 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,16 +16,16 @@ * 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; /** - * Represents an OAuth application with basic data. + * Represents an OAuth application with basic necessary 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/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 af96d2a37d..b40e9a5504 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 7950a4dbb8..3707e9ef5c 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,113 +58,119 @@ import org.wso2.carbon.utils.ConfigurationContextService; */ public class DynamicClientWebAppRegistrationServiceComponent { - 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); + } - } + @SuppressWarnings("unused") + protected void deactivate(ComponentContext componentContext) { - @SuppressWarnings("unused") - protected void deactivate(ComponentContext componentContext) { - //do nothing - } + } - /** - * 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 ce8e452a82..29d1f1ae0b 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().initiateDynamicClientRegistrationProcess( - 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 1dd54c40f1..9540d0e9e8 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; @@ -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); @@ -62,9 +65,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: " + @@ -72,115 +74,98 @@ public class DynamicClientWebAppRegistrationUtil { } } - public static OAuthApp getOAuthApplicationData(String appName) + 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"); } 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( - new StringReader(new String((byte[]) resource.getContent(), Charset - .forName( - DynamicClientWebAppRegistrationConstants.CharSets.CHARSET_UTF8)))); + 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); } 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(OAuthApp oAuthApp) - throws DynamicClientRegistrationException { + public static boolean putOAuthApplicationData(OAuthAppDetails oAuthAppDetails) throws + DynamicClientRegistrationException { boolean status; try { if (log.isDebugEnabled()) { 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(); + Resource resource = DynamicClientWebAppRegistrationUtil.getGovernanceRegistry().newResource(); resource.setContent(writer.toString()); resource.setMediaType(DynamicClientWebAppRegistrationConstants.ContentTypes.MEDIA_TYPE_XML); - String resourcePath = - DynamicClientWebAppRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH + "/" + - oAuthApp.getWebAppName(); - status = - DynamicClientWebAppRegistrationUtil.putRegistryResource(resourcePath, resource); + String resourcePath = DynamicClientWebAppRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH + "/" + + 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; } - 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,40 +178,40 @@ 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( - OAuthSettings oAuthSettings, String webAppName) { + public static RegistrationProfile constructRegistrationProfile(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()); + registrationProfile.setAudience(jaggeryOAuthConfigurationSettings.getAudience()); + registrationProfile.setAssertionConsumerURL(jaggeryOAuthConfigurationSettings.getAssertionConsumerURL()); + registrationProfile.setRecepientValidationURL(jaggeryOAuthConfigurationSettings.getRecepientValidationURL()); + 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 " + @@ -240,43 +225,50 @@ 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); + 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(); 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; + 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 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 +296,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/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 84% 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 0432238fac..ba56143668 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"; @@ -46,13 +46,14 @@ public class ScopeValidator 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"; 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,18 +65,19 @@ 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 { 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/identity-extensions/pom.xml b/components/identity-extensions/pom.xml index 78a24d9adb..8dbb24619d 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/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 6087207db1..c5b8ed303d 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,15 @@ public class Policy implements Comparable, Serializable { this.updated = updated; } + @XmlElement + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + @XmlElement public List getPolicyCriterias() { return policyCriterias; @@ -181,11 +191,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/PolicyManagerService.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/PolicyManagerService.java index 15ed689e4b..f4514a2c0d 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 1ad71fa0f9..2027c10a7f 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/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 9f5ba5b255..9fa1259b31 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,8 +32,22 @@ 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; + /** + * 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 e1921f1aac..322b57918c 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,45 +68,87 @@ 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; } @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; } @@ -611,15 +651,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) { @@ -724,6 +765,9 @@ 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")); + policy.setUpdated(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("UPDATED"))); + policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE"))); } return policy; @@ -757,6 +801,9 @@ 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")); + policy.setUpdated(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("UPDATED"))); + policy.setActive(PolicyManagerUtil.convertIntToBoolean(resultSet.getInt("ACTIVE"))); } return policy; } catch (SQLException e) { @@ -792,6 +839,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; @@ -1167,8 +1215,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()); @@ -1179,6 +1226,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/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 1b6f10c162..c7fb6a3251 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/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 e72b1d25fa..75350b3fdc 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()) { 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 a9f1a10fd8..263817802b 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) { @@ -468,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/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 648fba4aed..9be3b71b96 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 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 982b3859a7..990cb24875 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; @@ -41,15 +48,16 @@ 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 { 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); @@ -159,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); @@ -185,4 +193,35 @@ 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(); + + if (configuration != null && !configuration.isEmpty()) { + 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; + } } 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 0000000000..f9d78e05fc --- /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 ffc592b335..b17fda051c 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); } 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 a7dbe5c4a6..2b86282aaf 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 f221ba0e78..6af5c86031 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/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 e66f9a1cd5..6ca33feb7a 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 0000000000..a65c99fa39 --- /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 6bc406b27c..547cda44a5 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 7eb98c0d55..c416444682 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 c0e0e68a49..9613b18c00 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 02b94941cd..0000000000 --- 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 74396ab9c5..902c796b55 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 77edaadbae..83631d49fd 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 cb71da9fcd..6e8439368a 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 3fd3027592..241e7de9b4 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 18e49cb212..d3493e329d 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 27042131a5..c8abdab444 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 ce4623b4cb..29230f4bb6 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 d00164ea9a..e09acd59ca 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); } } 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 4e337ef6a3..95a32302b1 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, diff --git a/pom.xml b/pom.xml index 26df26d760..770dffd2c4 100644 --- a/pom.xml +++ b/pom.xml @@ -152,10 +152,6 @@ org.eclipse.osgi org.eclipse.osgi - - org.eclipse.osgi - org.eclipse.osgi.services - @@ -316,6 +312,10 @@ commons-pool.wso2 commons-pool + + javax.servlet + servlet-api + @@ -390,6 +390,10 @@ org.wso2.carbon.registry org.wso2.carbon.registry.extensions + + javax.servlet + servlet-api + @@ -410,6 +414,11 @@ org.eclipse.osgi.services 3.3.100.v20120522-1822 + + org.osgi.ut + org.eclipse.osgi + 3.3.100.v20120522-1822 + @@ -807,6 +816,10 @@ org.wso2.carbon.registry org.wso2.carbon.registry.ws.client + + javax.servlet + servlet-api + @@ -941,6 +954,21 @@ 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 +1154,6 @@ - - org.wso2.carbon.identity - org.wso2.carbon.identity.oauth - ${carbon.identity.version} - org.wso2.carbon.identity org.wso2.carbon.identity.sso.saml