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 5025a796bf..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 @@ -26,11 +26,8 @@ import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationServ */ public class DynamicClientUtil { - public static DynamicClientRegistrationService getDynamicClientRegistrationService() { - DynamicClientRegistrationService dynamicClientRegistrationService; - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - dynamicClientRegistrationService = - (DynamicClientRegistrationService) ctx.getOSGiService(DynamicClientRegistrationService.class, null); - return dynamicClientRegistrationService; - } + public static DynamicClientRegistrationService getDynamicClientRegistrationService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + return (DynamicClientRegistrationService) ctx.getOSGiService(DynamicClientRegistrationService.class, null); + } } diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/impl/RegistrationServiceImpl.java b/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/impl/RegistrationServiceImpl.java index 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/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 379194a3bf..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); } diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationImpl.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationServiceImpl.java similarity index 79% rename from components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationImpl.java rename to components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationServiceImpl.java index fcd1c7c133..31aa091c26 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationImpl.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/impl/DynamicClientRegistrationServiceImpl.java @@ -38,12 +38,13 @@ import org.wso2.carbon.identity.sso.saml.admin.SAMLSSOConfigAdmin; import org.wso2.carbon.identity.sso.saml.dto.SAMLSSOServiceProviderDTO; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; + import java.util.Arrays; /** * Implementation of DynamicClientRegistrationService. */ -public class DynamicClientRegistrationImpl implements DynamicClientRegistrationService { +public class DynamicClientRegistrationServiceImpl implements DynamicClientRegistrationService { private static final String TOKEN_SCOPE = "tokenScope"; private static final String MDM = "mdm"; @@ -54,12 +55,14 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS private static final String ASSERTION_CONSUMER_URI = "https://localhost:9443/mdm/sso/acs"; private static final String AUDIENCE = "https://null:9443/oauth2/token"; private static final Log log = LogFactory.getLog(DynamicClientRegistrationService.class); + private static final String AUTH_TYPE_OAUTH_2 = "oauth2"; + private static final String OAUTH_CONSUMER_SECRET = "oauthConsumerSecret"; + private static final int STEP_ORDER = 1; @Override - public OAuthApplicationInfo registerOAuthApplication(RegistrationProfile profile) - throws DynamicClientRegistrationException { + public OAuthApplicationInfo registerOAuthApplication(RegistrationProfile profile) throws + DynamicClientRegistrationException { OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo(); - String applicationName = profile.getClientName(); if (log.isDebugEnabled()) { @@ -74,9 +77,10 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS OAuthApplicationInfo info; try { info = this.createOAuthApplication(profile); - } catch (Exception e) { - throw new DynamicClientRegistrationException( - "Can not create OAuth application : " + applicationName, e); + } catch (DynamicClientRegistrationException e) { + throw new DynamicClientRegistrationException("Can not create OAuth application : " + applicationName, e); + } catch (IdentityException e) { + throw new DynamicClientRegistrationException("Can not create OAuth application : " + applicationName, e); } if (info == null || info.getJsonString() == null) { @@ -92,18 +96,14 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS try { JSONObject jsonObject = new JSONObject(info.getJsonString()); if (jsonObject.has(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS)) { - oAuthApplicationInfo - .addParameter(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS, - jsonObject - .get(ApplicationConstants.ClientMetadata. - OAUTH_REDIRECT_URIS)); + oAuthApplicationInfo.addParameter(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS, + jsonObject + .get(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS)); } if (jsonObject.has(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT)) { - oAuthApplicationInfo.addParameter(ApplicationConstants.ClientMetadata. - OAUTH_CLIENT_GRANT, jsonObject - .get(ApplicationConstants.ClientMetadata. - OAUTH_CLIENT_GRANT)); + oAuthApplicationInfo.addParameter(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT, jsonObject + .get(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT)); } } catch (JSONException e) { throw new DynamicClientRegistrationException( @@ -113,8 +113,7 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS } private OAuthApplicationInfo createOAuthApplication( - RegistrationProfile profile) - throws DynamicClientRegistrationException, IdentityException { + RegistrationProfile profile) throws DynamicClientRegistrationException, IdentityException { //Subscriber's name should be passed as a parameter, since it's under the subscriber //the OAuth App is created. @@ -152,27 +151,22 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS serviceProvider.setOwner(user); serviceProvider.setDescription("Service Provider for application " + applicationName); - - ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder. - getInstance().getApplicationManagementService(); + ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder.getInstance(). + getApplicationManagementService(); if (appMgtService == null) { - throw new IllegalStateException( - "Error occurred while retrieving Application Management" + - "Service"); + throw new IllegalStateException("Error occurred while retrieving Application Management" + "Service"); } - ServiceProvider existingServiceProvider = appMgtService.getServiceProvider( - applicationName, tenantDomain); + ServiceProvider existingServiceProvider = appMgtService.getServiceProvider(applicationName, tenantDomain); if (existingServiceProvider == null) { appMgtService.createApplication(serviceProvider, tenantDomain, userName); } - ServiceProvider createdServiceProvider = appMgtService.getServiceProvider( - applicationName, tenantDomain); + ServiceProvider createdServiceProvider = appMgtService.getServiceProvider(applicationName, tenantDomain); if (createdServiceProvider == null) { - throw new DynamicClientRegistrationException( - "Couldn't create Service Provider Application " + applicationName); + throw new DynamicClientRegistrationException("Couldn't create Service Provider Application " + + applicationName); } //Set SaaS app option createdServiceProvider.setSaasApp(isSaaSApp); @@ -187,8 +181,8 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS log.debug("Creating OAuth App " + applicationName); } - if ((existingServiceProvider == null) || (existingServiceProvider. - getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs().length == 0)) { + if ((existingServiceProvider == null) || (existingServiceProvider.getInboundAuthenticationConfig(). + getInboundAuthenticationRequestConfigs().length == 0)) { oAuthAdminService.registerOAuthApplicationData(oAuthConsumerApp); } @@ -210,14 +204,13 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS InboundAuthenticationRequestConfig inboundAuthenticationRequestConfig = new InboundAuthenticationRequestConfig(); inboundAuthenticationRequestConfig.setInboundAuthKey(createdApp.getOauthConsumerKey()); - inboundAuthenticationRequestConfig.setInboundAuthType("oauth2"); - if (createdApp.getOauthConsumerSecret() != null && !createdApp. - getOauthConsumerSecret() - .isEmpty()) { + inboundAuthenticationRequestConfig.setInboundAuthType(AUTH_TYPE_OAUTH_2); + String oauthConsumerSecret = createdApp.getOauthConsumerSecret(); + if (oauthConsumerSecret != null && !oauthConsumerSecret.isEmpty()) { Property property = new Property(); - property.setName("oauthConsumerSecret"); - property.setValue(createdApp.getOauthConsumerSecret()); - Property[] properties = {property}; + property.setName(OAUTH_CONSUMER_SECRET); + property.setValue(oauthConsumerSecret); + Property[] properties = { property }; inboundAuthenticationRequestConfig.setProperties(properties); } @@ -225,7 +218,7 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS samlssoServiceProviderDTO.setIssuer(MDM); samlssoServiceProviderDTO.setAssertionConsumerUrl(ASSERTION_CONSUMER_URI); samlssoServiceProviderDTO.setDoSignResponse(true); - samlssoServiceProviderDTO.setRequestedAudiences(new String[]{AUDIENCE}); + samlssoServiceProviderDTO.setRequestedAudiences(new String[] { AUDIENCE }); SAMLSSOConfigAdmin configAdmin = new SAMLSSOConfigAdmin(getConfigSystemRegistry()); configAdmin.addRelyingPartyServiceProvider(samlssoServiceProviderDTO); @@ -240,15 +233,15 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS localAuth.setEnabled(true); AuthenticationStep authStep = new AuthenticationStep(); - authStep.setStepOrder(1); + authStep.setStepOrder(STEP_ORDER); authStep.setSubjectStep(true); authStep.setAttributeStep(true); - authStep.setLocalAuthenticatorConfigs(new LocalAuthenticatorConfig[]{localAuth}); + authStep.setLocalAuthenticatorConfigs(new LocalAuthenticatorConfig[] { localAuth }); LocalAndOutboundAuthenticationConfig localOutboundAuthConfig = new LocalAndOutboundAuthenticationConfig(); localOutboundAuthConfig.setAuthenticationType(LOCAL); - localOutboundAuthConfig.setAuthenticationSteps(new AuthenticationStep[]{authStep}); + localOutboundAuthConfig.setAuthenticationSteps(new AuthenticationStep[] { authStep }); inboundAuthenticationRequestConfigs[0] = inboundAuthenticationRequestConfig; inboundAuthenticationRequestConfigs[1] = samlAuthenticationRequest; @@ -263,15 +256,13 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo(); oAuthApplicationInfo.setClientId(createdApp.getOauthConsumerKey()); oAuthApplicationInfo.setCallBackURL(createdApp.getCallbackUrl()); - oAuthApplicationInfo.setClientSecret(createdApp.getOauthConsumerSecret()); + oAuthApplicationInfo.setClientSecret(oauthConsumerSecret); oAuthApplicationInfo.setClientName(createdApp.getApplicationName()); oAuthApplicationInfo.addParameter( - ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS, - createdApp.getCallbackUrl()); + ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS, createdApp.getCallbackUrl()); oAuthApplicationInfo.addParameter( - ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT, - createdApp.getGrantTypes()); + ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT, createdApp.getGrantTypes()); return oAuthApplicationInfo; } catch (IdentityApplicationManagementException e) { @@ -287,20 +278,19 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS } protected Registry getConfigSystemRegistry() { - return (Registry) PrivilegedCarbonContext.getThreadLocalCarbonContext(). - getRegistry(RegistryType.SYSTEM_CONFIGURATION); + return (Registry) PrivilegedCarbonContext.getThreadLocalCarbonContext().getRegistry(RegistryType. + SYSTEM_CONFIGURATION); } @Override - public boolean unregisterOAuthApplication(String userId, String applicationName, - String consumerKey) throws DynamicClientRegistrationException { + public boolean unregisterOAuthApplication(String userId, String applicationName, String consumerKey) throws + DynamicClientRegistrationException { DynamicClientRegistrationUtil.validateUsername(userId); DynamicClientRegistrationUtil.validateApplicationName(applicationName); DynamicClientRegistrationUtil.validateConsumerKey(consumerKey); boolean status = false; String tenantDomain = MultitenantUtils.getTenantDomain(userId); - String baseUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); String userName = MultitenantUtils.getTenantAwareUsername(userId); PrivilegedCarbonContext.startTenantFlow(); @@ -312,9 +302,9 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS try { oAuthAdminService = new OAuthAdminService(); oAuthConsumerApp = oAuthAdminService.getOAuthApplicationData(consumerKey); - } catch (IdentityOAuthAdminException e) { - throw new DynamicClientRegistrationException("Error occurred while retrieving application data", e); } catch (Exception e) { + //We had to catch Exception here because getOAuthApplicationData can throw exceptions of java.lang.Exception + // class. throw new DynamicClientRegistrationException("Error occurred while retrieving application data", e); } @@ -325,17 +315,15 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS try { oAuthAdminService.removeOAuthApplicationData(consumerKey); - - ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder. - getInstance().getApplicationManagementService(); + ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder.getInstance(). + getApplicationManagementService(); if (appMgtService == null) { throw new IllegalStateException( "Error occurred while retrieving Application Management" + - "Service"); + "Service"); } - ServiceProvider createdServiceProvider = appMgtService.getServiceProvider( - applicationName, tenantDomain); + ServiceProvider createdServiceProvider = appMgtService.getServiceProvider(applicationName, tenantDomain); if (createdServiceProvider == null) { throw new DynamicClientRegistrationException( "Couldn't retrieve Service Provider Application " + applicationName); @@ -346,38 +334,31 @@ public class DynamicClientRegistrationImpl implements DynamicClientRegistrationS throw new DynamicClientRegistrationException( "Error occurred while removing ServiceProvider for application '" + applicationName + "'", e); } catch (IdentityOAuthAdminException e) { - throw new DynamicClientRegistrationException("Error occurred while removing application '" + - applicationName + "'", e); - } catch (Exception e) { throw new DynamicClientRegistrationException("Error occurred while removing application '" + applicationName + "'", e); } finally { PrivilegedCarbonContext.endTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(baseUser); } return status; } @Override - public boolean isOAuthApplicationExists(String applicationName) throws DynamicClientRegistrationException { - ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder. - getInstance().getApplicationManagementService(); + public boolean isOAuthApplicationAvailable(String applicationName) throws DynamicClientRegistrationException { + ApplicationManagementService appMgtService = DynamicClientRegistrationDataHolder.getInstance(). + getApplicationManagementService(); if (appMgtService == null) { throw new IllegalStateException( "Error occurred while retrieving Application Management" + - "Service"); + "Service"); } try { - if (appMgtService.getServiceProvider(applicationName, - CarbonContext.getThreadLocalCarbonContext() - .getTenantDomain()) != null) { - return true; - } + return appMgtService.getServiceProvider(applicationName, + CarbonContext.getThreadLocalCarbonContext().getTenantDomain()) != + null; } catch (IdentityApplicationManagementException e) { throw new DynamicClientRegistrationException( "Error occurred while retrieving information of OAuthApp " + applicationName, e); } - return false; } } diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationDataHolder.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationDataHolder.java index 63bda3e337..9d105608e0 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationDataHolder.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationDataHolder.java @@ -45,7 +45,7 @@ public class DynamicClientRegistrationDataHolder { return applicationManagementService; } - public void setApplicationManagementService(ApplicationManagementService realmService) { - this.applicationManagementService = realmService; + public void setApplicationManagementService(ApplicationManagementService applicationManagementService) { + this.applicationManagementService = applicationManagementService; } } diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java index 68d7ef02a0..6717742ac3 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/internal/DynamicClientRegistrationServiceComponent.java @@ -20,9 +20,10 @@ package org.wso2.carbon.dynamic.client.registration.internal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.ComponentContext; import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationService; -import org.wso2.carbon.dynamic.client.registration.impl.DynamicClientRegistrationImpl; +import org.wso2.carbon.dynamic.client.registration.impl.DynamicClientRegistrationServiceImpl; import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; /** @@ -44,9 +45,9 @@ public class DynamicClientRegistrationServiceComponent { log.debug("Starting DynamicClientRegistrationServiceComponent"); } DynamicClientRegistrationService dynamicClientRegistrationService = - new DynamicClientRegistrationImpl(); - componentContext.getBundleContext().registerService(DynamicClientRegistrationService.class.getName(), - dynamicClientRegistrationService, null); + new DynamicClientRegistrationServiceImpl(); + componentContext.getBundleContext().registerService( + DynamicClientRegistrationService.class.getName(), dynamicClientRegistrationService, null); } @SuppressWarnings("unused") diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/profile/RegistrationProfile.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/profile/RegistrationProfile.java index 8f8286ba68..f755e9ed23 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/profile/RegistrationProfile.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration/src/main/java/org/wso2/carbon/dynamic/client/registration/profile/RegistrationProfile.java @@ -19,11 +19,11 @@ package org.wso2.carbon.dynamic.client.registration.profile; /** * - * DTO class to be used when registering a OAuth application. + * DTO class to be used when registering an OAuth application. * * */ public class RegistrationProfile { - +//todo mark mandatory fields private String applicationType; private String[] redirectUris; private String clientName; diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/DynamicClientWebAppRegistrationManager.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/DynamicClientWebAppRegistrationManager.java index b159a3515c..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 @@ -41,11 +41,9 @@ import java.util.*; public class DynamicClientWebAppRegistrationManager { private static DynamicClientWebAppRegistrationManager dynamicClientWebAppRegistrationManager; - private static List registrationProfileList = new ArrayList<>(); private static Map webAppContexts = new HashMap<>(); - private static final Log log = - LogFactory.getLog(DynamicClientWebAppRegistrationManager.class); + private static final Log log = LogFactory.getLog(DynamicClientWebAppRegistrationManager.class); private DynamicClientWebAppRegistrationManager() { } @@ -64,17 +62,14 @@ public class DynamicClientWebAppRegistrationManager { public OAuthAppDetails registerOAuthApplication(RegistrationProfile registrationProfile) { if (log.isDebugEnabled()) { - log.debug("Registering OAuth application for web app : " + - registrationProfile.getClientName()); + log.debug("Registering OAuth application for web app : " + registrationProfile.getClientName()); } if (DynamicClientWebAppRegistrationUtil.validateRegistrationProfile(registrationProfile)) { DynamicClientRegistrationService dynamicClientRegistrationService = - DynamicClientWebAppRegistrationDataHolder.getInstance() - .getDynamicClientRegistrationService(); + DynamicClientWebAppRegistrationDataHolder.getInstance().getDynamicClientRegistrationService(); try { OAuthApplicationInfo oAuthApplicationInfo = - dynamicClientRegistrationService - .registerOAuthApplication(registrationProfile); + dynamicClientRegistrationService.registerOAuthApplication(registrationProfile); OAuthAppDetails oAuthAppDetails = new OAuthAppDetails(); oAuthAppDetails.setWebAppName(registrationProfile.getClientName()); oAuthAppDetails.setClientName(oAuthApplicationInfo.getClientName()); @@ -84,19 +79,17 @@ public class DynamicClientWebAppRegistrationManager { if (DynamicClientWebAppRegistrationUtil.putOAuthApplicationData(oAuthAppDetails)) { return oAuthAppDetails; } else { - dynamicClientRegistrationService - .unregisterOAuthApplication(registrationProfile.getOwner(), + dynamicClientRegistrationService.unregisterOAuthApplication(registrationProfile.getOwner(), oAuthApplicationInfo.getClientName(), oAuthApplicationInfo.getClientId()); - log.warn( - "Error occurred while persisting the OAuth application data in registry."); + log.warn("Error occurred while persisting the OAuth application data in registry."); } } catch (DynamicClientRegistrationException e) { log.error("Error occurred while registering the OAuth application : " + registrationProfile.getClientName(), e); } } - return new OAuthAppDetails(); + return null; } public OAuthAppDetails getOAuthApplicationData(String clientName) { @@ -106,12 +99,13 @@ public class DynamicClientWebAppRegistrationManager { log.error("Error occurred while fetching the OAuth application data for web app : " + clientName, e); } - return new OAuthAppDetails(); + return null; } public boolean isRegisteredOAuthApplication(String clientName) { OAuthAppDetails oAuthAppDetails = this.getOAuthApplicationData(clientName); - if (oAuthAppDetails.getClientKey() != null && oAuthAppDetails.getClientSecret() != null) { + if (oAuthAppDetails != null && (oAuthAppDetails.getClientKey() != null && oAuthAppDetails.getClientSecret() != + null)) { return true; } return false; @@ -119,66 +113,66 @@ public class DynamicClientWebAppRegistrationManager { public void saveServletContextToCache(StandardContext context) { DynamicClientWebAppRegistrationManager.webAppContexts.put(context.getBaseName(), - context.getServletContext()); + context.getServletContext()); } public void initiateDynamicClientRegistration() { String requiredDynamicClientRegistration, webAppName; ServletContext servletContext; RegistrationProfile registrationProfile; - OAuthAppDetails oAuthAppDetails = new OAuthAppDetails(); + OAuthAppDetails oAuthAppDetails = null; DynamicClientWebAppRegistrationManager dynamicClientWebAppRegistrationManager = DynamicClientWebAppRegistrationManager.getInstance(); - + //todo move enumeration to while loop Enumeration enumeration = new IteratorEnumeration(DynamicClientWebAppRegistrationManager. - webAppContexts.keySet().iterator()); + webAppContexts.keySet().iterator()); if (log.isDebugEnabled()) { log.debug("Initiating the DynamicClientRegistration service for web-apps"); } - while (enumeration.hasMoreElements()){ + while (enumeration.hasMoreElements()) { + oAuthAppDetails = new OAuthAppDetails(); webAppName = (String) enumeration.nextElement(); servletContext = DynamicClientWebAppRegistrationManager.webAppContexts.get(webAppName); requiredDynamicClientRegistration = servletContext.getInitParameter( DynamicClientWebAppRegistrationConstants.DYNAMIC_CLIENT_REQUIRED_FLAG); //Java web-app section - if ((requiredDynamicClientRegistration != null) && - (Boolean.parseBoolean(requiredDynamicClientRegistration))) { + if ((requiredDynamicClientRegistration != null) && (Boolean. + parseBoolean( + requiredDynamicClientRegistration))) { //Check whether this is an already registered application if (!dynamicClientWebAppRegistrationManager.isRegisteredOAuthApplication(webAppName)) { //Construct the RegistrationProfile registrationProfile = DynamicClientWebAppRegistrationUtil. - constructRegistrationProfile(servletContext, - webAppName); + constructRegistrationProfile(servletContext, webAppName); //Register the OAuth application - oAuthAppDetails = dynamicClientWebAppRegistrationManager.registerOAuthApplication( - registrationProfile); + oAuthAppDetails = + dynamicClientWebAppRegistrationManager.registerOAuthApplication(registrationProfile); } else { - oAuthAppDetails = - dynamicClientWebAppRegistrationManager.getOAuthApplicationData(webAppName); + oAuthAppDetails = dynamicClientWebAppRegistrationManager.getOAuthApplicationData(webAppName); } } else if (requiredDynamicClientRegistration == null) { //Jaggery apps - JaggeryOAuthConfigurationSettings jaggeryOAuthConfigurationSettings = DynamicClientWebAppRegistrationUtil - .getJaggeryAppOAuthSettings(servletContext); + JaggeryOAuthConfigurationSettings jaggeryOAuthConfigurationSettings = + DynamicClientWebAppRegistrationUtil.getJaggeryAppOAuthSettings(servletContext); if (jaggeryOAuthConfigurationSettings.isRequireDynamicClientRegistration()) { - if (!dynamicClientWebAppRegistrationManager - .isRegisteredOAuthApplication(webAppName)) { - registrationProfile = DynamicClientWebAppRegistrationUtil - .constructRegistrationProfile(jaggeryOAuthConfigurationSettings, webAppName); - oAuthAppDetails = dynamicClientWebAppRegistrationManager - .registerOAuthApplication(registrationProfile); + if (!dynamicClientWebAppRegistrationManager.isRegisteredOAuthApplication(webAppName)) { + registrationProfile = DynamicClientWebAppRegistrationUtil. + constructRegistrationProfile(jaggeryOAuthConfigurationSettings, + webAppName); + oAuthAppDetails = dynamicClientWebAppRegistrationManager. + registerOAuthApplication(registrationProfile); } else { - oAuthAppDetails = dynamicClientWebAppRegistrationManager - .getOAuthApplicationData(webAppName); + oAuthAppDetails = dynamicClientWebAppRegistrationManager.getOAuthApplicationData(webAppName); } } } //Add client credentials to the web-context - if (oAuthAppDetails.getClientKey() != null) { + if ((oAuthAppDetails != null && oAuthAppDetails.getClientKey() != null) && !oAuthAppDetails.getClientKey().isEmpty()) { DynamicClientWebAppRegistrationUtil.addClientCredentialsToWebContext(oAuthAppDetails, - servletContext); - log.info("Added OAuth application credentials to webapp context of webapp : " + webAppName); + servletContext); + log.info("Added OAuth application credentials to webapp context of webapp : " + + webAppName); } } } diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/JaggeryOAuthConfigurationSettings.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/JaggeryOAuthConfigurationSettings.java index 8b9849175c..32f8b9bcc9 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/JaggeryOAuthConfigurationSettings.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/JaggeryOAuthConfigurationSettings.java @@ -22,7 +22,7 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** - * Represents OAuthConfiguration data. + * Represents OAuthConfiguration data required to create OAuth service provider for Jaggery apps. */ @XmlRootElement(name = "OAuthSettings") public class JaggeryOAuthConfigurationSettings { diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/OAuthAppDetails.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/OAuthAppDetails.java index 9fc1b359e8..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/dto/OAuthAppDetails.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/dto/OAuthAppDetails.java @@ -22,7 +22,7 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** - * Represents an OAuth application with basic data. + * Represents an OAuth application with basic necessary data. */ @XmlRootElement(name = "OAuthAppDetails") public class OAuthAppDetails { diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/internal/DynamicClientWebAppRegistrationDataHolder.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/internal/DynamicClientWebAppRegistrationDataHolder.java index 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 8ecfc33b2d..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 @@ -58,114 +58,119 @@ import org.wso2.carbon.utils.ConfigurationContextService; */ public class DynamicClientWebAppRegistrationServiceComponent { - private ServiceTracker serviceTracker; - private static Log log = LogFactory.getLog(DynamicClientWebAppRegistrationServiceComponent.class); + private static Log log = + LogFactory.getLog(DynamicClientWebAppRegistrationServiceComponent.class); - @SuppressWarnings("unused") - protected void activate(ComponentContext componentContext) { + @SuppressWarnings("unused") + protected void activate(ComponentContext componentContext) { componentContext.getBundleContext().registerService(ServerStartupObserver.class.getName(), - new WebAppRegistrationServerStartupObserver(), null) ; - } + new WebAppRegistrationServerStartupObserver(), null); + } - @SuppressWarnings("unused") - protected void deactivate(ComponentContext componentContext) { + @SuppressWarnings("unused") + protected void deactivate(ComponentContext componentContext) { - } + } - /** - * Sets Realm Service. - * - * @param realmService An instance of RealmService - */ - protected void setRealmService(RealmService realmService) { - if (log.isDebugEnabled()) { - log.debug("Setting Realm Service"); - } - DynamicClientWebAppRegistrationDataHolder.getInstance().setRealmService(realmService); - } + /** + * Sets Realm Service. + * + * @param realmService An instance of RealmService + */ + protected void setRealmService(RealmService realmService) { + if (log.isDebugEnabled()) { + log.debug("Setting Realm Service"); + } + DynamicClientWebAppRegistrationDataHolder.getInstance().setRealmService(realmService); + } - /** - * Unsets Realm Service. - * - * @param realmService An instance of RealmService - */ - protected void unsetRealmService(RealmService realmService) { - if (log.isDebugEnabled()) { - log.debug("Unsetting Realm Service"); - } - DynamicClientWebAppRegistrationDataHolder.getInstance().setRealmService(null); - } + /** + * Unsets Realm Service. + * + * @param realmService An instance of RealmService + */ + protected void unsetRealmService(RealmService realmService) { + if (log.isDebugEnabled()) { + log.debug("Unsetting Realm Service"); + } + DynamicClientWebAppRegistrationDataHolder.getInstance().setRealmService(null); + } - /** - * Sets Registry Service. - * - * @param registryService An instance of RegistryService - */ - protected void setRegistryService(RegistryService registryService) { - if (log.isDebugEnabled()) { - log.debug("Setting Registry Service"); - } - DynamicClientWebAppRegistrationDataHolder.getInstance().setRegistryService(registryService); - } + /** + * Sets Registry Service. + * + * @param registryService An instance of RegistryService + */ + protected void setRegistryService(RegistryService registryService) { + if (log.isDebugEnabled()) { + log.debug("Setting Registry Service"); + } + DynamicClientWebAppRegistrationDataHolder.getInstance().setRegistryService(registryService); + } - /** - * Unsets Registry Service. - * - * @param registryService An instance of RegistryService - */ - protected void unsetRegistryService(RegistryService registryService) { - if (log.isDebugEnabled()) { - log.debug("Un setting Registry Service"); - } - DynamicClientWebAppRegistrationDataHolder.getInstance().setRegistryService(null); - } + /** + * Unsets Registry Service. + * + * @param registryService An instance of RegistryService + */ + protected void unsetRegistryService(RegistryService registryService) { + if (log.isDebugEnabled()) { + log.debug("Un setting Registry Service"); + } + DynamicClientWebAppRegistrationDataHolder.getInstance().setRegistryService(null); + } - /** - * Sets Dynamic Client Registration Service. - * - * @param dynamicClientRegistrationService An instance of DynamicClientRegistrationService - */ - protected void setDynamicClientService(DynamicClientRegistrationService dynamicClientRegistrationService) { - if (log.isDebugEnabled()) { - log.debug("Setting Dynamic Client Registration Service"); - } - DynamicClientWebAppRegistrationDataHolder.getInstance().setDynamicClientRegistrationService( - dynamicClientRegistrationService); - } + /** + * Sets Dynamic Client Registration Service. + * + * @param dynamicClientRegistrationService An instance of DynamicClientRegistrationService + */ + protected void setDynamicClientService( + DynamicClientRegistrationService dynamicClientRegistrationService) { + if (log.isDebugEnabled()) { + log.debug("Setting Dynamic Client Registration Service"); + } + DynamicClientWebAppRegistrationDataHolder.getInstance().setDynamicClientRegistrationService( + dynamicClientRegistrationService); + } - /** - * Unsets Dynamic Client Registration Service. - * - * @param dynamicClientRegistrationService An instance of DynamicClientRegistrationService - */ - protected void unsetDynamicClientService(DynamicClientRegistrationService dynamicClientRegistrationService) { - if (log.isDebugEnabled()) { - log.debug("Un setting Dynamic Client Registration Service"); - } - DynamicClientWebAppRegistrationDataHolder.getInstance().setDynamicClientRegistrationService(null); - } + /** + * Unsets Dynamic Client Registration Service. + * + * @param dynamicClientRegistrationService An instance of DynamicClientRegistrationService + */ + protected void unsetDynamicClientService( + DynamicClientRegistrationService dynamicClientRegistrationService) { + if (log.isDebugEnabled()) { + log.debug("Un setting Dynamic Client Registration Service"); + } + DynamicClientWebAppRegistrationDataHolder.getInstance().setDynamicClientRegistrationService(null); + } - /** - * Sets ConfigurationContext Service. - * - * @param configurationContextService An instance of ConfigurationContextService - */ - protected void setConfigurationContextService(ConfigurationContextService configurationContextService) { - if (log.isDebugEnabled()) { - log.debug("Setting ConfigurationContextService"); - } - DynamicClientWebAppRegistrationDataHolder.getInstance().setConfigurationContextService(configurationContextService); - } + /** + * Sets ConfigurationContext Service. + * + * @param configurationContextService An instance of ConfigurationContextService + */ + protected void setConfigurationContextService( + ConfigurationContextService configurationContextService) { + if (log.isDebugEnabled()) { + log.debug("Setting ConfigurationContextService"); + } + DynamicClientWebAppRegistrationDataHolder.getInstance().setConfigurationContextService( + configurationContextService); + } - /** - * Unsets ConfigurationContext Service. - * - * @param configurationContextService An instance of ConfigurationContextService - */ - protected void unsetConfigurationContextService(ConfigurationContextService configurationContextService) { - if (log.isDebugEnabled()) { - log.debug("Un-setting ConfigurationContextService"); - } - DynamicClientWebAppRegistrationDataHolder.getInstance().setConfigurationContextService(null); - } + /** + * Unsets ConfigurationContext Service. + * + * @param configurationContextService An instance of ConfigurationContextService + */ + protected void unsetConfigurationContextService( + ConfigurationContextService configurationContextService) { + if (log.isDebugEnabled()) { + log.debug("Un-setting ConfigurationContextService"); + } + DynamicClientWebAppRegistrationDataHolder.getInstance().setConfigurationContextService(null); + } } \ No newline at end of file diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/listner/DynamicClientWebAppDeploymentLifecycleListener.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/listner/DynamicClientWebAppDeploymentLifecycleListener.java index aeff85c2a6..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().saveServletContextToCache( - context); + DynamicClientWebAppRegistrationManager.getInstance().saveServletContextToCache(context); } } } diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java index 765b0191e3..5c826b338b 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java @@ -62,9 +62,8 @@ public class DynamicClientWebAppRegistrationUtil { public static Registry getGovernanceRegistry() throws DynamicClientRegistrationException { try { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - return DynamicClientWebAppRegistrationDataHolder.getInstance().getRegistryService() - .getGovernanceSystemRegistry( - tenantId); + return DynamicClientWebAppRegistrationDataHolder.getInstance().getRegistryService(). + getGovernanceSystemRegistry(tenantId); } catch (RegistryException e) { throw new DynamicClientRegistrationException( "Error in retrieving governance registry instance: " + @@ -75,8 +74,7 @@ public class DynamicClientWebAppRegistrationUtil { public static OAuthAppDetails getOAuthApplicationData(String appName) throws DynamicClientRegistrationException { Resource resource; - String resourcePath = - DynamicClientWebAppRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH + "/" + appName; + String resourcePath = DynamicClientWebAppRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH + "/" + appName; try { if (log.isDebugEnabled()) { log.debug("Retrieving OAuth application " + appName + " data from Registry"); @@ -86,9 +84,8 @@ public class DynamicClientWebAppRegistrationUtil { JAXBContext context = JAXBContext.newInstance(OAuthAppDetails.class); Unmarshaller unmarshaller = context.createUnmarshaller(); return (OAuthAppDetails) unmarshaller.unmarshal( - new StringReader(new String((byte[]) resource.getContent(), Charset - .forName( - DynamicClientWebAppRegistrationConstants.CharSets.CHARSET_UTF8)))); + new StringReader(new String((byte[]) resource.getContent(), Charset.forName( + DynamicClientWebAppRegistrationConstants.CharSets.CHARSET_UTF8)))); } return new OAuthAppDetails(); } catch (JAXBException e) { @@ -96,13 +93,12 @@ public class DynamicClientWebAppRegistrationUtil { "Error occurred while parsing the OAuth application data : " + appName, e); } catch (RegistryException e) { throw new DynamicClientRegistrationException( - "Error occurred while retrieving the Registry resource of OAuth application : " + - appName, e); + "Error occurred while retrieving the Registry resource of OAuth application : " + appName, e); } } - public static boolean putOAuthApplicationData(OAuthAppDetails oAuthAppDetails) - throws DynamicClientRegistrationException { + public static boolean putOAuthApplicationData(OAuthAppDetails oAuthAppDetails) throws + DynamicClientRegistrationException { boolean status; try { if (log.isDebugEnabled()) { @@ -113,15 +109,12 @@ public class DynamicClientWebAppRegistrationUtil { Marshaller marshaller = context.createMarshaller(); marshaller.marshal(oAuthAppDetails, writer); - Resource resource = - DynamicClientWebAppRegistrationUtil.getGovernanceRegistry().newResource(); + Resource resource = DynamicClientWebAppRegistrationUtil.getGovernanceRegistry().newResource(); resource.setContent(writer.toString()); resource.setMediaType(DynamicClientWebAppRegistrationConstants.ContentTypes.MEDIA_TYPE_XML); - String resourcePath = - DynamicClientWebAppRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH + "/" + + String resourcePath = DynamicClientWebAppRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH + "/" + oAuthAppDetails.getWebAppName(); - status = - DynamicClientWebAppRegistrationUtil.putRegistryResource(resourcePath, resource); + status = DynamicClientWebAppRegistrationUtil.putRegistryResource(resourcePath, resource); } catch (RegistryException e) { throw new DynamicClientRegistrationException( "Error occurred while persisting OAuth application data : " + @@ -134,53 +127,42 @@ public class DynamicClientWebAppRegistrationUtil { return status; } - public static boolean putRegistryResource(String path, - Resource resource) - throws DynamicClientRegistrationException { - boolean status; + public static boolean putRegistryResource(String path, Resource resource) throws DynamicClientRegistrationException { try { - Registry governanceRegistry = DynamicClientWebAppRegistrationUtil - .getGovernanceRegistry(); + Registry governanceRegistry = DynamicClientWebAppRegistrationUtil.getGovernanceRegistry(); governanceRegistry.beginTransaction(); governanceRegistry.put(path, resource); governanceRegistry.commitTransaction(); - status = true; + return true; } catch (RegistryException e) { - throw new DynamicClientRegistrationException( - "Error occurred while persisting registry resource : " + - e.getMessage(), e); + throw new DynamicClientRegistrationException("Error occurred while persisting registry resource : " + + e.getMessage(), e); } - return status; } - public static Resource getRegistryResource(String path) - throws DynamicClientRegistrationException { + public static Resource getRegistryResource(String path) throws DynamicClientRegistrationException { try { - Registry governanceRegistry = DynamicClientWebAppRegistrationUtil - .getGovernanceRegistry(); + Registry governanceRegistry = DynamicClientWebAppRegistrationUtil.getGovernanceRegistry(); if (governanceRegistry.resourceExists(path)) { return governanceRegistry.get(path); } return null; } catch (RegistryException e) { - throw new DynamicClientRegistrationException( - "Error in retrieving registry resource : " + - e.getMessage(), e); + throw new DynamicClientRegistrationException("Error in retrieving registry resource : " + + e.getMessage(), e); } } public static String getUserName() { String username = ""; - RealmService realmService = - DynamicClientWebAppRegistrationDataHolder.getInstance().getRealmService(); + RealmService realmService = DynamicClientWebAppRegistrationDataHolder.getInstance().getRealmService(); if (realmService != null) { username = realmService.getBootstrapRealmConfiguration().getAdminUserName(); } return username; } - public static RegistrationProfile constructRegistrationProfile(ServletContext servletContext, - String webAppName) { + public static RegistrationProfile constructRegistrationProfile(ServletContext servletContext, String webAppName) { RegistrationProfile registrationProfile; registrationProfile = new RegistrationProfile(); registrationProfile.setGrantType(servletContext.getInitParameter( @@ -193,18 +175,16 @@ public class DynamicClientWebAppRegistrationUtil { if ((callbackURL != null) && !callbackURL.isEmpty()) { registrationProfile.setCallbackUrl(callbackURL); } else { - registrationProfile.setCallbackUrl(DynamicClientWebAppRegistrationUtil.getCallbackUrl( - webAppName)); + registrationProfile.setCallbackUrl(DynamicClientWebAppRegistrationUtil.getCallbackUrl(webAppName)); } registrationProfile.setClientName(webAppName); registrationProfile.setSaasApp(Boolean.parseBoolean(servletContext.getInitParameter( DynamicClientWebAppRegistrationUtil.OAUTH_PARAM_SAAS_APP))); - return registrationProfile; } - public static RegistrationProfile constructRegistrationProfile( - JaggeryOAuthConfigurationSettings jaggeryOAuthConfigurationSettings, String webAppName) { + public static RegistrationProfile constructRegistrationProfile(JaggeryOAuthConfigurationSettings + jaggeryOAuthConfigurationSettings, String webAppName) { RegistrationProfile registrationProfile = new RegistrationProfile(); if (jaggeryOAuthConfigurationSettings != null) { registrationProfile.setGrantType(jaggeryOAuthConfigurationSettings.getGrantType()); @@ -215,18 +195,17 @@ public class DynamicClientWebAppRegistrationUtil { if (jaggeryOAuthConfigurationSettings.getCallbackURL() != null) { registrationProfile.setCallbackUrl(jaggeryOAuthConfigurationSettings.getCallbackURL()); } else { - registrationProfile.setCallbackUrl( - DynamicClientWebAppRegistrationUtil.getCallbackUrl(webAppName)); + registrationProfile.setCallbackUrl(DynamicClientWebAppRegistrationUtil.getCallbackUrl(webAppName)); } } else { - log.warn( - "Please configure OAuth settings properly for jaggery app : " + webAppName); + log.warn("Please configure OAuth settings properly for jaggery app : " + webAppName); } return registrationProfile; } public static boolean validateRegistrationProfile(RegistrationProfile registrationProfile) { boolean status = true; + //todo fix this if (registrationProfile.getGrantType() == null) { status = false; log.warn("Required parameter 'grantType' is missing for initiating Dynamic-Client " + @@ -241,14 +220,11 @@ public class DynamicClientWebAppRegistrationUtil { } public static JaggeryOAuthConfigurationSettings getJaggeryAppOAuthSettings(ServletContext servletContext) { - JaggeryOAuthConfigurationSettings - jaggeryOAuthConfigurationSettings = new JaggeryOAuthConfigurationSettings(); + JaggeryOAuthConfigurationSettings jaggeryOAuthConfigurationSettings = new JaggeryOAuthConfigurationSettings(); try { - InputStream inputStream = - servletContext.getResourceAsStream(JAGGERY_APP_OAUTH_CONFIG_PATH); + InputStream inputStream = servletContext.getResourceAsStream(JAGGERY_APP_OAUTH_CONFIG_PATH); if (inputStream != null) { - JsonReader reader = - new JsonReader(new InputStreamReader(inputStream, CHARSET_UTF_8)); + JsonReader reader = new JsonReader(new InputStreamReader(inputStream, CHARSET_UTF_8)); reader.beginObject(); while (reader.hasNext()) { String key = reader.nextName(); @@ -307,7 +283,7 @@ public class DynamicClientWebAppRegistrationUtil { public static void addClientCredentialsToWebContext(OAuthAppDetails oAuthAppDetails, ServletContext servletContext) { - if(oAuthAppDetails != null){ + if (oAuthAppDetails != null) { //Check for client credentials if ((oAuthAppDetails.getClientKey() != null && !oAuthAppDetails.getClientKey().isEmpty()) && (oAuthAppDetails.getClientSecret() != null && !oAuthAppDetails.getClientSecret().isEmpty())) { diff --git a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java index 39d62f0063..ba56143668 100644 --- a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java +++ b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java @@ -46,6 +46,7 @@ public class PermissionBasedScopeValidator extends OAuth2ScopeValidator { private PermissionMethod() { throw new AssertionError(); } + public static final String READ = "read"; public static final String WRITE = "write"; public static final String DELETE = "delete"; @@ -70,12 +71,13 @@ public class PermissionBasedScopeValidator extends OAuth2ScopeValidator { getPermissionManagerService(); try { Permission permission = permissionManagerService.getPermission(properties); - if((permission != null) && (accessTokenDO.getAuthzUser() != null)) { + if ((permission != null) && (accessTokenDO.getAuthzUser() != null)) { String username = accessTokenDO.getAuthzUser().getUserName(); UserRealm userRealm = CarbonContext.getThreadLocalCarbonContext().getUserRealm(); - if(userRealm != null && userRealm.getAuthorizationManager() != null){ - status = userRealm.getAuthorizationManager().isUserAuthorized(username, permission.getPath(), - PermissionMethod.READ); + if (userRealm != null && userRealm.getAuthorizationManager() != null) { + status = userRealm.getAuthorizationManager() + .isUserAuthorized(username, permission.getPath(), + PermissionMethod.READ); } } } catch (PermissionManagementException e) { diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationFrameworkUtil.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/AuthenticationFrameworkUtil.java index 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); } }