From 7e65d9f9801dd792bfcc08437747ecd53c6c1868 Mon Sep 17 00:00:00 2001 From: tcdlpds Date: Tue, 12 Sep 2023 00:02:07 +0530 Subject: [PATCH] Fix access token validating issue --- .../APIManagementProviderServiceImpl.java | 61 ++++--- .../request/interceptor/SsoLoginHandler.java | 153 +++++++++++------- .../ui/request/interceptor/UserHandler.java | 4 +- .../authenticator/OAuthAuthenticator.java | 2 +- 4 files changed, 124 insertions(+), 96 deletions(-) diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderServiceImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderServiceImpl.java index 3a3bf5f941..f4bd1cb588 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderServiceImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.application.extension/src/main/java/io/entgra/device/mgt/core/apimgt/application/extension/APIManagementProviderServiceImpl.java @@ -111,13 +111,13 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe @Override public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String[] tags, - String keyType, - boolean isAllowedAllDomains, - String validityTime, String accessToken) throws APIManagerException { + String keyType, + boolean isAllowedAllDomains, + String validityTime, String accessToken) throws APIManagerException { TokenInfo tokenInfo = new TokenInfo(); tokenInfo.setApiApplicationInfo(null); tokenInfo.setAccessToken(accessToken); - return generateAndRetrieveApplicationKeys(applicationName, tags ,keyType, isAllowedAllDomains, validityTime, tokenInfo); + return generateAndRetrieveApplicationKeys(applicationName, tags, keyType, isAllowedAllDomains, validityTime, tokenInfo); } @Override @@ -127,12 +127,11 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe String validityTime, String password) throws APIManagerException { - ApiApplicationInfo applicationInfo = getApplicationInfo(username, password); TokenInfo tokenInfo = new TokenInfo(); tokenInfo.setApiApplicationInfo(applicationInfo); tokenInfo.setAccessToken(null); - return generateAndRetrieveApplicationKeys(applicationName, tags, keyType,isAllowedAllDomains, validityTime, tokenInfo); + return generateAndRetrieveApplicationKeys(applicationName, tags, keyType, isAllowedAllDomains, validityTime, tokenInfo); } private ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String[] tags, @@ -149,7 +148,7 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe headerParams.put("X-WSO2-Tenant", "carbon.super"); } - Map uniqueApiSet = new HashMap<>(); + Map uniqueApiSet = new HashMap<>(); for (String tag : tags) { Map queryParams = new HashMap<>(); queryParams.put("tag", tag); @@ -162,8 +161,6 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application[] applications = consumerRESTAPIServices.getAllApplications(tokenInfo, applicationName); - io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application; - MetadataManagementService metadataManagementService = APIApplicationManagerExtensionDataHolder.getInstance().getMetadataManagementService(); if (applications.length == 0) { return handleNewAPIApplication(applicationName, uniqueApiList, tokenInfo, keyType, validityTime); @@ -171,8 +168,10 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe if (applications.length == 1) { Optional applicationOpt = Arrays.stream(applications).findFirst(); - application = applicationOpt.get(); + io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application = + applicationOpt.get(); + MetadataManagementService metadataManagementService = APIApplicationManagerExtensionDataHolder.getInstance().getMetadataManagementService(); Metadata metaData = metadataManagementService.retrieveMetadata(applicationName); if (metaData == null) { // Todo add a comment @@ -183,7 +182,10 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe for (Subscription subscription : subscriptions) { uniqueApiList.removeIf(apiInfo -> Objects.equals(apiInfo.getId(), subscription.getApiInfo().getId())); } - addSubscriptions(application, uniqueApiList, tokenInfo); + + if (!uniqueApiList.isEmpty()) { + addSubscriptions(application, uniqueApiList, tokenInfo); + } String[] metaValues = metaData.getMetaValue().split(":"); if (metaValues.length != 2) { @@ -200,7 +202,6 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret()); return apiApplicationKey; } - } else { String msg = "Found more than one application for application name: " + applicationName; log.error(msg); @@ -250,11 +251,11 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe throw new APIManagerException(msg); } - ApiApplicationInfo applicationInfo = getApplicationInfo(null, null); - tokenInfo.setApiApplicationInfo(applicationInfo); - - ApplicationKey applicationKey = consumerRESTAPIServices.mapApplicationKeys(tokenInfo, application, - keyManager.getName(), keyType); + tokenInfo.setApiApplicationInfo(getApplicationInfo(null, null)); +// ApplicationKey applicationKey = consumerRESTAPIServices.mapApplicationKeys(tokenInfo, application, +// keyManager.getName(), keyType); + ApplicationKey applicationKey = consumerRESTAPIServices.generateApplicationKeys(tokenInfo, application.getApplicationId(), + keyManager.getName(), validityTime, keyType); ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey()); @@ -294,16 +295,14 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe } /** - * * This method can be used to add a new subscriptions providing the ids of the APIs and the applications. * * @param application {@link io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application} - * @param apiInfos {@link List} - * @param tokenInfo {@link TokenInfo} - * - * @throws BadRequestException if incorrect data provided to call subscribing REST API. + * @param apiInfos {@link List} + * @param tokenInfo {@link TokenInfo} + * @throws BadRequestException if incorrect data provided to call subscribing REST API. * @throws UnexpectedResponseException if error occurred while processing the subscribing REST API. - * @throws APIServicesException if error occurred while invoking the subscribing REST API. + * @throws APIServicesException if error occurred while invoking the subscribing REST API. */ private void addSubscriptions( io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application, @@ -323,7 +322,7 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe subscriptionList.add(subscription); }); - consumerRESTAPIServices.createSubscriptions(tokenInfo, subscriptionList); + consumerRESTAPIServices.createSubscriptions(tokenInfo, subscriptionList); } // /** @@ -557,7 +556,7 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe @Override public AccessTokenInfo getAccessToken(String scopes, String[] tags, String applicationName, String tokenType, - String validityPeriod, String username) throws APIManagerException { + String validityPeriod, String username) throws APIManagerException { try { String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true); ApiApplicationKey clientCredentials = getClientCredentials(tenantDomain, tags, applicationName, tokenType, @@ -605,17 +604,17 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe /** * Get Client credentials of application belongs to tenant admin * - * @param tenantDomain Tenant Domain - * @param tags Tags + * @param tenantDomain Tenant Domain + * @param tags Tags * @param applicationName Application Name - * @param tokenType Token Type - * @param validityPeriod Validity Period + * @param tokenType Token Type + * @param validityPeriod Validity Period * @return {@link ApiApplicationKey} * @throws APIManagerException if error occurred while generating access token - * @throws UserStoreException if error occurred while getting admin username. + * @throws UserStoreException if error occurred while getting admin username. */ private ApiApplicationKey getClientCredentials(String tenantDomain, String[] tags, String applicationName, - String tokenType, String validityPeriod) throws APIManagerException, UserStoreException { + String tokenType, String validityPeriod) throws APIManagerException, UserStoreException { APIRegistrationProfile registrationProfile = new APIRegistrationProfile(); registrationProfile.setAllowedToAllDomains(false); diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginHandler.java index 52dc03b79c..78a95c019f 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/SsoLoginHandler.java @@ -23,6 +23,7 @@ import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; import io.entgra.device.mgt.core.ui.request.interceptor.cache.LoginCache; import io.entgra.device.mgt.core.ui.request.interceptor.cache.OAuthApp; import io.entgra.device.mgt.core.ui.request.interceptor.cache.OAuthAppCacheKey; +import io.entgra.device.mgt.core.ui.request.interceptor.exceptions.LoginException; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerConstants; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import org.apache.commons.lang.text.StrSubstitutor; @@ -139,6 +140,8 @@ public class SsoLoginHandler extends HttpServlet { log.error("Error while creating the document builder."); } catch (SAXException e) { log.error("Error while parsing xml file.", e); + } catch (LoginException e) { + log.error("SSO Login is failed. Application: " + applicationName, e); } } @@ -149,7 +152,7 @@ public class SsoLoginHandler extends HttpServlet { * @param req {@link HttpServletRequest} * @param resp {@link HttpServletResponse} */ - private void dynamicClientRegistration(HttpServletRequest req, HttpServletResponse resp) { + private void dynamicClientRegistration(HttpServletRequest req, HttpServletResponse resp) throws LoginException { try { JsonArray tags = uiConfigJsonObject.get("appRegistration").getAsJsonObject().get("tags").getAsJsonArray(); JsonArray scopes = uiConfigJsonObject.get("scopes").getAsJsonArray(); @@ -166,10 +169,6 @@ public class SsoLoginHandler extends HttpServlet { ProxyResponse clientAppResponse = HandlerUtil.execute(apiRegEndpoint); - if (clientAppResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) { - HandlerUtil.handleError(resp, clientAppResponse); - } - if (clientAppResponse.getCode() == HttpStatus.SC_CREATED) { JsonParser jsonParser = new JsonParser(); JsonElement jClientAppResult = jsonParser.parse(clientAppResponse.getData()); @@ -188,71 +187,101 @@ public class SsoLoginHandler extends HttpServlet { // cache the oauth app credentials oAuthApp = new OAuthApp(applicationName, adminUsername, clientId, clientSecret, encodedClientApp); loginCache.addOAuthAppToCache(oAuthAppCacheKey, oAuthApp); + } else if (clientAppResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) { + String msg = "Unauthorized attempt to register the client application. " + + "Application Name: " + applicationName + ". Response message: " + clientAppResponse.getData(); + log.error(msg); + HandlerUtil.handleError(resp, clientAppResponse); + throw new LoginException(msg); + } else { + String msg = "Failed the process while registering the client application. " + + "Application Name: " + applicationName + ". Response Code: " + + clientAppResponse.getCode() + ", Response message: " + clientAppResponse.getData(); + log.error(msg); + HandlerUtil.handleError(resp, null); + throw new LoginException(msg); } // Get the details of the registered application - String getApplicationEndpointUrl = apiMgtUrl + HandlerConstants.APIM_APPLICATIONS_ENDPOINT + - "?query=" + applicationName; - HttpGet getApplicationEndpoint = new HttpGet(getApplicationEndpointUrl); - getApplicationEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + - getAccessToken(resp, encodedClientApp)); - - ProxyResponse getApplicationResponse = HandlerUtil.execute(getApplicationEndpoint); - - if (getApplicationResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) { - HandlerUtil.handleError(resp, getApplicationResponse); - return; - } - - if (getApplicationResponse.getCode() == HttpStatus.SC_OK) { - JsonParser jsonParser = new JsonParser(); - JsonElement jAppResult = jsonParser.parse(getApplicationResponse.getData()); - if (jAppResult.isJsonObject()) { - JsonObject jClientAppResultAsJsonObject = jAppResult.getAsJsonObject(); - JsonArray appList = jClientAppResultAsJsonObject.getAsJsonArray("list"); - JsonObject app; - for (JsonElement appJson : appList) { - app = appJson.getAsJsonObject(); - if (app.get("name").getAsString().equals(applicationName)) { - applicationId = app.get("applicationId").getAsString(); - break; - } - } - } - } +// String getApplicationEndpointUrl = apiMgtUrl + HandlerConstants.APIM_APPLICATIONS_ENDPOINT + +// "?query=" + applicationName; +// HttpGet getApplicationEndpoint = new HttpGet(getApplicationEndpointUrl); +// getApplicationEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + +// getAccessToken(resp, encodedClientApp)); +// +// ProxyResponse getApplicationResponse = HandlerUtil.execute(getApplicationEndpoint); +// +// if (getApplicationResponse.getCode() == HttpStatus.SC_OK) { +// JsonParser jsonParser = new JsonParser(); +// JsonElement jAppResult = jsonParser.parse(getApplicationResponse.getData()); +// if (jAppResult.isJsonObject()) { +// JsonObject jClientAppResultAsJsonObject = jAppResult.getAsJsonObject(); +// JsonArray appList = jClientAppResultAsJsonObject.getAsJsonArray("list"); +// JsonObject app; +// for (JsonElement appJson : appList) { +// app = appJson.getAsJsonObject(); +// if (app.get("name").getAsString().equals(applicationName)) { +// applicationId = app.get("applicationId").getAsString(); +// break; +// } +// } +// } +// } else if (getApplicationResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) { +// String msg = "Unauthorized attempt to get registered application data. " + +// "Application Name: " + applicationName + ". Response message: " + clientAppResponse.getData(); +// log.error(msg); +// HandlerUtil.handleError(resp, getApplicationResponse); +// throw new LoginException(msg); +// } else { +// String msg = "Failed the process while getting the data of registered application. " + +// "Application Name: " + applicationName + ". Response Code: " +// + clientAppResponse.getCode() + ", Response message: " + clientAppResponse.getData(); +// log.error(msg); +// HandlerUtil.handleError(resp, null); +// throw new LoginException(msg); +// } // Update the grant types of the application - String url = apiMgtUrl + HandlerConstants.APIM_APPLICATIONS_ENDPOINT + "/" + applicationId + "/keys/" + - HandlerConstants.PRODUCTION_KEY; - HttpPut updateApplicationGrantTypesEndpoint = new HttpPut(url); - updateApplicationGrantTypesEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + - getAccessToken(resp, encodedClientApp)); - updateApplicationGrantTypesEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); - updateApplicationGrantTypesEndpoint.setEntity(constructAppGrantTypeUpdatePayload()); - - ProxyResponse updateApplicationGrantTypesEndpointResponse = HandlerUtil.execute(updateApplicationGrantTypesEndpoint); - - // Update app as a SaaS app - this.updateSaasApp(applicationId); - - if (updateApplicationGrantTypesEndpointResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) { - HandlerUtil.handleError(resp, updateApplicationGrantTypesEndpointResponse); - return; - } - - if (updateApplicationGrantTypesEndpointResponse.getCode() == HttpStatus.SC_OK) { - return; - } - HandlerUtil.handleError(resp, null); +// String url = apiMgtUrl + HandlerConstants.APIM_APPLICATIONS_ENDPOINT + "/" + applicationId + "/keys/" + +// HandlerConstants.PRODUCTION_KEY; +// HttpPut updateApplicationGrantTypesEndpoint = new HttpPut(url); +// updateApplicationGrantTypesEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + +// getAccessToken(resp, encodedClientApp)); +// updateApplicationGrantTypesEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); +// updateApplicationGrantTypesEndpoint.setEntity(constructAppGrantTypeUpdatePayload()); +// +// ProxyResponse updateApplicationGrantTypesEndpointResponse = HandlerUtil.execute(updateApplicationGrantTypesEndpoint); +// +// // Update app as a SaaS app +// this.updateSaasApp(applicationId); +// +// if (updateApplicationGrantTypesEndpointResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) { +// String msg = "Unauthorized attempt to update the grant types of the application. " + +// "Application ID: " + applicationId + ". Response message: " +// + updateApplicationGrantTypesEndpointResponse.getData(); +// log.error(msg); +// HandlerUtil.handleError(resp, updateApplicationGrantTypesEndpointResponse); +// throw new LoginException(msg); +// } else if (updateApplicationGrantTypesEndpointResponse.getCode() != HttpStatus.SC_OK) { +// String msg = "Failed the process while updating the grant types of the application. " + +// "Application ID: " + applicationId + ". Response Code: " +// + updateApplicationGrantTypesEndpointResponse.getCode() + ", Response message: " +// + updateApplicationGrantTypesEndpointResponse.getData(); +// log.error(msg); +// HandlerUtil.handleError(resp, null); +// throw new LoginException(msg); +// } } catch (IOException e) { - log.error("Error occurred while sending the response into the socket. ", e); + throw new LoginException("Error occurred while sending the response into the socket.", e); } catch (JsonSyntaxException e) { - log.error("Error occurred while parsing the response. ", e); - } catch (ParserConfigurationException e) { - log.error("Error while creating the document builder."); - } catch (SAXException e) { - log.error("Error while parsing xml file.", e); + throw new LoginException("Error occurred while parsing the response.", e); } +// catch (ParserConfigurationException e) { +// throw new LoginException("Error while creating the document builder.", e); +// } +// catch (SAXException e) { +// throw new LoginException("Error while parsing xml file.", e); +// } } /** diff --git a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/UserHandler.java b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/UserHandler.java index c0f6c7f6ee..ac423d215c 100644 --- a/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/UserHandler.java +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/UserHandler.java @@ -73,7 +73,7 @@ public class UserHandler extends HttpServlet { } String accessToken = authData.getAccessToken(); - String accessTokenWithoutPrefix = accessToken.substring(accessToken.indexOf("_") + 1); +// String accessTokenWithoutPrefix = accessToken.substring(accessToken.indexOf("_") + 1); HttpPost tokenEndpoint = new HttpPost(keymanagerUrl + HandlerConstants.INTROSPECT_ENDPOINT); tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); @@ -82,7 +82,7 @@ public class UserHandler extends HttpServlet { String adminPassword = dmc.getKeyManagerConfigurations().getAdminPassword(); tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder() .encodeToString((adminUsername + HandlerConstants.COLON + adminPassword).getBytes())); - StringEntity tokenEPPayload = new StringEntity("token=" + accessTokenWithoutPrefix, + StringEntity tokenEPPayload = new StringEntity("token=" + accessToken, ContentType.APPLICATION_FORM_URLENCODED); tokenEndpoint.setEntity(tokenEPPayload); ProxyResponse tokenStatus = HandlerUtil.execute(tokenEndpoint); diff --git a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java index f973ae7dae..9678bff1eb 100644 --- a/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/io.entgra.device.mgt.core.webapp.authenticator.framework/src/main/java/io/entgra/device/mgt/core/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java @@ -74,7 +74,7 @@ public class OAuthAuthenticator implements WebappAuthenticator { } try { String bearerToken = getBearerToken(request); - bearerToken = bearerToken.substring(bearerToken.indexOf("_")+1); +// bearerToken = bearerToken.substring(bearerToken.indexOf("_")+1); String resource = requestUri + ":" + requestMethod; OAuthValidationResponse oAuthValidationResponse = this.tokenValidator.validateToken(bearerToken, resource); authenticationInfo = Utils.setAuthenticationInfo(oAuthValidationResponse, authenticationInfo);