Fix access token validating issue

remotes/1725333865317989910/tmp_refs/heads/master
tcdlpds 1 year ago
parent da1f9d2437
commit 7e65d9f980

@ -127,7 +127,6 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
String validityTime, String password) String validityTime, String password)
throws APIManagerException { throws APIManagerException {
ApiApplicationInfo applicationInfo = getApplicationInfo(username, password); ApiApplicationInfo applicationInfo = getApplicationInfo(username, password);
TokenInfo tokenInfo = new TokenInfo(); TokenInfo tokenInfo = new TokenInfo();
tokenInfo.setApiApplicationInfo(applicationInfo); tokenInfo.setApiApplicationInfo(applicationInfo);
@ -162,8 +161,6 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application[] applications = io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application[] applications =
consumerRESTAPIServices.getAllApplications(tokenInfo, applicationName); 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) { if (applications.length == 0) {
return handleNewAPIApplication(applicationName, uniqueApiList, tokenInfo, keyType, return handleNewAPIApplication(applicationName, uniqueApiList, tokenInfo, keyType,
validityTime); validityTime);
@ -171,8 +168,10 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
if (applications.length == 1) { if (applications.length == 1) {
Optional<io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application> applicationOpt = Optional<io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application> applicationOpt =
Arrays.stream(applications).findFirst(); 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); Metadata metaData = metadataManagementService.retrieveMetadata(applicationName);
if (metaData == null) { if (metaData == null) {
// Todo add a comment // Todo add a comment
@ -183,7 +182,10 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
for (Subscription subscription : subscriptions) { for (Subscription subscription : subscriptions) {
uniqueApiList.removeIf(apiInfo -> Objects.equals(apiInfo.getId(), subscription.getApiInfo().getId())); uniqueApiList.removeIf(apiInfo -> Objects.equals(apiInfo.getId(), subscription.getApiInfo().getId()));
} }
if (!uniqueApiList.isEmpty()) {
addSubscriptions(application, uniqueApiList, tokenInfo); addSubscriptions(application, uniqueApiList, tokenInfo);
}
String[] metaValues = metaData.getMetaValue().split(":"); String[] metaValues = metaData.getMetaValue().split(":");
if (metaValues.length != 2) { if (metaValues.length != 2) {
@ -200,7 +202,6 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret()); apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret());
return apiApplicationKey; return apiApplicationKey;
} }
} else { } else {
String msg = "Found more than one application for application name: " + applicationName; String msg = "Found more than one application for application name: " + applicationName;
log.error(msg); log.error(msg);
@ -250,11 +251,11 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
throw new APIManagerException(msg); throw new APIManagerException(msg);
} }
ApiApplicationInfo applicationInfo = getApplicationInfo(null, null); tokenInfo.setApiApplicationInfo(getApplicationInfo(null, null));
tokenInfo.setApiApplicationInfo(applicationInfo); // ApplicationKey applicationKey = consumerRESTAPIServices.mapApplicationKeys(tokenInfo, application,
// keyManager.getName(), keyType);
ApplicationKey applicationKey = consumerRESTAPIServices.mapApplicationKeys(tokenInfo, application, ApplicationKey applicationKey = consumerRESTAPIServices.generateApplicationKeys(tokenInfo, application.getApplicationId(),
keyManager.getName(), keyType); keyManager.getName(), validityTime, keyType);
ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey()); apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey());
@ -294,13 +295,11 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
} }
/** /**
*
* This method can be used to add a new subscriptions providing the ids of the APIs and the applications. * 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 application {@link io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application}
* @param apiInfos {@link List<APIInfo>} * @param apiInfos {@link List<APIInfo>}
* @param tokenInfo {@link TokenInfo} * @param tokenInfo {@link TokenInfo}
*
* @throws BadRequestException if incorrect data provided to call subscribing REST API. * @throws BadRequestException if incorrect data provided to call subscribing REST API.
* @throws UnexpectedResponseException if error occurred while processing the 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.

@ -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.LoginCache;
import io.entgra.device.mgt.core.ui.request.interceptor.cache.OAuthApp; 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.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.HandlerConstants;
import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil; import io.entgra.device.mgt.core.ui.request.interceptor.util.HandlerUtil;
import org.apache.commons.lang.text.StrSubstitutor; import org.apache.commons.lang.text.StrSubstitutor;
@ -139,6 +140,8 @@ public class SsoLoginHandler extends HttpServlet {
log.error("Error while creating the document builder."); log.error("Error while creating the document builder.");
} catch (SAXException e) { } catch (SAXException e) {
log.error("Error while parsing xml file.", 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 req {@link HttpServletRequest}
* @param resp {@link HttpServletResponse} * @param resp {@link HttpServletResponse}
*/ */
private void dynamicClientRegistration(HttpServletRequest req, HttpServletResponse resp) { private void dynamicClientRegistration(HttpServletRequest req, HttpServletResponse resp) throws LoginException {
try { try {
JsonArray tags = uiConfigJsonObject.get("appRegistration").getAsJsonObject().get("tags").getAsJsonArray(); JsonArray tags = uiConfigJsonObject.get("appRegistration").getAsJsonObject().get("tags").getAsJsonArray();
JsonArray scopes = uiConfigJsonObject.get("scopes").getAsJsonArray(); JsonArray scopes = uiConfigJsonObject.get("scopes").getAsJsonArray();
@ -166,10 +169,6 @@ public class SsoLoginHandler extends HttpServlet {
ProxyResponse clientAppResponse = HandlerUtil.execute(apiRegEndpoint); ProxyResponse clientAppResponse = HandlerUtil.execute(apiRegEndpoint);
if (clientAppResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) {
HandlerUtil.handleError(resp, clientAppResponse);
}
if (clientAppResponse.getCode() == HttpStatus.SC_CREATED) { if (clientAppResponse.getCode() == HttpStatus.SC_CREATED) {
JsonParser jsonParser = new JsonParser(); JsonParser jsonParser = new JsonParser();
JsonElement jClientAppResult = jsonParser.parse(clientAppResponse.getData()); JsonElement jClientAppResult = jsonParser.parse(clientAppResponse.getData());
@ -188,71 +187,101 @@ public class SsoLoginHandler extends HttpServlet {
// cache the oauth app credentials // cache the oauth app credentials
oAuthApp = new OAuthApp(applicationName, adminUsername, clientId, clientSecret, encodedClientApp); oAuthApp = new OAuthApp(applicationName, adminUsername, clientId, clientSecret, encodedClientApp);
loginCache.addOAuthAppToCache(oAuthAppCacheKey, oAuthApp); 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 // Get the details of the registered application
String getApplicationEndpointUrl = apiMgtUrl + HandlerConstants.APIM_APPLICATIONS_ENDPOINT + // String getApplicationEndpointUrl = apiMgtUrl + HandlerConstants.APIM_APPLICATIONS_ENDPOINT +
"?query=" + applicationName; // "?query=" + applicationName;
HttpGet getApplicationEndpoint = new HttpGet(getApplicationEndpointUrl); // HttpGet getApplicationEndpoint = new HttpGet(getApplicationEndpointUrl);
getApplicationEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + // getApplicationEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER +
getAccessToken(resp, encodedClientApp)); // getAccessToken(resp, encodedClientApp));
//
ProxyResponse getApplicationResponse = HandlerUtil.execute(getApplicationEndpoint); // ProxyResponse getApplicationResponse = HandlerUtil.execute(getApplicationEndpoint);
//
if (getApplicationResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) { // if (getApplicationResponse.getCode() == HttpStatus.SC_OK) {
HandlerUtil.handleError(resp, getApplicationResponse); // JsonParser jsonParser = new JsonParser();
return; // JsonElement jAppResult = jsonParser.parse(getApplicationResponse.getData());
} // if (jAppResult.isJsonObject()) {
// JsonObject jClientAppResultAsJsonObject = jAppResult.getAsJsonObject();
if (getApplicationResponse.getCode() == HttpStatus.SC_OK) { // JsonArray appList = jClientAppResultAsJsonObject.getAsJsonArray("list");
JsonParser jsonParser = new JsonParser(); // JsonObject app;
JsonElement jAppResult = jsonParser.parse(getApplicationResponse.getData()); // for (JsonElement appJson : appList) {
if (jAppResult.isJsonObject()) { // app = appJson.getAsJsonObject();
JsonObject jClientAppResultAsJsonObject = jAppResult.getAsJsonObject(); // if (app.get("name").getAsString().equals(applicationName)) {
JsonArray appList = jClientAppResultAsJsonObject.getAsJsonArray("list"); // applicationId = app.get("applicationId").getAsString();
JsonObject app; // break;
for (JsonElement appJson : appList) { // }
app = appJson.getAsJsonObject(); // }
if (app.get("name").getAsString().equals(applicationName)) { // }
applicationId = app.get("applicationId").getAsString(); // } else if (getApplicationResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) {
break; // 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 // Update the grant types of the application
String url = apiMgtUrl + HandlerConstants.APIM_APPLICATIONS_ENDPOINT + "/" + applicationId + "/keys/" + // String url = apiMgtUrl + HandlerConstants.APIM_APPLICATIONS_ENDPOINT + "/" + applicationId + "/keys/" +
HandlerConstants.PRODUCTION_KEY; // HandlerConstants.PRODUCTION_KEY;
HttpPut updateApplicationGrantTypesEndpoint = new HttpPut(url); // HttpPut updateApplicationGrantTypesEndpoint = new HttpPut(url);
updateApplicationGrantTypesEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + // updateApplicationGrantTypesEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER +
getAccessToken(resp, encodedClientApp)); // getAccessToken(resp, encodedClientApp));
updateApplicationGrantTypesEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); // updateApplicationGrantTypesEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
updateApplicationGrantTypesEndpoint.setEntity(constructAppGrantTypeUpdatePayload()); // updateApplicationGrantTypesEndpoint.setEntity(constructAppGrantTypeUpdatePayload());
//
ProxyResponse updateApplicationGrantTypesEndpointResponse = HandlerUtil.execute(updateApplicationGrantTypesEndpoint); // ProxyResponse updateApplicationGrantTypesEndpointResponse = HandlerUtil.execute(updateApplicationGrantTypesEndpoint);
//
// Update app as a SaaS app // // Update app as a SaaS app
this.updateSaasApp(applicationId); // this.updateSaasApp(applicationId);
//
if (updateApplicationGrantTypesEndpointResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) { // if (updateApplicationGrantTypesEndpointResponse.getCode() == HttpStatus.SC_UNAUTHORIZED) {
HandlerUtil.handleError(resp, updateApplicationGrantTypesEndpointResponse); // String msg = "Unauthorized attempt to update the grant types of the application. " +
return; // "Application ID: " + applicationId + ". Response message: "
} // + updateApplicationGrantTypesEndpointResponse.getData();
// log.error(msg);
if (updateApplicationGrantTypesEndpointResponse.getCode() == HttpStatus.SC_OK) { // HandlerUtil.handleError(resp, updateApplicationGrantTypesEndpointResponse);
return; // throw new LoginException(msg);
} // } else if (updateApplicationGrantTypesEndpointResponse.getCode() != HttpStatus.SC_OK) {
HandlerUtil.handleError(resp, null); // 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) { } 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) { } catch (JsonSyntaxException e) {
log.error("Error occurred while parsing the response. ", e); throw new LoginException("Error occurred while parsing the response.", e);
} catch (ParserConfigurationException e) { }
log.error("Error while creating the document builder."); // catch (ParserConfigurationException e) {
} catch (SAXException e) { // throw new LoginException("Error while creating the document builder.", e);
log.error("Error while parsing xml file.", e); // }
} // catch (SAXException e) {
// throw new LoginException("Error while parsing xml file.", e);
// }
} }
/** /**

@ -73,7 +73,7 @@ public class UserHandler extends HttpServlet {
} }
String accessToken = authData.getAccessToken(); 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); HttpPost tokenEndpoint = new HttpPost(keymanagerUrl + HandlerConstants.INTROSPECT_ENDPOINT);
tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); tokenEndpoint.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString());
@ -82,7 +82,7 @@ public class UserHandler extends HttpServlet {
String adminPassword = dmc.getKeyManagerConfigurations().getAdminPassword(); String adminPassword = dmc.getKeyManagerConfigurations().getAdminPassword();
tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder() tokenEndpoint.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + Base64.getEncoder()
.encodeToString((adminUsername + HandlerConstants.COLON + adminPassword).getBytes())); .encodeToString((adminUsername + HandlerConstants.COLON + adminPassword).getBytes()));
StringEntity tokenEPPayload = new StringEntity("token=" + accessTokenWithoutPrefix, StringEntity tokenEPPayload = new StringEntity("token=" + accessToken,
ContentType.APPLICATION_FORM_URLENCODED); ContentType.APPLICATION_FORM_URLENCODED);
tokenEndpoint.setEntity(tokenEPPayload); tokenEndpoint.setEntity(tokenEPPayload);
ProxyResponse tokenStatus = HandlerUtil.execute(tokenEndpoint); ProxyResponse tokenStatus = HandlerUtil.execute(tokenEndpoint);

@ -74,7 +74,7 @@ public class OAuthAuthenticator implements WebappAuthenticator {
} }
try { try {
String bearerToken = getBearerToken(request); String bearerToken = getBearerToken(request);
bearerToken = bearerToken.substring(bearerToken.indexOf("_")+1); // bearerToken = bearerToken.substring(bearerToken.indexOf("_")+1);
String resource = requestUri + ":" + requestMethod; String resource = requestUri + ":" + requestMethod;
OAuthValidationResponse oAuthValidationResponse = this.tokenValidator.validateToken(bearerToken, resource); OAuthValidationResponse oAuthValidationResponse = this.tokenValidator.validateToken(bearerToken, resource);
authenticationInfo = Utils.setAuthenticationInfo(oAuthValidationResponse, authenticationInfo); authenticationInfo = Utils.setAuthenticationInfo(oAuthValidationResponse, authenticationInfo);

Loading…
Cancel
Save