diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServices.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServices.java deleted file mode 100644 index d628c4ce25..0000000000 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServices.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.extension.rest.api; - -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; - -public interface APIApplicationServices { - - APIApplicationKey createAndRetrieveApplicationCredentials() throws APIServicesException; - - AccessTokenInfo generateAccessTokenFromRegisteredApplication(String clientId, String clientSecret) throws APIServicesException; - - AccessTokenInfo generateAccessTokenFromRefreshToken(String refreshToken, String clientId, String clientSecret) throws APIServicesException; - -} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServicesImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServicesImpl.java deleted file mode 100644 index c412d189c0..0000000000 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/APIApplicationServicesImpl.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (c) 2018 - 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.extension.rest.api; - -import com.google.gson.Gson; -import org.json.JSONObject; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.HttpsTrustManagerUtils; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import okhttp3.RequestBody; -import okhttp3.Credentials; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.apimgt.impl.APIConstants; -import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; -import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; -import org.wso2.carbon.context.PrivilegedCarbonContext; - -import java.io.IOException; - -public class APIApplicationServicesImpl implements APIApplicationServices { - - private static final Log log = LogFactory.getLog(APIApplicationServicesImpl.class); - private static final OkHttpClient client = new OkHttpClient(HttpsTrustManagerUtils.getSSLClient().newBuilder()); - private static final Gson gson = new Gson(); - private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); - String msg = null; - APIManagerConfiguration config = ServiceReferenceHolder.getInstance(). - getAPIManagerConfigurationService().getAPIManagerConfiguration(); - - @Override - public APIApplicationKey createAndRetrieveApplicationCredentials() throws APIServicesException { - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - String serverUser = getScopePublishUserName(tenantDomain); - String serverPassword = getScopePublishUserPassword(tenantDomain); - - String applicationEndpoint = config.getFirstProperty(Constants.DCR_END_POINT); - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("callbackUrl", Constants.EMPTY_STRING); - jsonObject.put("clientName", Constants.CLIENT_NAME); - jsonObject.put("grantType", Constants.GRANT_TYPE); - jsonObject.put("owner", serverUser); - jsonObject.put("saasApp", true); - - RequestBody requestBody = RequestBody.Companion.create(jsonObject.toString(), JSON); - Request request = new Request.Builder() - .url(applicationEndpoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic(serverUser, serverPassword)) - .post(requestBody) - .build(); - - try { - try (Response response = client.newCall(request).execute()) { - return gson.fromJson(response.body().string(), APIApplicationKey.class); - } - } catch (IOException e) { - msg = "Error occurred while processing the response"; - log.error(msg, e); - throw new APIServicesException(e); - } - } - - @Override - public AccessTokenInfo generateAccessTokenFromRegisteredApplication(String consumerKey, String consumerSecret) - throws APIServicesException { - - String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - String userName = getScopePublishUserName(tenantDomain); - String userPassword = getScopePublishUserPassword(tenantDomain); - - JSONObject params = new JSONObject(); - params.put(Constants.GRANT_TYPE_PARAM_NAME, Constants.PASSWORD_GRANT_TYPE); - params.put(Constants.PASSWORD_GRANT_TYPE_USERNAME, userName); - params.put(Constants.PASSWORD_GRANT_TYPE_PASSWORD, userPassword); - params.put(Constants.SCOPE_PARAM_NAME, Constants.SCOPES); - return getToken(params, consumerKey, consumerSecret); - } - - @Override - public AccessTokenInfo generateAccessTokenFromRefreshToken(String refreshToken, String consumerKey, - String consumerSecret) throws APIServicesException { - JSONObject params = new JSONObject(); - params.put(Constants.GRANT_TYPE_PARAM_NAME, Constants.REFRESH_TOKEN_GRANT_TYPE); - params.put(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME, refreshToken); - params.put(Constants.SCOPE_PARAM_NAME, Constants.SCOPES); - return getToken(params, consumerKey, consumerSecret); - } - - public AccessTokenInfo getToken(JSONObject nameValuePairs, String clientId, String clientSecret) - throws APIServicesException { - - String tokenEndPoint = config.getFirstProperty(Constants.TOKE_END_POINT); - - RequestBody requestBody = RequestBody.Companion.create(nameValuePairs.toString(), JSON); - Request request = new Request.Builder() - .url(tokenEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic(clientId, clientSecret)) - .post(requestBody) - .build(); - - try { - Response response = client.newCall(request).execute(); - return gson.fromJson(response.body().string(), AccessTokenInfo.class); - } catch (IOException e) { - msg = "Error occurred while processing the response"; - log.error(msg, e); - throw new APIServicesException(e); - } - } - - private String getScopePublishUserName(String tenantDomain) { - if(APIConstants.SUPER_TENANT_DOMAIN.equals(tenantDomain)) { - return config.getFirstProperty(Constants.SERVER_USER); - } else { - return Constants.SCOPE_PUBLISH_RESERVED_USER_NAME + "@" + tenantDomain; - } - } - - private String getScopePublishUserPassword(String tenantDomain) { - if(APIConstants.SUPER_TENANT_DOMAIN.equals(tenantDomain)) { - return config.getFirstProperty(Constants.SERVER_PASSWORD); - } else { - return Constants.SCOPE_PUBLISH_RESERVED_USER_PASSWORD; - } - } -} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java index a263ad2d63..1d15c9f9d8 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServices.java @@ -18,98 +18,77 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.*; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; -import org.json.JSONObject; import java.util.List; public interface PublisherRESTAPIServices { - Scope[] getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + Scope[] getScopes() throws APIServicesException, BadRequestException, UnexpectedResponseException; - boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean isSharedScopeNameExists(String key) throws APIServicesException, BadRequestException, + UnexpectedResponseException; - boolean addNewSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean addNewSharedScope(Scope scope) throws APIServicesException, BadRequestException, + UnexpectedResponseException; - boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean updateSharedScope(Scope scope) throws APIServicesException, BadRequestException, + UnexpectedResponseException; - boolean deleteSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean deleteSharedScope(Scope scope) throws APIServicesException, BadRequestException, + UnexpectedResponseException; - APIInfo getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String apiUuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + APIInfo getApi(String apiUuid) throws APIServicesException, BadRequestException, UnexpectedResponseException; - APIInfo[] getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + APIInfo[] getApis() throws APIServicesException, BadRequestException, UnexpectedResponseException; - APIInfo addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + APIInfo addAPI(APIInfo api) throws APIServicesException, BadRequestException, UnexpectedResponseException; - boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean updateApi(APIInfo api) throws APIServicesException, BadRequestException, UnexpectedResponseException; - boolean saveAsyncApiDefinition(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, - String asyncApiDefinition) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean saveAsyncApiDefinition(String uuid, String asyncApiDefinition) throws APIServicesException, + BadRequestException, UnexpectedResponseException; - MediationPolicy[] getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String apiUuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + MediationPolicy[] getAllApiSpecificMediationPolicies(String apiUuid) throws APIServicesException, + BadRequestException, UnexpectedResponseException; - boolean addApiSpecificMediationPolicy(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, Mediation mediation) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean addApiSpecificMediationPolicy(String uuid, Mediation mediation) throws APIServicesException, + BadRequestException, UnexpectedResponseException; - boolean deleteApiSpecificMediationPolicy(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, Mediation mediation) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean deleteApiSpecificMediationPolicy(String uuid, Mediation mediation) throws APIServicesException, + BadRequestException, UnexpectedResponseException; - boolean changeLifeCycleStatus(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, String action) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean changeLifeCycleStatus(String uuid, String action) throws APIServicesException, BadRequestException, + UnexpectedResponseException; - APIRevision[] getAPIRevisions(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, - Boolean deploymentStatus) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + APIRevision[] getAPIRevisions(String uuid, Boolean deploymentStatus) throws APIServicesException, + BadRequestException, UnexpectedResponseException; - APIRevision addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIRevision apiRevision) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + APIRevision addAPIRevision(APIRevision apiRevision) throws APIServicesException, BadRequestException, + UnexpectedResponseException; - boolean deployAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, - String apiRevisionId, List apiRevisionDeploymentList) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean deployAPIRevision(String uuid, String apiRevisionId, + List apiRevisionDeploymentList) throws APIServicesException, + BadRequestException, UnexpectedResponseException; - boolean undeployAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIRevision apiRevisionDeployment, String uuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean undeployAPIRevisionDeployment(APIRevision apiRevisionDeployment, String uuid) throws APIServicesException + , BadRequestException, UnexpectedResponseException; - boolean deleteAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIRevision apiRevision, String uuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean deleteAPIRevision(APIRevision apiRevision, String uuid) throws APIServicesException, BadRequestException, + UnexpectedResponseException; - Documentation[] getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + Documentation[] getDocumentations(String uuid) throws APIServicesException, BadRequestException, + UnexpectedResponseException; - boolean deleteDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, String documentID) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean deleteDocumentations(String uuid, String documentID) throws APIServicesException, BadRequestException, + UnexpectedResponseException; - Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, Documentation documentation) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + Documentation addDocumentation(String uuid, Documentation documentation) throws APIServicesException, + BadRequestException, UnexpectedResponseException; - boolean addDocumentationContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String apiUuid, String docId, String docContent) - throws APIServicesException, BadRequestException, UnexpectedResponseException; + boolean addDocumentationContent(String apiUuid, String docId, String docContent) throws APIServicesException, + BadRequestException, UnexpectedResponseException; } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java index e322ae0307..acc042d1e5 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/PublisherRESTAPIServicesImpl.java @@ -19,16 +19,19 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api; import com.google.gson.Gson; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.PublisherRESTAPIClientResponse; import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.*; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.PublisherRESTAPIOauthClientException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.HttpsTrustManagerUtils; -import okhttp3.*; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.util.PublisherRESTAPIOauthClient; +import okhttp3.MediaType; +import okhttp3.MultipartBody; +import okhttp3.Request; import okhttp3.Request.Builder; +import okhttp3.RequestBody; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -36,12 +39,10 @@ import org.apache.commons.ssl.Base64; import org.json.JSONArray; import org.json.JSONObject; -import java.io.IOException; import java.util.List; public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { private static final Log log = LogFactory.getLog(PublisherRESTAPIServicesImpl.class); - private static final OkHttpClient client = new OkHttpClient(HttpsTrustManagerUtils.getSSLClient().newBuilder()); private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); private static final Gson gson = new Gson(); private static final String host = System.getProperty(Constants.IOT_CORE_HOST); @@ -50,48 +51,26 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { + Constants.COLON + port; @Override - public Scope[] getScopes(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) - throws APIServicesException, BadRequestException, UnexpectedResponseException { - + public Scope[] getScopes() throws APIServicesException, BadRequestException, UnexpectedResponseException { String getAllScopesUrl = endPointPrefix + Constants.GET_ALL_SCOPES; Request request = new Request.Builder() .url(getAllScopesUrl) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .get() .build(); - try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - JSONArray scopeList = (JSONArray) new JSONObject(response.body().string()).get("list"); - return gson.fromJson(scopeList.toString(), Scope[].class); - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return getScopes(apiApplicationKey, refreshedAccessToken); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + JSONArray scopeList = (JSONArray) new JSONObject(response.getBody()).get("list"); + return gson.fromJson(scopeList.toString(), Scope[].class); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while retrieving scopes"; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public boolean isSharedScopeNameExists(String key) throws APIServicesException, BadRequestException, + UnexpectedResponseException { String keyValue = new String(Base64.encodeBase64((key).getBytes())).replace(Constants.QUERY_KEY_VALUE_SEPARATOR, Constants.EMPTY_STRING); @@ -99,46 +78,21 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { Request request = new Request.Builder() .url(getScopeUrl) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .head() .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return isSharedScopeNameExists(apiApplicationKey, refreshedAccessToken, key); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request"; - log.error(msg); - throw new BadRequestException(msg); - } else if (HttpStatus.SC_NOT_FOUND == response.code()) { - String msg = "Shared scope key not found : " + key; - if (log.isDebugEnabled()) { - log.debug(msg); - } - return false; - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while checking if shared scope exists for the key : " + key; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean addNewSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public boolean addNewSharedScope(Scope scope) throws APIServicesException, BadRequestException, + UnexpectedResponseException { String addNewSharedScopeEndPoint = endPointPrefix + Constants.SCOPE_API_ENDPOINT; @@ -159,41 +113,22 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { RequestBody requestBody = RequestBody.create(JSON, payload.toString()); Request request = new Request.Builder() .url(addNewSharedScopeEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .post(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return addNewSharedScope(apiApplicationKey, refreshedAccessToken, scope); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid scope object"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.message(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_CREATED == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while adding new shared scope for scope name : " + scope.getName(); log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public boolean updateSharedScope(Scope scope) throws APIServicesException, BadRequestException, + UnexpectedResponseException { String updateScopeUrl = endPointPrefix + Constants.SCOPE_API_ENDPOINT + scope.getId(); @@ -214,41 +149,22 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { RequestBody requestBody = RequestBody.create(JSON, payload.toString()); Request request = new Request.Builder() .url(updateScopeUrl) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .put(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return updateSharedScope(apiApplicationKey, refreshedAccessToken, scope); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid scope object"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while updating shared scope for scope name : " + scope.getName(); log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean deleteSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public boolean deleteSharedScope(Scope scope) throws APIServicesException, BadRequestException, + UnexpectedResponseException { String updateScopeUrl = endPointPrefix + Constants.SCOPE_API_ENDPOINT + scope.getId(); JSONArray bindings = new JSONArray(); @@ -268,120 +184,60 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { RequestBody requestBody = RequestBody.create(JSON, payload.toString()); Request request = new Request.Builder() .url(updateScopeUrl) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .delete(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return deleteSharedScope(apiApplicationKey, refreshedAccessToken, scope); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid scope object"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while deleting shared scope for scope name : " + scope.getName(); log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public APIInfo getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String apiUuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public APIInfo getApi(String apiUuid) throws APIServicesException, BadRequestException, + UnexpectedResponseException { String getAllApi = endPointPrefix + Constants.API_ENDPOINT + apiUuid; Request request = new Request.Builder() .url(getAllApi) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .get() .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - return gson.fromJson(response.body().string(), APIInfo.class); - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return getApi(apiApplicationKey, refreshedAccessToken, apiUuid); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return gson.fromJson(response.getBody(), APIInfo.class); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while retrieving API for API UUID : " + apiUuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public APIInfo[] getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) - throws APIServicesException, BadRequestException, UnexpectedResponseException { - + public APIInfo[] getApis() throws APIServicesException, BadRequestException, UnexpectedResponseException { String getAllApis = endPointPrefix + Constants.GET_ALL_APIS; Request request = new Request.Builder() .url(getAllApis) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .get() .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - JSONArray apiList = (JSONArray) new JSONObject(response.body().string()).get("list"); - return gson.fromJson(apiList.toString(), APIInfo[].class); - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return getApis(apiApplicationKey, refreshedAccessToken); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + JSONArray apiList = (JSONArray) new JSONObject(response.getBody()).get("list"); + return gson.fromJson(apiList.toString(), APIInfo[].class); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while retrieving APIs"; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public APIInfo addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public APIInfo addAPI(APIInfo api) throws APIServicesException, BadRequestException, UnexpectedResponseException { String addAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT; @@ -406,7 +262,8 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { payload.put("apiThrottlingPolicy", api.getApiThrottlingPolicy()); payload.put("authorizationHeader", api.getAuthorizationHeader()); payload.put("visibility", api.getVisibility()); - payload.put("subscriptionAvailability", (api.getSubscriptionAvailability() != null ? api.getSubscriptionAvailability() : "")); + payload.put("subscriptionAvailability", (api.getSubscriptionAvailability() != null ? + api.getSubscriptionAvailability() : "")); //Lists if (api.getTransport() != null) { @@ -474,54 +331,42 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } //objects - payload.put("monetization", (api.getMonetization() != null ? new JSONObject(gson.toJson(api.getMonetization())) : null)); - payload.put("corsConfiguration", (api.getCorsConfiguration() != null ? new JSONObject(gson.toJson(api.getCorsConfiguration())) : null)); - payload.put("websubSubscriptionConfiguration", (api.getWebsubSubscriptionConfiguration() != null ? new JSONObject(gson.toJson(api.getWebsubSubscriptionConfiguration())) : null)); + payload.put("monetization", (api.getMonetization() != null ? + new JSONObject(gson.toJson(api.getMonetization())) : null)); + payload.put("corsConfiguration", (api.getCorsConfiguration() != null ? + new JSONObject(gson.toJson(api.getCorsConfiguration())) : null)); + payload.put("websubSubscriptionConfiguration", (api.getWebsubSubscriptionConfiguration() != null ? + new JSONObject(gson.toJson(api.getWebsubSubscriptionConfiguration())) : null)); payload.put("workflowStatus", (api.getWorkflowStatus() != null ? api.getWorkflowStatus() : null)); payload.put("endpointConfig", (api.getEndpointConfig() != null ? api.getEndpointConfig() : null)); - payload.put("endpointImplementationType", (api.getEndpointImplementationType() != null ? api.getEndpointImplementationType() : null)); - payload.put("threatProtectionPolicies", (api.getThreatProtectionPolicies() != null ? api.getThreatProtectionPolicies() : null)); - payload.put("serviceInfo", (api.getServiceInfo() != null ? new JSONObject(gson.toJson(api.getServiceInfo())) : null)); - payload.put("advertiseInfo", (api.getAdvertiseInfo() != null ? new JSONObject(gson.toJson(api.getAdvertiseInfo())) : null)); + payload.put("endpointImplementationType", (api.getEndpointImplementationType() != null ? + api.getEndpointImplementationType() : null)); + payload.put("threatProtectionPolicies", (api.getThreatProtectionPolicies() != null ? + api.getThreatProtectionPolicies() : null)); + payload.put("serviceInfo", (api.getServiceInfo() != null ? new JSONObject(gson.toJson(api.getServiceInfo())) + : null)); + payload.put("advertiseInfo", (api.getAdvertiseInfo() != null ? + new JSONObject(gson.toJson(api.getAdvertiseInfo())) : null)); RequestBody requestBody = RequestBody.create(JSON, payload.toString()); Request request = new Request.Builder() .url(addAPIEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .post(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { - return gson.fromJson(response.body().string(), APIInfo.class); - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return addAPI(apiApplicationKey, refreshedAccessToken, api); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid API request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response status : " + response.code() + " Response message : " + response.message(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return gson.fromJson(response.getBody(), APIInfo.class); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while adding API for API name : " + api.getName(); log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public boolean updateApi(APIInfo api) throws APIServicesException, BadRequestException, + UnexpectedResponseException { String updateAPIEndPoint = endPointPrefix + Constants.API_ENDPOINT + api.getId(); @@ -546,7 +391,8 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { payload.put("apiThrottlingPolicy", api.getApiThrottlingPolicy()); payload.put("authorizationHeader", api.getAuthorizationHeader()); payload.put("visibility", api.getVisibility()); - payload.put("subscriptionAvailability", (api.getSubscriptionAvailability() != null ? api.getSubscriptionAvailability() : "")); + payload.put("subscriptionAvailability", (api.getSubscriptionAvailability() != null ? + api.getSubscriptionAvailability() : "")); //Lists if (api.getTransport() != null) { @@ -614,55 +460,42 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } //objects - payload.put("monetization", (api.getMonetization() != null ? new JSONObject(gson.toJson(api.getMonetization())) : null)); - payload.put("corsConfiguration", (api.getCorsConfiguration() != null ? new JSONObject(gson.toJson(api.getCorsConfiguration())) : null)); - payload.put("websubSubscriptionConfiguration", (api.getWebsubSubscriptionConfiguration() != null ? new JSONObject(gson.toJson(api.getWebsubSubscriptionConfiguration())) : null)); + payload.put("monetization", (api.getMonetization() != null ? + new JSONObject(gson.toJson(api.getMonetization())) : null)); + payload.put("corsConfiguration", (api.getCorsConfiguration() != null ? + new JSONObject(gson.toJson(api.getCorsConfiguration())) : null)); + payload.put("websubSubscriptionConfiguration", (api.getWebsubSubscriptionConfiguration() != null ? + new JSONObject(gson.toJson(api.getWebsubSubscriptionConfiguration())) : null)); payload.put("workflowStatus", (api.getWorkflowStatus() != null ? api.getWorkflowStatus() : null)); payload.put("endpointConfig", (api.getEndpointConfig() != null ? api.getEndpointConfig() : null)); - payload.put("endpointImplementationType", (api.getEndpointImplementationType() != null ? api.getEndpointImplementationType() : null)); - payload.put("threatProtectionPolicies", (api.getThreatProtectionPolicies() != null ? api.getThreatProtectionPolicies() : null)); - payload.put("serviceInfo", (api.getServiceInfo() != null ? new JSONObject(gson.toJson(api.getServiceInfo())) : null)); - payload.put("advertiseInfo", (api.getAdvertiseInfo() != null ? new JSONObject(gson.toJson(api.getAdvertiseInfo())) : null)); + payload.put("endpointImplementationType", (api.getEndpointImplementationType() != null ? + api.getEndpointImplementationType() : null)); + payload.put("threatProtectionPolicies", (api.getThreatProtectionPolicies() != null ? + api.getThreatProtectionPolicies() : null)); + payload.put("serviceInfo", (api.getServiceInfo() != null ? new JSONObject(gson.toJson(api.getServiceInfo())) + : null)); + payload.put("advertiseInfo", (api.getAdvertiseInfo() != null ? + new JSONObject(gson.toJson(api.getAdvertiseInfo())) : null)); RequestBody requestBody = RequestBody.create(JSON, payload.toString()); Request request = new Request.Builder() .url(updateAPIEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .put(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return updateApi(apiApplicationKey, refreshedAccessToken, api); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid API request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while updating API for API name : " + api.getName(); log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean saveAsyncApiDefinition(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, String asyncApiDefinition) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public boolean saveAsyncApiDefinition(String uuid, String asyncApiDefinition) throws APIServicesException, + BadRequestException, UnexpectedResponseException { String saveAsyncAPI = endPointPrefix + Constants.API_ENDPOINT + uuid + "/asyncapi"; @@ -674,33 +507,14 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { Request request = new Request.Builder() .url(saveAsyncAPI) .addHeader(Constants.HEADER_CONTENT_TYPE, "multipart/form-data") - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .put(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { //Check the response - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return saveAsyncApiDefinition(apiApplicationKey, refreshedAccessToken, uuid, asyncApiDefinition); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid API definition request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while saving async API definition for API UUID : " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } @@ -708,49 +522,27 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } @Override - public MediationPolicy[] getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String apiUuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException { - + public MediationPolicy[] getAllApiSpecificMediationPolicies(String apiUuid) throws APIServicesException, + BadRequestException, UnexpectedResponseException { String getAPIMediationEndPoint = endPointPrefix + Constants.API_ENDPOINT + apiUuid + "/mediation-policies"; Request request = new Request.Builder() .url(getAPIMediationEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .get() .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - JSONArray mediationPolicyList = (JSONArray) new JSONObject(response.body().string()).get("list"); - return gson.fromJson(mediationPolicyList.toString(), MediationPolicy[].class); - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return getAllApiSpecificMediationPolicies(apiApplicationKey, refreshedAccessToken, apiUuid); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + JSONArray mediationPolicyList = (JSONArray) new JSONObject(response.getBody()).get("list"); + return gson.fromJson(mediationPolicyList.toString(), MediationPolicy[].class); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while retrieving all mediation policies for API UUID : " + apiUuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean addApiSpecificMediationPolicy(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, Mediation mediation) + public boolean addApiSpecificMediationPolicy(String uuid, Mediation mediation) throws APIServicesException, BadRequestException, UnexpectedResponseException { String addAPIMediation = endPointPrefix + Constants.API_ENDPOINT + uuid + "/mediation-policies"; @@ -764,33 +556,14 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { Request request = new Builder() .url(addAPIMediation) .addHeader(Constants.HEADER_CONTENT_TYPE, "multipart/form-data") - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .post(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { // Check response status - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return addApiSpecificMediationPolicy(apiApplicationKey, refreshedAccessToken, uuid, mediation); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_CREATED == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while adding API specific mediation policy for API UUID : " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } @@ -798,41 +571,22 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } @Override - public boolean deleteApiSpecificMediationPolicy(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, Mediation mediation) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public boolean deleteApiSpecificMediationPolicy(String uuid, Mediation mediation) throws APIServicesException, + BadRequestException, UnexpectedResponseException { - String deleteApiMediationEndPOint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/mediation-policies/" + mediation.getUuid(); + String deleteApiMediationEndPOint = + endPointPrefix + Constants.API_ENDPOINT + uuid + "/mediation-policies/" + mediation.getUuid(); Request request = new Request.Builder() .url(deleteApiMediationEndPOint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .delete() .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_NO_CONTENT == response.code()) { // Check response status - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return deleteApiSpecificMediationPolicy(apiApplicationKey, refreshedAccessToken, uuid, mediation); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid mediation policy"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_NO_CONTENT == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while deleting mediation policy from API UUID : " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } @@ -840,8 +594,7 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { } @Override - public boolean changeLifeCycleStatus(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, String action) + public boolean changeLifeCycleStatus(String uuid, String action) throws APIServicesException, BadRequestException, UnexpectedResponseException { String changeAPIStatusEndPoint = endPointPrefix + Constants.API_ENDPOINT + "change-lifecycle?apiId=" + uuid @@ -850,41 +603,21 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { RequestBody requestBody = RequestBody.create(JSON, Constants.EMPTY_STRING); Request request = new Request.Builder() .url(changeAPIStatusEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .post(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return changeLifeCycleStatus(apiApplicationKey, refreshedAccessToken, uuid, action); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while changing life cycle state for API UUID : " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public APIRevision[] getAPIRevisions(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, - Boolean deploymentStatus) + public APIRevision[] getAPIRevisions(String uuid, Boolean deploymentStatus) throws APIServicesException, BadRequestException, UnexpectedResponseException { String getAPIRevisionsEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/revisions?query=deployed:" @@ -892,42 +625,23 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { Request request = new Request.Builder() .url(getAPIRevisionsEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .get() .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - JSONArray revisionList = (JSONArray) new JSONObject(response.body().string()).get("list"); - return gson.fromJson(revisionList.toString(), APIRevision[].class); - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return getAPIRevisions(apiApplicationKey, refreshedAccessToken, uuid, deploymentStatus); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + JSONArray revisionList = (JSONArray) new JSONObject(response.getBody()).get("list"); + return gson.fromJson(revisionList.toString(), APIRevision[].class); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while retrieving API revisions for API UUID : " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public APIRevision addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIRevision apiRevision) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public APIRevision addAPIRevision(APIRevision apiRevision) throws APIServicesException, BadRequestException, + UnexpectedResponseException { String addNewScope = endPointPrefix + Constants.API_ENDPOINT + apiRevision.getApiUUID() + "/revisions"; @@ -937,44 +651,26 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { RequestBody requestBody = RequestBody.create(JSON, payload.toString()); Request request = new Request.Builder() .url(addNewScope) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .post(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { - return gson.fromJson(response.body().string(), APIRevision.class); - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return addAPIRevision(apiApplicationKey, refreshedAccessToken, apiRevision); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid API revision request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return gson.fromJson(response.getBody(), APIRevision.class); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while adding API revision for API UUID : " + apiRevision.getApiUUID(); log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean deployAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid, - String apiRevisionId, List apiRevisionDeploymentList) + public boolean deployAPIRevision(String uuid, String apiRevisionId, + List apiRevisionDeploymentList) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String deployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/deploy-revision?revisionId=" + apiRevisionId; + String deployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/deploy-revision" + + "?revisionId=" + apiRevisionId; APIRevisionDeployment apiRevisionDeployment = apiRevisionDeploymentList.get(0); JSONArray payload = new JSONArray(); @@ -987,45 +683,25 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { RequestBody requestBody = RequestBody.create(JSON, payload.toString()); Request request = new Request.Builder() .url(deployAPIRevisionEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .post(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return deployAPIRevision(apiApplicationKey, refreshedAccessToken, uuid, apiRevisionId, - apiRevisionDeploymentList); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid API revision request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while deploying API revision for API UUID + " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean undeployAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIRevision apiRevisionDeployment, String uuid) + public boolean undeployAPIRevisionDeployment(APIRevision apiRevisionDeployment, String uuid) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String undeployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/undeploy-revision?revisionId=" + String undeployAPIRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/undeploy-revision" + + "?revisionId=" + apiRevisionDeployment.getId(); List apiRevisionDeployments = apiRevisionDeployment.getDeploymentInfo(); APIRevisionDeployment earliestDeployment = apiRevisionDeployments.get(0); @@ -1040,165 +716,86 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { RequestBody requestBody = RequestBody.create(JSON, payload.toString()); Request request = new Request.Builder() .url(undeployAPIRevisionEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .post(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return undeployAPIRevisionDeployment(apiApplicationKey, refreshedAccessToken, apiRevisionDeployment, uuid); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid API revision request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while undeploy an API revision from API UUID : " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean deleteAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - APIRevision apiRevision, String uuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public boolean deleteAPIRevision(APIRevision apiRevision, String uuid) throws APIServicesException, + BadRequestException, UnexpectedResponseException { String apiRevisionEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/revisions/" + apiRevision.getId(); Request request = new Request.Builder() .url(apiRevisionEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .delete() .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return deleteAPIRevision(apiApplicationKey, refreshedAccessToken, apiRevision, uuid); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while deleting an API revision from API UUID : " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public Documentation[] getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid) - throws APIServicesException, BadRequestException, UnexpectedResponseException { + public Documentation[] getDocumentations(String uuid) throws APIServicesException, BadRequestException, + UnexpectedResponseException { String getDocumentationsEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/documents?limit=1000"; Request request = new Request.Builder() .url(getDocumentationsEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .get() .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - JSONArray documentList = (JSONArray) new JSONObject(response.body().string()).get("list"); - return gson.fromJson(documentList.toString(), Documentation[].class); - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return getDocumentations(apiApplicationKey, refreshedAccessToken, uuid); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + JSONArray documentList = (JSONArray) new JSONObject(response.getBody()).get("list"); + return gson.fromJson(documentList.toString(), Documentation[].class); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while retrieving documentation for API UUID " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean deleteDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, String documentID) + public boolean deleteDocumentations(String uuid, String documentID) throws APIServicesException, BadRequestException, UnexpectedResponseException { String getDocumentationsEndPoint = endPointPrefix + Constants.API_ENDPOINT + uuid + "/documents/" + documentID; Request request = new Request.Builder() .url(getDocumentationsEndPoint) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .delete() .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_OK == response.code()) { - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return deleteDocumentations(apiApplicationKey, refreshedAccessToken, uuid, documentID); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_OK == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while deleting documentation for API UUID : " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String uuid, Documentation documentation) + public Documentation addDocumentation(String uuid, Documentation documentation) throws APIServicesException, BadRequestException, UnexpectedResponseException { String addNewScope = endPointPrefix + Constants.API_ENDPOINT + uuid + "/documents"; @@ -1216,44 +813,25 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { Request request = new Request.Builder() .url(addNewScope) .addHeader(Constants.HEADER_CONTENT_TYPE, Constants.APPLICATION_JSON) - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .post(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { // Check response status - return gson.fromJson(response.body().string(), Documentation.class); - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return addDocumentation(apiApplicationKey, refreshedAccessToken, uuid, documentation); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid documentation request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return gson.fromJson(response.getBody(), Documentation.class); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while adding documentation for API UUID " + uuid; log.error(msg, e); throw new APIServicesException(msg, e); } } @Override - public boolean addDocumentationContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - String apiUuid, String docId, String docContent) + public boolean addDocumentationContent(String apiUuid, String docId, String docContent) throws APIServicesException, BadRequestException, UnexpectedResponseException { - String addDocumentationContentEndPoint = endPointPrefix + Constants.API_ENDPOINT + apiUuid + "/documents/" + docId + "/content"; + String addDocumentationContentEndPoint = + endPointPrefix + Constants.API_ENDPOINT + apiUuid + "/documents/" + docId + "/content"; RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) @@ -1263,33 +841,14 @@ public class PublisherRESTAPIServicesImpl implements PublisherRESTAPIServices { Request request = new Request.Builder() .url(addDocumentationContentEndPoint) .addHeader(Constants.HEADER_CONTENT_TYPE, "multipart/form-data") - .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Constants.AUTHORIZATION_HEADER_PREFIX_BEARER - + accessTokenInfo.getAccess_token()) .post(requestBody) .build(); try { - Response response = client.newCall(request).execute(); - if (HttpStatus.SC_CREATED == response.code()) { // Check response status - return true; - } else if (HttpStatus.SC_UNAUTHORIZED == response.code()) { - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - AccessTokenInfo refreshedAccessToken = apiApplicationServices. - generateAccessTokenFromRefreshToken(accessTokenInfo.getRefresh_token(), - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - //TODO: max attempt count - return addDocumentationContent(apiApplicationKey, refreshedAccessToken, apiUuid, docId, docContent); - } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { - String msg = "Bad Request, Invalid documentation request body"; - log.error(msg); - throw new BadRequestException(msg); - } else { - String msg = "Response : " + response.code() + response.body(); - log.error(msg); - throw new UnexpectedResponseException(msg); - } - } catch (IOException e) { - String msg = "Error occurred while processing the response"; + PublisherRESTAPIClientResponse response = PublisherRESTAPIOauthClient.execute(request); + return HttpStatus.SC_CREATED == response.getCode(); + } catch (PublisherRESTAPIOauthClientException e) { + String msg = "Error occurred while adding documentation for API UUID : " + apiUuid; log.error(msg, e); throw new APIServicesException(msg, e); } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/PublisherOauthApp.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/PublisherOauthApp.java new file mode 100644 index 0000000000..d8605f411d --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/PublisherOauthApp.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.bean; + +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; + +public class PublisherOauthApp { + private final APIApplicationKey apiApplicationKey; + private final AccessTokenInfo accessTokenInfo; + + public PublisherOauthApp(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) { + this.apiApplicationKey = apiApplicationKey; + this.accessTokenInfo = accessTokenInfo; + } + + public AccessTokenInfo getAccessTokenInfo() { + return accessTokenInfo; + } + + public APIApplicationKey getApiApplicationKey() { + return apiApplicationKey; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/PublisherRESTAPIClientResponse.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/PublisherRESTAPIClientResponse.java new file mode 100644 index 0000000000..148d59b95a --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/bean/PublisherRESTAPIClientResponse.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.bean; + +public class PublisherRESTAPIClientResponse { + private final int code; + private final String body; + private final boolean isSuccessful; + + public PublisherRESTAPIClientResponse(int code, String body, boolean isSuccessful) { + this.code = code; + this.body = body; + this.isSuccessful = isSuccessful; + } + + public int getCode() { + return code; + } + + public String getBody() { + return body; + } + + public boolean isSuccessful() { + return isSuccessful; + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/exceptions/PublisherRESTAPIOauthClientException.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/exceptions/PublisherRESTAPIOauthClientException.java new file mode 100644 index 0000000000..1ded2c4b80 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/exceptions/PublisherRESTAPIOauthClientException.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions; + +public class PublisherRESTAPIOauthClientException extends Exception { + private static final long serialVersionUID = -896103750774855894L; + + public PublisherRESTAPIOauthClientException(String errorMessage) { + super(errorMessage); + } + + public PublisherRESTAPIOauthClientException(String errorMessage, Throwable t) { + super(errorMessage, t); + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceComponent.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceComponent.java index fef16ea6ee..bdb0ef44af 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceComponent.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceComponent.java @@ -18,8 +18,6 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api.internal; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServicesImpl; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServicesImpl; import org.apache.commons.logging.Log; @@ -48,11 +46,6 @@ public class APIManagerServiceComponent { } try { BundleContext bundleContext = componentContext.getBundleContext(); - - APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl(); - bundleContext.registerService(APIApplicationServices.class.getName(), apiApplicationServices, null); - APIManagerServiceDataHolder.getInstance().setApiApplicationServices(apiApplicationServices); - PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServicesImpl(); bundleContext.registerService(PublisherRESTAPIServices.class.getName(), publisherRESTAPIServices, null); APIManagerServiceDataHolder.getInstance().setPublisherRESTAPIServices(publisherRESTAPIServices); diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceDataHolder.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceDataHolder.java index deeeaa2a06..2b021476e4 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceDataHolder.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/internal/APIManagerServiceDataHolder.java @@ -18,15 +18,12 @@ package io.entgra.device.mgt.core.apimgt.extension.rest.api.internal; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.tenant.TenantManager; public class APIManagerServiceDataHolder { - - private APIApplicationServices apiApplicationServices; private APIManagerConfigurationService apiManagerConfigurationService; private PublisherRESTAPIServices publisherRESTAPIServices; private RealmService realmService; @@ -37,18 +34,10 @@ public class APIManagerServiceDataHolder { private APIManagerServiceDataHolder() { } - static APIManagerServiceDataHolder getInstance() { + public static APIManagerServiceDataHolder getInstance() { return thisInstance; } - public APIApplicationServices getApiApplicationServices() { - return apiApplicationServices; - } - - public void setApiApplicationServices(APIApplicationServices apiApplicationServices) { - this.apiApplicationServices = apiApplicationServices; - } - public void setAPIManagerConfiguration(APIManagerConfigurationService apiManagerConfigurationService) { this.apiManagerConfigurationService = apiManagerConfigurationService; } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/util/PublisherRESTAPIOauthClient.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/util/PublisherRESTAPIOauthClient.java new file mode 100644 index 0000000000..ec38de5689 --- /dev/null +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.extension.rest.api/src/main/java/io/entgra/device/mgt/core/apimgt/extension/rest/api/util/PublisherRESTAPIOauthClient.java @@ -0,0 +1,242 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.extension.rest.api.util; + +import com.google.gson.Gson; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.PublisherOauthApp; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.PublisherRESTAPIClientResponse; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.PublisherRESTAPIOauthClientException; +import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; +import okhttp3.Credentials; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONObject; +import org.wso2.carbon.apimgt.impl.APIConstants; +import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; +import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; +import org.wso2.carbon.context.PrivilegedCarbonContext; + +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public class PublisherRESTAPIOauthClient { + private static final Log log = LogFactory.getLog(PublisherRESTAPIOauthClient.class); + private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); + private static final Gson gson = new Gson(); + private static final OkHttpClient client = new OkHttpClient(HttpsTrustManagerUtils.getSSLClient().newBuilder()); + private static final Map publisherOauthAppCache = new ConcurrentHashMap<>(); + private static final APIManagerConfiguration config = ServiceReferenceHolder.getInstance(). + getAPIManagerConfigurationService().getAPIManagerConfiguration(); + private static final int MAX_RETRY_ATTEMPT = 2; + + public static PublisherRESTAPIClientResponse execute(Request request) throws PublisherRESTAPIOauthClientException + , BadRequestException, + UnexpectedResponseException { + int currentRetryAttempt = 0; + PublisherRESTAPIClientResponse publisherRESTAPIClientResponse; + + while (true) { + try { + request = addAuthorizationHeader(request); + try (Response response = client.newCall(request).execute()) { + if (response.isSuccessful()) { + publisherRESTAPIClientResponse = map(response); + break; + } + + if (response.code() == HttpStatus.SC_NOT_FOUND) { + if (log.isDebugEnabled()) { + log.info("Resource not found for the request [ " + request.url() + " ]"); + } + publisherRESTAPIClientResponse = map(response); + break; + } + + // entering to the retrying phase, so increment the counter + currentRetryAttempt++; + if (response.code() == HttpStatus.SC_UNAUTHORIZED) { + if (currentRetryAttempt <= MAX_RETRY_ATTEMPT) { + updateCacheWithNewToken(); + } else { + String msg = + "Request [ " + request.url() + " ] failed with code : [ " + response.code() + " ]" + + " & body : [ " + (response.body() != null ? + response.body().string() : " empty body received!") + " ]"; + log.error(msg); + throw new UnexpectedResponseException(msg); + } + } else if (HttpStatus.SC_BAD_REQUEST == response.code()) { + String msg = + "Encountered a bad request! Request [ " + request.url() + " ] failed with code : " + + "[ " + response.code() + " ] & body : [ " + (response.body() != null ? + response.body().string() : " empty body received!") + " ]"; + log.error(msg); + throw new BadRequestException(msg); + } else { + String msg = + "Request [ " + request.url() + " ]failed with code : [ " + response.code() + " ] & " + + "body : [ " + (response.body() != null ? response.body().string() : " empty " + + "body received!") + " ]"; + log.error(msg); + throw new UnexpectedResponseException(msg); + } + } + } catch (IOException ex) { + String msg = + "Error occurred while executing the request : [ " + request.method() + ":" + request.url() + + " ]"; + throw new PublisherRESTAPIOauthClientException(msg, ex); + } + } + return publisherRESTAPIClientResponse; + } + + private static APIApplicationKey createOauthApplication() throws IOException { + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + String serverUser = getScopePublishUserName(tenantDomain); + String serverPassword = getScopePublishUserPassword(tenantDomain); + String applicationEndpoint = config.getFirstProperty(Constants.DCR_END_POINT); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("callbackUrl", Constants.EMPTY_STRING); + jsonObject.put("clientName", Constants.CLIENT_NAME + "_for_" + tenantDomain); + jsonObject.put("grantType", Constants.GRANT_TYPE); + jsonObject.put("owner", serverUser); + jsonObject.put("saasApp", true); + + RequestBody requestBody = RequestBody.Companion.create(jsonObject.toString(), JSON); + Request request = new Request.Builder() + .url(applicationEndpoint) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, Credentials.basic(serverUser, serverPassword)) + .post(requestBody) + .build(); + + try (Response response = client.newCall(request).execute()) { + return gson.fromJson(response.body() != null ? response.body().string() : null, APIApplicationKey.class); + } + } + + private static AccessTokenInfo getAccessToken() throws IOException { + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + APIApplicationKey apiApplicationKey = createOauthApplication(); + String userName = getScopePublishUserName(tenantDomain); + String userPassword = getScopePublishUserPassword(tenantDomain); + + JSONObject params = new JSONObject(); + params.put(Constants.GRANT_TYPE_PARAM_NAME, Constants.PASSWORD_GRANT_TYPE); + params.put(Constants.PASSWORD_GRANT_TYPE_USERNAME, userName); + params.put(Constants.PASSWORD_GRANT_TYPE_PASSWORD, userPassword); + params.put(Constants.SCOPE_PARAM_NAME, Constants.SCOPES); + return getToken(params, apiApplicationKey); + } + + public static void updateCacheWithNewToken() throws IOException { + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + publisherOauthAppCache.computeIfPresent(tenantDomain, (key, value) -> { + PublisherOauthApp publisherOauthApp = value; + try { + APIApplicationKey apiApplicationKey = value.getApiApplicationKey(); + JSONObject params = new JSONObject(); + params.put(Constants.GRANT_TYPE_PARAM_NAME, Constants.REFRESH_TOKEN_GRANT_TYPE); + params.put(Constants.REFRESH_TOKEN_GRANT_TYPE_PARAM_NAME, + value.getAccessTokenInfo().getRefresh_token()); + params.put(Constants.SCOPE_PARAM_NAME, Constants.SCOPES); + AccessTokenInfo accessTokenInfo = getToken(params, apiApplicationKey); + publisherOauthApp = new PublisherOauthApp(apiApplicationKey, accessTokenInfo); + } catch (IOException e) { + log.error("Error encountered while creating publisher OAuth application", e); + } + return publisherOauthApp; + }); + } + + private static AccessTokenInfo getToken(JSONObject params, APIApplicationKey apiApplicationKey) throws IOException { + String tokenEndPoint = config.getFirstProperty(Constants.TOKE_END_POINT); + RequestBody requestBody = RequestBody.Companion.create(params.toString(), JSON); + Request request = new Request.Builder() + .url(tokenEndPoint) + .addHeader(Constants.AUTHORIZATION_HEADER_NAME, + Credentials.basic(apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret())) + .post(requestBody) + .build(); + try (Response response = client.newCall(request).execute()) { + return gson.fromJson(response.body() != null ? response.body().string() : null, AccessTokenInfo.class); + } + } + + private static PublisherOauthApp getOauthApp() { + String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + return publisherOauthAppCache.computeIfAbsent(tenantDomain, key -> { + PublisherOauthApp publisherOauthApp = null; + try { + APIApplicationKey apiApplicationKey = createOauthApplication(); + AccessTokenInfo accessTokenInfo = getAccessToken(); + publisherOauthApp = new PublisherOauthApp(apiApplicationKey, accessTokenInfo); + } catch (IOException e) { + log.error("Error encountered while creating publisher OAuth application", e); + } + return publisherOauthApp; + }); + } + + private static Request addAuthorizationHeader(Request request) throws IOException { + return request.newBuilder().addHeader(Constants.AUTHORIZATION_HEADER_NAME, + Constants.AUTHORIZATION_HEADER_PREFIX_BEARER + getOauthApp().getAccessTokenInfo(). + getAccess_token()).build(); + } + + private static String getScopePublishUserName(String tenantDomain) throws IOException { + if (APIConstants.SUPER_TENANT_DOMAIN.equals(tenantDomain)) { + return config.getFirstProperty(Constants.SERVER_USER); + } else { + try { + APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); + } catch (APIServicesException e) { + throw new IOException("Failed to create user for api publishing in sub tenant : " + tenantDomain); + } + return Constants.SCOPE_PUBLISH_RESERVED_USER_NAME + "@" + tenantDomain; + } + } + + private static String getScopePublishUserPassword(String tenantDomain) { + if (APIConstants.SUPER_TENANT_DOMAIN.equals(tenantDomain)) { + return config.getFirstProperty(Constants.SERVER_PASSWORD); + } else { + return Constants.SCOPE_PUBLISH_RESERVED_USER_PASSWORD; + } + } + + private static PublisherRESTAPIClientResponse map(Response response) throws IOException { + return new PublisherRESTAPIClientResponse(response.code(), + response.body() != null ? response.body().string() : null, response.isSuccessful()); + } +} diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java index cab16f8482..ceb255b678 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/APIPublisherServiceImpl.java @@ -18,10 +18,8 @@ package io.entgra.device.mgt.core.apimgt.webapp.publisher; import com.google.gson.Gson; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevision; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIRevisionDeployment; @@ -31,7 +29,6 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Mediation import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.MediationPolicy; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Operations; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Scope; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; @@ -68,8 +65,6 @@ import org.wso2.carbon.user.core.tenant.Tenant; import org.wso2.carbon.user.core.tenant.TenantSearchResult; import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; -import io.entgra.device.mgt.core.device.mgt.core.permission.mgt.PermissionUtils; import io.entgra.device.mgt.core.device.mgt.common.permission.mgt.PermissionManagementException; import java.io.BufferedReader; @@ -117,11 +112,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { tenants.addAll(config.getTenants().getTenant()); RealmService realmService = (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext() .getOSGiService(RealmService.class, null); - - APIApplicationServices apiApplicationServices = APIPublisherDataHolder.getInstance().getApiApplicationServices(); PublisherRESTAPIServices publisherRESTAPIServices = APIPublisherDataHolder.getInstance().getPublisherRESTAPIServices(); - APIApplicationKey apiApplicationKey; - AccessTokenInfo accessTokenInfo; try { boolean tenantFound = false; @@ -156,17 +147,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(apiConfig.getOwner()); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - try { - APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); - apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); - accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - } catch (APIServicesException e) { - String errorMsg = "Error occurred while generating the API application"; - log.error(errorMsg, e); - throw new APIManagerPublisherException(e); - } - try { apiConfig.setOwner(APIUtil.getTenantAdminUserName(tenantDomain)); apiConfig.setTenantDomain(tenantDomain); @@ -174,7 +154,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(apiConfig.getOwner()), apiConfig.getName(), apiConfig.getVersion()); - APIInfo[] apiList = publisherRESTAPIServices.getApis(apiApplicationKey, accessTokenInfo); + APIInfo[] apiList = publisherRESTAPIServices.getApis(); boolean apiFound = false; for (int i = 0; i < apiList.length; i++) { APIInfo apiObj = apiList[i]; @@ -189,8 +169,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { if (!apiFound) { // add new scopes as shared scopes for (ApiScope apiScope : apiConfig.getScopes()) { - if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, - apiScope.getKey())) { + if (!publisherRESTAPIServices.isSharedScopeNameExists(apiScope.getKey())) { Scope scope = new Scope(); scope.setDisplayName(apiScope.getName()); scope.setDescription(apiScope.getDescription()); @@ -198,15 +177,14 @@ public class APIPublisherServiceImpl implements APIPublisherService { List bindings = new ArrayList<>(apiScope.getRoles()); bindings.add(ADMIN_ROLE_KEY); scope.setBindings(bindings); - publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); + publisherRESTAPIServices.addNewSharedScope(scope); } } APIInfo api = getAPI(apiConfig, true); - APIInfo createdAPI = publisherRESTAPIServices.addAPI(apiApplicationKey, accessTokenInfo, api); + APIInfo createdAPI = publisherRESTAPIServices.addAPI(api); apiUuid = createdAPI.getId(); if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) { - publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo, - apiUuid, apiConfig.getAsyncApiDefinition()); + publisherRESTAPIServices.saveAsyncApiDefinition(apiUuid, apiConfig.getAsyncApiDefinition()); } if (CREATED_STATUS.equals(createdAPI.getLifeCycleStatus())) { // if endpoint type "dynamic" and then add in sequence @@ -216,17 +194,14 @@ public class APIPublisherServiceImpl implements APIPublisherService { mediation.setConfig(apiConfig.getInSequenceConfig()); mediation.setType("in"); mediation.setGlobal(false); - publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey, - accessTokenInfo, apiUuid, mediation); + publisherRESTAPIServices.addApiSpecificMediationPolicy(apiUuid, mediation); } - publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey, accessTokenInfo, - apiUuid, PUBLISH_ACTION); + publisherRESTAPIServices.changeLifeCycleStatus(apiUuid, PUBLISH_ACTION); APIRevision apiRevision = new APIRevision(); apiRevision.setApiUUID(apiUuid); apiRevision.setDescription("Initial Revision"); - String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey, - accessTokenInfo, apiRevision).getId(); + String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiRevision).getId(); APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment(); apiRevisionDeployment.setName(API_PUBLISH_ENVIRONMENT); @@ -235,8 +210,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { List apiRevisionDeploymentList = new ArrayList<>(); apiRevisionDeploymentList.add(apiRevisionDeployment); - publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo, - apiUuid, apiRevisionId, apiRevisionDeploymentList); + publisherRESTAPIServices.deployAPIRevision(apiUuid, apiRevisionId, apiRevisionDeploymentList); } } else { if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) { @@ -259,8 +233,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { for (ApiScope apiScope : apiConfig.getScopes()) { // if the scope is not available as shared scope, and it is assigned to an API as a local scope // need remove the local scope and add as a shared scope - if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, - apiScope.getKey())) { + if (!publisherRESTAPIServices.isSharedScopeNameExists(apiScope.getKey())) { if (apiProvider.isScopeKeyAssignedLocally(apiIdentifier, apiScope.getKey(), tenantId)) { // collect scope to move as shared scopes scopesToMoveAsSharedScopes.add(apiScope); @@ -273,20 +246,19 @@ public class APIPublisherServiceImpl implements APIPublisherService { List bindings = new ArrayList<>(apiScope.getRoles()); bindings.add(ADMIN_ROLE_KEY); scope.setBindings(bindings); - publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); + publisherRESTAPIServices.addNewSharedScope(scope); } } } // Get existing API - APIInfo existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, - apiUuid); + APIInfo existingAPI = publisherRESTAPIServices.getApi(apiUuid); if (scopesToMoveAsSharedScopes.size() > 0) { // update API to remove local scopes APIInfo api = getAPI(apiConfig, false); api.setLifeCycleStatus(existingAPI.getLifeCycleStatus()); - publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api); + publisherRESTAPIServices.updateApi(api); for (ApiScope apiScope : scopesToMoveAsSharedScopes) { Scope scope = new Scope(); @@ -296,19 +268,18 @@ public class APIPublisherServiceImpl implements APIPublisherService { List bindings = new ArrayList<>(apiScope.getRoles()); bindings.add(ADMIN_ROLE_KEY); scope.setBindings(bindings); - publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); + publisherRESTAPIServices.addNewSharedScope(scope); } } - existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, apiUuid); + existingAPI = publisherRESTAPIServices.getApi(apiUuid); APIInfo api = getAPI(apiConfig, true); api.setLifeCycleStatus(existingAPI.getLifeCycleStatus()); api.setId(apiUuid); - publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api); + publisherRESTAPIServices.updateApi(api); if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) { - publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo, - apiUuid, apiConfig.getAsyncApiDefinition()); + publisherRESTAPIServices.saveAsyncApiDefinition(apiUuid, apiConfig.getAsyncApiDefinition()); } // if endpoint type "dynamic" and then add /update in sequence @@ -320,45 +291,37 @@ public class APIPublisherServiceImpl implements APIPublisherService { mediation.setGlobal(false); MediationPolicy[] mediationList = publisherRESTAPIServices - .getAllApiSpecificMediationPolicies(apiApplicationKey, accessTokenInfo, apiUuid); + .getAllApiSpecificMediationPolicies(apiUuid); boolean isMediationPolicyFound = false; for (int i = 0; i < mediationList.length; i++) { MediationPolicy mediationPolicy = mediationList[i]; if (apiConfig.getInSequenceName().equals(mediationPolicy.getName())) { mediation.setUuid(mediationPolicy.getId()); - publisherRESTAPIServices.deleteApiSpecificMediationPolicy(apiApplicationKey, - accessTokenInfo, apiUuid, mediation); - publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey, - accessTokenInfo, apiUuid, mediation); + publisherRESTAPIServices.deleteApiSpecificMediationPolicy(apiUuid, mediation); + publisherRESTAPIServices.addApiSpecificMediationPolicy(apiUuid, mediation); isMediationPolicyFound = true; break; } } if (!isMediationPolicyFound) { - publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey, - accessTokenInfo, apiUuid, mediation); + publisherRESTAPIServices.addApiSpecificMediationPolicy(apiUuid, mediation); } } - int apiRevisionCount = publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, - accessTokenInfo, apiUuid, null).length; + int apiRevisionCount = publisherRESTAPIServices.getAPIRevisions(apiUuid, null).length; if (apiRevisionCount >= 5) { // This will retrieve the deployed revision - APIRevision[] revisionDeploymentList = publisherRESTAPIServices.getAPIRevisions( - apiApplicationKey, accessTokenInfo, apiUuid, true); + APIRevision[] revisionDeploymentList = publisherRESTAPIServices.getAPIRevisions(apiUuid, true); if (revisionDeploymentList.length > 0) { APIRevision latestRevisionDeployment = revisionDeploymentList[0]; - publisherRESTAPIServices.undeployAPIRevisionDeployment(apiApplicationKey, - accessTokenInfo, latestRevisionDeployment, apiUuid); + publisherRESTAPIServices.undeployAPIRevisionDeployment(latestRevisionDeployment, apiUuid); } // This will retrieve the undeployed revision list - APIRevision[] undeployedRevisionList = publisherRESTAPIServices.getAPIRevisions(apiApplicationKey, - accessTokenInfo, apiUuid, false); + APIRevision[] undeployedRevisionList = publisherRESTAPIServices.getAPIRevisions(apiUuid, false); if (undeployedRevisionList.length > 0) { APIRevision earliestUndeployRevision = undeployedRevisionList[0]; - publisherRESTAPIServices.deleteAPIRevision(apiApplicationKey, accessTokenInfo, - earliestUndeployRevision, apiUuid); + publisherRESTAPIServices.deleteAPIRevision(earliestUndeployRevision, apiUuid); } } @@ -366,8 +329,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { APIRevision apiRevision = new APIRevision(); apiRevision.setApiUUID(apiUuid); apiRevision.setDescription("Updated Revision"); - String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey, - accessTokenInfo, apiRevision).getId(); + String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiRevision).getId(); APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment(); apiRevisionDeployment.setName(API_PUBLISH_ENVIRONMENT); @@ -377,12 +339,10 @@ public class APIPublisherServiceImpl implements APIPublisherService { List apiRevisionDeploymentList = new ArrayList<>(); apiRevisionDeploymentList.add(apiRevisionDeployment); - publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo, - apiUuid, apiRevisionId, apiRevisionDeploymentList); + publisherRESTAPIServices.deployAPIRevision(apiUuid, apiRevisionId, apiRevisionDeploymentList); if (CREATED_STATUS.equals(existingAPI.getLifeCycleStatus())) { - publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey, accessTokenInfo, - apiUuid, PUBLISH_ACTION); + publisherRESTAPIServices.changeLifeCycleStatus(apiUuid, PUBLISH_ACTION); } } } @@ -412,26 +372,23 @@ public class APIPublisherServiceImpl implements APIPublisherService { apiDocumentation.setSummary(apiConfig.getApiDocumentationSummary()); apiDocumentation.setOtherTypeName(null); - Documentation[] documentList = publisherRESTAPIServices.getDocumentations(apiApplicationKey, - accessTokenInfo, apiUuid); + Documentation[] documentList = publisherRESTAPIServices.getDocumentations(apiUuid); if (documentList.length > 0) { for (int i = 0; i < documentList.length; i++) { Documentation existingDoc = documentList[i]; if (existingDoc.getName().equals(apiConfig.getApiDocumentationName()) && existingDoc.getType().equals(Documentation.DocumentationType.HOWTO.name())) { - publisherRESTAPIServices.deleteDocumentations(apiApplicationKey, accessTokenInfo, - apiUuid, existingDoc.getDocumentId()); + publisherRESTAPIServices.deleteDocumentations(apiUuid, existingDoc.getDocumentId()); } } } else { log.info("There is no any existing api documentation."); } - Documentation createdDoc = publisherRESTAPIServices.addDocumentation(apiApplicationKey, accessTokenInfo, - apiUuid, apiDocumentation); + Documentation createdDoc = publisherRESTAPIServices.addDocumentation(apiUuid, apiDocumentation); - publisherRESTAPIServices.addDocumentationContent(apiApplicationKey, accessTokenInfo, apiUuid, + publisherRESTAPIServices.addDocumentationContent(apiUuid, createdDoc.getDocumentId(), docContent); } @@ -441,7 +398,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { log.error(msg, e); throw new APIManagerPublisherException(e); } finally { - APIPublisherUtils.removeScopePublishUserIfExists(tenantDomain); PrivilegedCarbonContext.endTenantFlow(); } } @@ -461,7 +417,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); DefaultPermissions defaultPermissions = deviceManagementConfig.getDefaultPermissions(); - APIApplicationServices apiApplicationServices = APIPublisherDataHolder.getInstance().getApiApplicationServices(); PublisherRESTAPIServices publisherRESTAPIServices = APIPublisherDataHolder.getInstance().getPublisherRESTAPIServices(); for (String tenantDomain : tenants) { @@ -469,17 +424,9 @@ public class APIPublisherServiceImpl implements APIPublisherService { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); - APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); - APIApplicationKey apiApplicationKey = - apiApplicationServices.createAndRetrieveApplicationCredentials(); - AccessTokenInfo accessTokenInfo = - apiApplicationServices.generateAccessTokenFromRegisteredApplication( - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - Scope scope = new Scope(); for (DefaultPermission defaultPermission : defaultPermissions.getDefaultPermissions()) { - if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, - defaultPermission.getScopeMapping().getKey())) { + if (!publisherRESTAPIServices.isSharedScopeNameExists(defaultPermission.getScopeMapping().getKey())) { ScopeMapping scopeMapping = defaultPermission.getScopeMapping(); List bindings = new ArrayList<>( @@ -489,7 +436,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { scope.setDescription(scopeMapping.getName()); scope.setDisplayName(scopeMapping.getName()); scope.setBindings(bindings); - publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); + publisherRESTAPIServices.addNewSharedScope(scope); } } } catch (BadRequestException | UnexpectedResponseException | APIServicesException e) { @@ -497,7 +444,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { log.error(errorMsg, e); throw new APIManagerPublisherException(e); } finally { - APIPublisherUtils.removeScopePublishUserIfExists(tenantDomain); PrivilegedCarbonContext.endTenantFlow(); } } @@ -511,12 +457,8 @@ public class APIPublisherServiceImpl implements APIPublisherService { WebappPublisherConfig config = WebappPublisherConfig.getInstance(); List tenants = new ArrayList<>(Collections.singletonList(APIConstants.SUPER_TENANT_DOMAIN)); tenants.addAll(config.getTenants().getTenant()); - - APIApplicationServices apiApplicationServices = APIPublisherDataHolder.getInstance().getApiApplicationServices(); PublisherRESTAPIServices publisherRESTAPIServices = APIPublisherDataHolder.getInstance().getPublisherRESTAPIServices(); - APIApplicationKey apiApplicationKey; - AccessTokenInfo accessTokenInfo; UserStoreManager userStoreManager; String fileName = null; @@ -524,16 +466,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); - try { - APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); - apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); - accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - } catch (APIServicesException e) { - String errorMsg = "Error occurred while generating the API application"; - log.error(errorMsg, e); - throw new APIManagerPublisherException(e); - } try { fileName = @@ -599,7 +531,7 @@ public class APIPublisherServiceImpl implements APIPublisherService { } } //Set scope details which related to the scope key - Scope[] scopes = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo); + Scope[] scopes = publisherRESTAPIServices.getScopes(); for (int i = 0; i < scopes.length; i++) { Scope relatedScope = scopes[i]; if (relatedScope.getName().equals(scopeMapping[2].toString())) { @@ -611,13 +543,13 @@ public class APIPublisherServiceImpl implements APIPublisherService { } scope.setBindings(rolesList); - if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getName())) { - publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope); + if (publisherRESTAPIServices.isSharedScopeNameExists(scope.getName())) { + publisherRESTAPIServices.updateSharedScope(scope); // todo: permission changed in update path, is not handled yet. } else { // This scope doesn't have an api attached. log.warn(scope.getName() + " not available as shared, add as new scope"); - publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); + publisherRESTAPIServices.addNewSharedScope(scope); // add permission if not exist try { PermissionUtils.putPermission(permission); @@ -652,7 +584,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { log.error(errorMsg, e); throw new APIManagerPublisherException(e); } finally { - APIPublisherUtils.removeScopePublishUserIfExists(tenantDomain); PrivilegedCarbonContext.endTenantFlow(); } } @@ -661,31 +592,18 @@ public class APIPublisherServiceImpl implements APIPublisherService { @Override public void updateScopeRoleMapping(String roleName, String[] permissions, String[] removedPermissions) throws APIManagerPublisherException { String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - APIApplicationServices apiApplicationServices = APIPublisherDataHolder.getInstance().getApiApplicationServices(); PublisherRESTAPIServices publisherRESTAPIServices = APIPublisherDataHolder.getInstance().getPublisherRESTAPIServices(); - APIApplicationKey apiApplicationKey; - AccessTokenInfo accessTokenInfo; - try { - APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); - apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); - accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - } catch (APIServicesException e) { - String errorMsg = "Error occurred while generating the API application"; - log.error(errorMsg, e); - throw new APIManagerPublisherException(e); - } try { - Scope[] scopeList = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo); + Scope[] scopeList = publisherRESTAPIServices.getScopes(); Map permScopeMap = APIPublisherDataHolder.getInstance().getPermScopeMapping(); if (permissions.length != 0) { - updateScopes(roleName, publisherRESTAPIServices, apiApplicationKey, accessTokenInfo, scopeList, permissions, permScopeMap, false); + updateScopes(roleName, publisherRESTAPIServices, scopeList, permissions, permScopeMap, false); } if (removedPermissions.length != 0) { - updateScopes(roleName, publisherRESTAPIServices, apiApplicationKey, accessTokenInfo, scopeList, removedPermissions, permScopeMap, true); + updateScopes(roleName, publisherRESTAPIServices, scopeList, removedPermissions, permScopeMap, true); } try { @@ -707,8 +625,6 @@ public class APIPublisherServiceImpl implements APIPublisherService { String errorMsg = "Unexpected response from the server"; log.error(errorMsg, e); throw new APIManagerPublisherException(errorMsg, e); - } finally { - APIPublisherUtils.removeScopePublishUserIfExists(tenantDomain); } } @@ -717,17 +633,13 @@ public class APIPublisherServiceImpl implements APIPublisherService { * * @param roleName Role Name * @param publisherRESTAPIServices {@link PublisherRESTAPIServices} - * @param apiApplicationKey {@link APIApplicationKey} - * @param accessTokenInfo {@link AccessTokenInfo} * @param scopeList scope list returning from APIM * @param permissions List of permissions * @param permScopeMap Permission Scope map * @param removingPermissions if list of permissions has to be removed from the role send true, otherwise sends false. * @throws APIManagerPublisherException If the method receives invalid permission to update. */ - private void updateScopes (String roleName, PublisherRESTAPIServices publisherRESTAPIServices, - APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, - Scope[] scopeList, String[] permissions, Map permScopeMap, boolean removingPermissions ) + private void updateScopes (String roleName, PublisherRESTAPIServices publisherRESTAPIServices, Scope[] scopeList, String[] permissions, Map permScopeMap, boolean removingPermissions ) throws APIManagerPublisherException { for (String permission : permissions) { String scopeValue = permScopeMap.get(permission); @@ -765,8 +677,8 @@ public class APIPublisherServiceImpl implements APIPublisherService { scope.setBindings(existingRoleList); try { - if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, scope.getName())) { - publisherRESTAPIServices.updateSharedScope(apiApplicationKey, accessTokenInfo, scope); + if (publisherRESTAPIServices.isSharedScopeNameExists(scope.getName())) { + publisherRESTAPIServices.updateSharedScope(scope); } else { // todo: come to this level means, that scope is removed from API, but haven't removed from the scope-role-permission-mappings list log.warn(scope.getName() + " not available as shared scope"); diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java index d00f50e35f..4457be5fea 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherDataHolder.java @@ -17,7 +17,6 @@ */ package io.entgra.device.mgt.core.apimgt.webapp.publisher.internal; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIConfig; import io.entgra.device.mgt.core.apimgt.webapp.publisher.APIPublisherService; @@ -49,7 +48,6 @@ public class APIPublisherDataHolder { private boolean isServerStarted; private Stack unpublishedApis = new Stack<>(); private Map permScopeMapping; - private APIApplicationServices apiApplicationServices; private PublisherRESTAPIServices publisherRESTAPIServices; private MetadataManagementService metadataManagementService; @@ -160,14 +158,6 @@ public class APIPublisherDataHolder { this.permScopeMapping = permScopeMapping; } - public APIApplicationServices getApiApplicationServices() { - return apiApplicationServices; - } - - public void setApiApplicationServices(APIApplicationServices apiApplicationServices) { - this.apiApplicationServices = apiApplicationServices; - } - public PublisherRESTAPIServices getPublisherRESTAPIServices() { return publisherRESTAPIServices; } diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java index 62684c2215..015fc69e9a 100644 --- a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java +++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.webapp.publisher/src/main/java/io/entgra/device/mgt/core/apimgt/webapp/publisher/internal/APIPublisherServiceComponent.java @@ -17,7 +17,6 @@ */ package io.entgra.device.mgt.core.apimgt.webapp.publisher.internal; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.MetadataManagementService; import io.entgra.device.mgt.core.apimgt.webapp.publisher.PostApiPublishingObsever; @@ -49,12 +48,6 @@ import java.util.HashMap; * policy="dynamic" * bind="setRegistryService" * unbind="unsetRegistryService" - * @scr.reference name="APIM.application.service" - * interface="io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices" - * cardinality="1..1" - * policy="dynamic" - * bind="setAPIApplicationServices" - * unbind="unsetAPIApplicationServices" * @scr.reference name="APIM.publisher.service" * interface="io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices" * cardinality="1..1" @@ -144,20 +137,6 @@ public class APIPublisherServiceComponent { APIPublisherDataHolder.getInstance().setRegistryService(null); } - protected void setAPIApplicationServices(APIApplicationServices apiApplicationServices) { - if (log.isDebugEnabled()) { - log.debug("Setting DCR REST API Service"); - } - APIPublisherDataHolder.getInstance().setApiApplicationServices(apiApplicationServices); - } - - protected void unsetAPIApplicationServices(APIApplicationServices apiApplicationServices) { - if (log.isDebugEnabled()) { - log.debug("Unsetting DCR REST API Service"); - } - APIPublisherDataHolder.getInstance().setApiApplicationServices(null); - } - protected void setPublisherRESTAPIServices(PublisherRESTAPIServices publisherRESTAPIServices) { if (log.isDebugEnabled()) { log.debug("Setting APIM Publisher REST API Service"); diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/ExtraQueryParam.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/ExtraQueryParam.java new file mode 100644 index 0000000000..5c7a6cd6c1 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/ExtraQueryParam.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.device.mgt.core.config.ui; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "ExtraQueryParam") +public class ExtraQueryParam { + private String queryParam; + private String paramValue; + + @XmlElement(name = "QueryParam") + public String getQueryParam() { + return queryParam; + } + + public void setQueryParam(String queryParam) { + this.queryParam = queryParam; + } + + @XmlElement(name = "ParamValue") + public String getParamValue() { + return paramValue; + } + + public void setParamValue(String paramValue) { + this.paramValue = paramValue; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/SSOConfiguration.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/SSOConfiguration.java new file mode 100644 index 0000000000..d1016c2798 --- /dev/null +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/SSOConfiguration.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.device.mgt.core.config.ui; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.List; + +@XmlRootElement(name = "SSOConfiguration") +public class SSOConfiguration { + private List authEndpointExtraQueryParam; + + @XmlElementWrapper(name = "AuthEndpointExtraQueryParams") + @XmlElement(name = "ExtraQueryParam") + public List getAuthEndpointExtraQueryParam() { + return authEndpointExtraQueryParam; + } + + public void setAuthEndpointExtraQueryParam(List authEndpointExtraQueryParam) { + this.authEndpointExtraQueryParam = authEndpointExtraQueryParam; + } +} diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/UIConfiguration.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/UIConfiguration.java index 4dd9cbfe4a..180d19138e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/UIConfiguration.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/config/ui/UIConfiguration.java @@ -35,6 +35,7 @@ public class UIConfiguration { private int loginCacheCapacity; private Billing billing; private HubspotChat hubspotChat; + private SSOConfiguration ssoConfiguration; private DeviceInfoConfigurations deviceInfoConfigurations; @@ -121,4 +122,13 @@ public class UIConfiguration { public void setDeviceStatusConfigurations(DeviceStatusConfigurations deviceStatusConfigurations) { this.deviceStatusConfigurations = deviceStatusConfigurations; } + + @XmlElement(name = "SSOConfiguration", required = true) + public SSOConfiguration getSsoConfiguration() { + return ssoConfiguration; + } + + public void setSsoConfiguration(SSOConfiguration ssoConfiguration) { + this.ssoConfiguration = ssoConfiguration; + } } diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementDataHolder.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementDataHolder.java index 48d573a5fa..db370f4d9c 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementDataHolder.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/DeviceManagementDataHolder.java @@ -18,7 +18,6 @@ package io.entgra.device.mgt.core.device.mgt.core.internal; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; import io.entgra.device.mgt.core.device.mgt.common.authorization.GroupAccessAuthorizationService; import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.DeviceStatusManagementService; @@ -98,7 +97,6 @@ public class DeviceManagementDataHolder { private WhiteLabelManagementService whiteLabelManagementService; private TraccarManagementService traccarManagementService; private DeviceStatusManagementService deviceStatusManagementService; - private APIApplicationServices apiApplicationServices; private PublisherRESTAPIServices publisherRESTAPIServices; private final Map deviceStatusTaskPluginConfigs = Collections.synchronizedMap( @@ -416,23 +414,6 @@ public class DeviceManagementDataHolder { this.traccarManagementService = traccarManagementService; } - /** - * Retrieves the Dynamic Client Registration REST API Service instance from OSGI service context. - * @return {@link APIApplicationServices} Dynamic Client Registration REST API Service - */ - public APIApplicationServices getApiApplicationServices() { - PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); - apiApplicationServices = (APIApplicationServices) ctx.getOSGiService(APIApplicationServices.class, null); - if (apiApplicationServices == null) { - throw new IllegalStateException("Dynamic Client Registration REST API Service was not initialized."); - } - return apiApplicationServices; - } - - public void setApiApplicationServices(APIApplicationServices apiApplicationServices) { - this.apiApplicationServices = apiApplicationServices; - } - /** * Retrieves the API Manager Publisher REST API Service instance from OSGI service context. * @return {@link PublisherRESTAPIServices} API Manager Publisher REST API Service diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/TenantCreateObserver.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/TenantCreateObserver.java index eb5fe919d2..7d958272f8 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/TenantCreateObserver.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/internal/TenantCreateObserver.java @@ -18,12 +18,9 @@ package io.entgra.device.mgt.core.device.mgt.core.internal; import com.google.gson.Gson; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.Scope; -import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; @@ -46,7 +43,6 @@ import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.utils.AbstractAxis2ConfigurationContextObserver; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; -import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import java.util.ArrayList; import java.util.Arrays; @@ -163,34 +159,16 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser return; } - APIApplicationServices apiApplicationServices = DeviceManagementDataHolder.getInstance().getApiApplicationServices(); - APIApplicationKey apiApplicationKey; - AccessTokenInfo accessTokenInfo; - - try { - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); - - APIPublisherUtils.createScopePublishUserIfNotExists(tenantDomain); - apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); - accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( - apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); - } catch (APIServicesException e) { - msg = "Error occurred while generating the API application for tenant: '" + tenantDomain + "'."; - log.error(msg, e); - throw new TenantManagementException(msg, e); - } - try { PublisherRESTAPIServices publisherRESTAPIServices = DeviceManagementDataHolder.getInstance().getPublisherRESTAPIServices(); - Scope[] superTenantScopes = getAllScopesFromSuperTenant(apiApplicationServices, publisherRESTAPIServices); + Scope[] superTenantScopes = getAllScopesFromSuperTenant(publisherRESTAPIServices); if (superTenantScopes != null) { if (log.isDebugEnabled()) { log.debug("Number of super tenant scopes already published - " + superTenantScopes.length); } - Scope[] subTenantScopes = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo); + Scope[] subTenantScopes = publisherRESTAPIServices.getScopes(); if (subTenantScopes.length > 0) { // If there is already existing scopes on the sub tenant space then do a comparison with the @@ -230,8 +208,7 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser if (log.isDebugEnabled()) { log.debug("Starting to add new/updated shared scopes to the tenant: '" + tenantDomain + "'."); } - publishSharedScopes(missingScopes, publisherRESTAPIServices, apiApplicationKey, - accessTokenInfo); + publishSharedScopes(missingScopes, publisherRESTAPIServices); } for (Scope subTenantScope : subTenantScopes) { @@ -261,10 +238,9 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser log.debug("Starting to delete shared scopes from the tenant: '" + tenantDomain + "'."); } for (Scope deletedScope : deletedScopes) { - if (publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, - deletedScope.getName())) { + if (publisherRESTAPIServices.isSharedScopeNameExists(deletedScope.getName())) { Scope scope = createScopeObject(deletedScope); - publisherRESTAPIServices.deleteSharedScope(apiApplicationKey, accessTokenInfo, scope); + publisherRESTAPIServices.deleteSharedScope(scope); } } } @@ -277,8 +253,7 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser log.debug("Starting to publish shared scopes to newly created tenant: '" + tenantDomain + "'."); } - publishSharedScopes(Arrays.asList(superTenantScopes), publisherRESTAPIServices, - apiApplicationKey, accessTokenInfo); + publishSharedScopes(Arrays.asList(superTenantScopes), publisherRESTAPIServices); updatePermScopeMetaData(superTenantPermScopeMapping, metadataManagementService); } } else { @@ -308,7 +283,6 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser log.error(msg); throw new TenantManagementException(msg); } finally { - APIPublisherUtils.removeScopePublishUserIfExists(tenantDomain); PrivilegedCarbonContext.endTenantFlow(); } } @@ -367,15 +341,13 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser /** * Get all the scopes from the super tenant space - * @param apiApplicationServices {@link APIApplicationServices} is used to create an OAuth application and retrieve client ID and secret * @param publisherRESTAPIServices {@link PublisherRESTAPIServices} is used to get all scopes under a given tenant using client credentials * @return array of {@link Scope} * @throws BadRequestException if an invalid request is sent to the API Manager Publisher REST API Service * @throws UnexpectedResponseException if an unexpected response is received from the API Manager Publisher REST API Service * @throws TenantManagementException if an error occurred while processing the request sent to API Manager Publisher REST API Service */ - private Scope[] getAllScopesFromSuperTenant(APIApplicationServices apiApplicationServices, - PublisherRESTAPIServices publisherRESTAPIServices) throws BadRequestException, + private Scope[] getAllScopesFromSuperTenant(PublisherRESTAPIServices publisherRESTAPIServices) throws BadRequestException, UnexpectedResponseException, TenantManagementException { try { @@ -383,10 +355,7 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser // in order to see if any new scopes were added or deleted PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); - APIApplicationKey superTenantApiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials(); - AccessTokenInfo superTenantAccessToken = apiApplicationServices.generateAccessTokenFromRegisteredApplication( - superTenantApiApplicationKey.getClientId(), superTenantApiApplicationKey.getClientSecret()); - return publisherRESTAPIServices.getScopes(superTenantApiApplicationKey, superTenantAccessToken); + return publisherRESTAPIServices.getScopes(); } catch (APIServicesException e) { msg = "Error occurred while retrieving access token from super tenant"; log.error(msg, e); @@ -399,22 +368,18 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser /** * Add shared scopes to the tenant space. * @param scopeList {@link List} of {@link Scope} - * @param publisherRESTAPIServices {@link PublisherRESTAPIServices} is used to add shared scopes to a given tenant using client credentials - * @param apiApplicationKey {@link APIApplicationKey} contains client credentials of the OAuth application - * @param accessTokenInfo {@link AccessTokenInfo} contains token information generated from the client credentials + * @param publisherRESTAPIServices {@link PublisherRESTAPIServices} is used to add shared scopes to a given tenant using client credential * @throws BadRequestException if an invalid request is sent to the API Manager Publisher REST API Service * @throws UnexpectedResponseException if an unexpected response is received from the API Manager Publisher REST API Service * @throws APIServicesException if an error occurred while processing the request sent to API Manager Publisher REST API Service */ - private void publishSharedScopes (List scopeList, PublisherRESTAPIServices publisherRESTAPIServices, - APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo) + private void publishSharedScopes (List scopeList, PublisherRESTAPIServices publisherRESTAPIServices) throws BadRequestException, UnexpectedResponseException, APIServicesException { for (Scope tenantScope : scopeList) { - if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo, - tenantScope.getName())) { + if (!publisherRESTAPIServices.isSharedScopeNameExists(tenantScope.getName())) { Scope scope = createScopeObject(tenantScope); - publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope); + publisherRESTAPIServices.addNewSharedScope(scope); } } } 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/InvokerHandler.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/InvokerHandler.java index 00b35af06c..9f1c73097b 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/InvokerHandler.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/InvokerHandler.java @@ -216,11 +216,24 @@ public class InvokerHandler extends HttpServlet { */ private static boolean validateRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException { + HttpSession session = req.getSession(false); + if (session == null) { + log.error("Unauthorized, You are not logged in. Please log in to the portal"); + HandlerUtil.handleError(resp, HttpStatus.SC_UNAUTHORIZED); + return false; + } + apiEndpoint = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme()); - kmManagerUrl = HandlerUtil.getKeyManagerUrl(req.getScheme()); + if (session.getAttribute(HandlerConstants.API_DOMAIN_PREFIX) != null) { + String apiDomainPrefix = session.getAttribute(HandlerConstants.API_DOMAIN_PREFIX).toString(); + if (!StringUtils.isEmpty(apiDomainPrefix)) { + apiEndpoint = apiEndpoint + apiDomainPrefix; + } + } + if (HandlerConstants.REPORTS.equalsIgnoreCase(req.getHeader(HandlerConstants.APP_NAME))){ apiEndpoint = System.getProperty("iot.reporting.webapp.host"); if (StringUtils.isBlank(apiEndpoint)){ @@ -230,13 +243,6 @@ public class InvokerHandler extends HttpServlet { } } - HttpSession session = req.getSession(false); - if (session == null) { - log.error("Unauthorized, You are not logged in. Please log in to the portal"); - HandlerUtil.handleError(resp, HttpStatus.SC_UNAUTHORIZED); - return false; - } - authData = (AuthData) session.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY); if (authData == null) { log.error("Unauthorized, Access token not found in the current session"); 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/JITEnrollmentCallbackHandler.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/JITEnrollmentCallbackHandler.java index 6a82ae3f26..00b63e6abb 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/JITEnrollmentCallbackHandler.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/JITEnrollmentCallbackHandler.java @@ -18,7 +18,6 @@ package io.entgra.device.mgt.core.ui.request.interceptor; -import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; @@ -53,7 +52,6 @@ import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; -import java.util.Base64; import java.util.Objects; @WebServlet( @@ -65,25 +63,26 @@ import java.util.Objects; ) public class JITEnrollmentCallbackHandler extends HttpServlet { private static final Log log = LogFactory.getLog(JITEnrollmentCallbackHandler.class); - private String gatewayUrl; private String keyManagerUrl; + private String JITProvisionCallbackUrl; private JITData JITInfo; - private String encodedClientCredentials; - private String applicationName; - private String clientId; - private String clientSecret; private String scope; private String JITConfigurationPath; private JITEnrollmentData JITEnrollmentInfo; + private String code; + @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) { - gatewayUrl = request.getScheme() + HandlerConstants.SCHEME_SEPARATOR - + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) - + HandlerConstants.COLON + HandlerUtil.getGatewayPort(request.getScheme()); keyManagerUrl = request.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_KM_HOST_ENV_VAR) + HandlerConstants.COLON + HandlerUtil.getKeyManagerPort(request.getScheme()); + JITProvisionCallbackUrl = request.getScheme() + HandlerConstants.SCHEME_SEPARATOR + + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR) + + HandlerConstants.COLON + HandlerUtil.getCorePort(request.getScheme()) + + request.getContextPath() + + HandlerConstants.JIT_PROVISION_CALLBACK_URL; JITConfigurationPath = CarbonUtils.getCarbonConfigDirPath() + File.separator + "jit-config.xml"; + HttpSession session = request.getSession(false); try { if (session == null) { @@ -91,6 +90,14 @@ public class JITEnrollmentCallbackHandler extends HttpServlet { return; } + String state = request.getParameter("state"); + if (state == null || !Objects.equals(state, session.getAttribute("state").toString())) { + response.sendError(org.apache.http.HttpStatus.SC_BAD_REQUEST, "MismatchingStateError: CSRF Warning! " + + "State not equal in request and response"); + return; + } + + code = request.getParameter("code"); JITInfo = (JITData) session.getAttribute(HandlerConstants.SESSION_JIT_DATA_KEY); if (JITInfo == null) { response.sendError(HttpStatus.SC_UNAUTHORIZED); @@ -103,10 +110,8 @@ public class JITEnrollmentCallbackHandler extends HttpServlet { response.sendError(HttpStatus.SC_UNAUTHORIZED); return; } - applicationName = request.getContextPath().substring(1, - request.getContextPath().indexOf("-ui-request-handler")); + initializeJITEnrollmentConfigurations(); - populateApplicationData(registerApplication()); persistAuthData(session, getToken()); response.sendRedirect(JITEnrollmentInfo.getRedirectUrl() + "?ownershipType=" + JITEnrollmentInfo.getOwnershipType() + "&os=" + JITEnrollmentInfo.getOs() + "&username=" + @@ -177,55 +182,6 @@ public class JITEnrollmentCallbackHandler extends HttpServlet { throw new JITEnrollmentException("Unexpected response body return"); } - /*** - * Build application registration request - * @return {@link HttpPost} Application registration request - */ - private HttpPost buildApplicationRegistrationRequest() { - HttpPost applicationRegistrationRequest = new HttpPost(gatewayUrl + HandlerConstants.APP_REG_ENDPOINT); - applicationRegistrationRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC - + JITInfo.getEncodedClientCredentials()); - applicationRegistrationRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); - JsonArray tags = new JsonArray(); - tags.add("device_management"); - JsonObject payload = new JsonObject(); - payload.addProperty("applicationName", applicationName); - payload.add("tags", tags); - payload.addProperty("allowedToAllDomains", false); - payload.addProperty("mappingAnExistingOAuthApp", false); - applicationRegistrationRequest.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON)); - return applicationRegistrationRequest; - } - - /*** - * Populate dynamic client's data - * @param application - application data receiving from dcr request - */ - private void populateApplicationData(JsonObject application) { - clientId = application.get("client_id").getAsString(); - clientSecret = application.get("client_secret").getAsString(); - String headerValue = clientId+ ':' + clientSecret; - encodedClientCredentials = Base64.getEncoder().encodeToString(headerValue.getBytes()); - } - - /*** - * Register client application - * @return {@link JsonObject} Json object contain registered application data - * @throws JITEnrollmentException throws when error occurred while application registration - */ - private JsonObject registerApplication() throws JITEnrollmentException { - try { - ProxyResponse proxyResponse = HandlerUtil.execute(buildApplicationRegistrationRequest()); - if (proxyResponse.getCode() == HttpStatus.SC_CREATED || - proxyResponse.getCode() == HttpStatus.SC_OK) { - return parseResponseData(proxyResponse.getData()); - } - throw new JITEnrollmentException("Unexpected response status return for application registration request"); - } catch (IOException ex) { - throw new JITEnrollmentException("Error occurred while executing application registration request", ex); - } - } - /*** * Acquire token * @return {@link JsonObject} Json object containing token data @@ -250,11 +206,11 @@ public class JITEnrollmentCallbackHandler extends HttpServlet { */ private HttpPost buildTokenAcquireRequest() { HttpPost tokenAcquiringRequest = new HttpPost(keyManagerUrl + HandlerConstants.OAUTH2_TOKEN_ENDPOINT); + tokenAcquiringRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + JITInfo.getEncodedClientCredentials()); tokenAcquiringRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); - tokenAcquiringRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC - + encodedClientCredentials); StringEntity payload = new StringEntity( - "grant_type=" + HandlerConstants.CLIENT_CREDENTIAL_GRANT_TYPE + "&scope=" + scope, + "grant_type=" + HandlerConstants.CODE_GRANT_TYPE + "&code=" + code + "&scope=" + scope + + "&redirect_uri=" + JITProvisionCallbackUrl, ContentType.APPLICATION_FORM_URLENCODED); tokenAcquiringRequest.setEntity(payload); return tokenAcquiringRequest; @@ -268,9 +224,10 @@ public class JITEnrollmentCallbackHandler extends HttpServlet { private void persistAuthData(HttpSession session, JsonObject token) { AuthData authData = new AuthData(); authData.setAccessToken(token.get("access_token").getAsString()); - authData.setClientId(clientId); - authData.setClientSecret(clientSecret); - authData.setEncodedClientApp(encodedClientCredentials); + authData.setRefreshToken(token.get("refresh_token").getAsString()); + authData.setClientId(JITInfo.getClientId()); + authData.setClientSecret(JITInfo.getClientSecret()); + authData.setEncodedClientApp(JITInfo.getEncodedClientCredentials()); authData.setScope(token.get("scope").getAsString()); session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, authData); } 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/JITEnrollmentHandler.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/JITEnrollmentHandler.java index 8ca9cdf98c..8bf15198d7 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/JITEnrollmentHandler.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/JITEnrollmentHandler.java @@ -49,6 +49,8 @@ public class JITEnrollmentHandler extends HttpServlet { private String os; private String redirectUrl; private String tenantDomain; + private String state; + @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) { try { @@ -58,11 +60,12 @@ public class JITEnrollmentHandler extends HttpServlet { + HandlerConstants.COLON + HandlerUtil.getCorePort(request.getScheme()) + request.getContextPath() + HandlerConstants.JIT_PROVISION_HANDLER; - String onCompletionUrl = request.getScheme() + HandlerConstants.SCHEME_SEPARATOR + String JITEnrollmentCallbackUrl = request.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR) + HandlerConstants.COLON + HandlerUtil.getCorePort(request.getScheme()) + request.getContextPath() + "/jit-enrollment-callback"; + state = HandlerUtil.generateStateToken(); username = request.getParameter("username"); ownershipType = request.getParameter("ownershipType"); os = request.getParameter("os"); @@ -71,7 +74,7 @@ public class JITEnrollmentHandler extends HttpServlet { String sp = request.getParameter("sp"); persistJITData(session); response.sendRedirect(JITProvisionHandlerUrl + "?tenantDomain=" + tenantDomain - + "&sp=" + sp + "&redirectUrl=" + onCompletionUrl); + + "&sp=" + sp + "&redirectUrl=" + JITEnrollmentCallbackUrl); } catch (IOException ex) { log.error("Error occurred while handling JIT enrollment request"); } @@ -88,6 +91,7 @@ public class JITEnrollmentHandler extends HttpServlet { JITEnrollmentInfo.setUsername(username); JITEnrollmentInfo.setRedirectUrl(redirectUrl); JITEnrollmentInfo.setTenantDomain(tenantDomain); + session.setAttribute("state", state); session.setAttribute(HandlerConstants.SESSION_JIT_ENROLLMENT_DATA_KEY, JITEnrollmentInfo); } } 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/JITProvisionCallbackHandler.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/JITProvisionCallbackHandler.java index 433c1e7de3..759e2e1604 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/JITProvisionCallbackHandler.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/JITProvisionCallbackHandler.java @@ -18,13 +18,22 @@ package io.entgra.device.mgt.core.ui.request.interceptor; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import io.entgra.device.mgt.core.ui.request.interceptor.beans.AuthData; import io.entgra.device.mgt.core.ui.request.interceptor.beans.JITData; -import io.entgra.device.mgt.core.ui.request.interceptor.beans.JITEnrollmentData; +import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; +import io.entgra.device.mgt.core.ui.request.interceptor.exceptions.JITProvisionException; 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.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpHeaders; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; @@ -43,38 +52,129 @@ import java.util.Objects; ) public class JITProvisionCallbackHandler extends HttpServlet { private static final Log log = LogFactory.getLog(JITProvisionCallbackHandler.class); + private String keyManagerUrl; + private String JITProvisionCallbackUrl; + private String scope; + private String code; + private JITData JITInfo; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) { - String state = request.getParameter("state"); - HttpSession session = request.getSession(false); - String JITProvisionCallbackURL = request.getScheme() + HandlerConstants.SCHEME_SEPARATOR + JITProvisionCallbackUrl = request.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR) + HandlerConstants.COLON + HandlerUtil.getCorePort(request.getScheme()) + request.getContextPath() + HandlerConstants.JIT_PROVISION_CALLBACK_URL; + + HttpSession session = request.getSession(false); + try { if (session == null) { response.sendError(HttpStatus.SC_UNAUTHORIZED); return; } + String state = request.getParameter("state"); if (state == null || !Objects.equals(state, session.getAttribute("state").toString())) { response.sendError(org.apache.http.HttpStatus.SC_BAD_REQUEST, "MismatchingStateError: CSRF Warning! " + "State not equal in request and response"); return; } - JITData JITInfo = (JITData) session.getAttribute(HandlerConstants.SESSION_JIT_DATA_KEY); + code = request.getParameter("code"); + JITInfo = (JITData) session.getAttribute(HandlerConstants.SESSION_JIT_DATA_KEY); if (JITInfo == null) { response.sendError(HttpStatus.SC_UNAUTHORIZED); return; } - response.sendRedirect(JITInfo.getRedirectUrl() + "?code=" + request.getParameter("code") - + "&redirectUrl=" + JITProvisionCallbackURL); + if (JITInfo.getApplicationUrl() != null) { + handleApplicationLogin(request, response, session); + return; + } + + response.sendRedirect(JITInfo.getRedirectUrl() + "?code=" + request.getParameter("code") + "&state=" + state); + } catch (IOException ex) { log.error("Error occurred while processing JIT provisioning callback request", ex); } } + + private void handleApplicationLogin(HttpServletRequest request, HttpServletResponse response, HttpSession session) { + keyManagerUrl = request.getScheme() + HandlerConstants.SCHEME_SEPARATOR + + System.getProperty(HandlerConstants.IOT_KM_HOST_ENV_VAR) + + HandlerConstants.COLON + HandlerUtil.getKeyManagerPort(request.getScheme()); + try { + scope = session.getAttribute("scope").toString(); + persistAuthData(session, getToken()); + response.sendRedirect(JITInfo.getApplicationUrl()); + } catch (JITProvisionException | IOException ex) { + log.error("Error encountered while handling login request for " + JITInfo.getApplicationUrl()); + } + } + + /*** + * Parse string data and build json object + * @param data - Json string + * @return {@link JsonObject} Json object corresponding to provided json string + * @throws JITProvisionException throws when error occurred while parsing + */ + private JsonObject parseResponseData(String data) throws JITProvisionException { + JsonParser parser = new JsonParser(); + JsonElement responseData = parser.parse(data); + if (responseData.isJsonObject()) { + return responseData.getAsJsonObject(); + } + throw new JITProvisionException("Unexpected response body return"); + } + + /*** + * Acquire token + * @return {@link JsonObject} Json object containing token data + * @throws JITProvisionException throws when error occurred while acquiring token + */ + private JsonObject getToken() throws JITProvisionException { + try { + ProxyResponse proxyResponse = HandlerUtil.execute(buildTokenAcquireRequest()); + if (proxyResponse.getCode() == org.apache.http.HttpStatus.SC_CREATED || + proxyResponse.getCode() == org.apache.http.HttpStatus.SC_OK) { + return parseResponseData(proxyResponse.getData()); + } + throw new JITProvisionException("Unexpected response status return for token acquiring request"); + } catch (IOException ex) { + throw new JITProvisionException("Error occurred while executing token acquiring request", ex); + } + } + + /*** + * Build token acquire request + * @return {@link HttpPost} Token acquire request + */ + private HttpPost buildTokenAcquireRequest() { + HttpPost tokenAcquiringRequest = new HttpPost(keyManagerUrl + HandlerConstants.OAUTH2_TOKEN_ENDPOINT); + tokenAcquiringRequest.setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BASIC + JITInfo.getEncodedClientCredentials()); + tokenAcquiringRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); + StringEntity payload = new StringEntity( + "grant_type=" + HandlerConstants.CODE_GRANT_TYPE + "&code=" + code + "&scope=" + scope + + "&redirect_uri=" + JITProvisionCallbackUrl, + ContentType.APPLICATION_FORM_URLENCODED); + tokenAcquiringRequest.setEntity(payload); + return tokenAcquiringRequest; + } + + /*** + * Persists auth data in session + * @param session {@link HttpSession} + * @param token Json object containing token data + */ + private void persistAuthData(HttpSession session, JsonObject token) { + AuthData authData = new AuthData(); + authData.setAccessToken(token.get("access_token").getAsString()); + authData.setRefreshToken(token.get("refresh_token").getAsString()); + authData.setClientId(JITInfo.getClientId()); + authData.setClientSecret(JITInfo.getClientSecret()); + authData.setEncodedClientApp(JITInfo.getEncodedClientCredentials()); + authData.setScope(token.get("scope").getAsString()); + session.setAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY, authData); + } } 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/JITProvisionHandler.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/JITProvisionHandler.java index 9c1cf31a94..d9102b3ff9 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/JITProvisionHandler.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/JITProvisionHandler.java @@ -18,22 +18,18 @@ package io.entgra.device.mgt.core.ui.request.interceptor; -import com.google.gson.JsonElement; +import com.google.gson.Gson; +import com.google.gson.JsonArray; import com.google.gson.JsonObject; -import com.google.gson.JsonParser; import io.entgra.device.mgt.core.ui.request.interceptor.beans.JITData; import io.entgra.device.mgt.core.ui.request.interceptor.beans.ProxyResponse; -import io.entgra.device.mgt.core.ui.request.interceptor.exceptions.JITEnrollmentException; +import io.entgra.device.mgt.core.ui.request.interceptor.beans.ServiceProvider; import io.entgra.device.mgt.core.ui.request.interceptor.exceptions.JITProvisionException; 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.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHeaders; import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -52,9 +48,11 @@ import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.util.Base64; -import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; @WebServlet( @@ -66,53 +64,104 @@ import java.util.Objects; ) public class JITProvisionHandler extends HttpServlet { private static final Log log = LogFactory.getLog(JITProvisionHandler.class); + private static final String JITConfigurationPath = CarbonUtils.getCarbonConfigDirPath() + File.separator + "jit-config.xml"; + private static final Gson gson = new Gson(); + private static Map serviceProviders; private String tenantDomain; private String clientId; + private String clientSecret; private String JITServiceProviderName; private String encodedClientCredentials; - private String JITConfigurationPath; private String redirectUrl; + private String applicationUrl; private String state; - private static final Map tenantConfigs = new HashMap<>(); + private String scope; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) { String keyManagerUrl = request.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_KM_HOST_ENV_VAR) + HandlerConstants.COLON + HandlerUtil.getKeyManagerPort(request.getScheme()); + String iotCoreUrl = request.getScheme() + HandlerConstants.SCHEME_SEPARATOR + + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR) + + HandlerConstants.COLON + HandlerUtil.getCorePort(request.getScheme()); + String gatewayUrl = request.getScheme() + HandlerConstants.SCHEME_SEPARATOR + + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) + + HandlerConstants.COLON + HandlerUtil.getGatewayPort(request.getScheme()); String JITCallbackUrl = request.getScheme() + HandlerConstants.SCHEME_SEPARATOR + System.getProperty(HandlerConstants.IOT_CORE_HOST_ENV_VAR) + HandlerConstants.COLON + HandlerUtil.getCorePort(request.getScheme()) + request.getContextPath() + HandlerConstants.JIT_PROVISION_CALLBACK_URL; - JITConfigurationPath = CarbonUtils.getCarbonConfigDirPath() + File.separator + "jit-config.xml"; - String scope = "openid"; + String uiConfigUrl = iotCoreUrl + HandlerConstants.UI_CONFIG_ENDPOINT; + + HttpSession session = request.getSession(true); state = HandlerUtil.generateStateToken(); tenantDomain = request.getParameter("tenantDomain"); redirectUrl = request.getParameter("redirectUrl"); JITServiceProviderName = request.getParameter("sp"); + applicationUrl = request.getParameter("applicationUrl"); try { + JsonObject uiConfigJsonObject = HandlerUtil.getUIConfigAndPersistInSession(uiConfigUrl, gatewayUrl, session, response); + JsonArray scopeJson = uiConfigJsonObject.get("scopes").getAsJsonArray(); + JsonObject ssoConfigurations = uiConfigJsonObject.getAsJsonObject("ssoConfiguration"); + JsonArray authEndpointExtraQueryParam = ssoConfigurations.getAsJsonArray("authEndpointExtraQueryParam"); + String extraParamString = HandlerUtil.getAuthEndpointExtraQueryParamString(authEndpointExtraQueryParam); + scope = "openid " + HandlerUtil.getScopeString(scopeJson); + if (tenantDomain == null || JITServiceProviderName == null) { HandlerUtil.handleError(response, HttpStatus.SC_BAD_REQUEST); return; } + + if (serviceProviders == null) { + loadServiceProviders(); + } + if (!initializeJITConfigurations()) { HandlerUtil.handleError(response, HttpStatus.SC_SERVICE_UNAVAILABLE); return; } - persistJITData(request.getSession(true)); + persistJITData(session); response.sendRedirect(keyManagerUrl + HandlerConstants.AUTHORIZATION_ENDPOINT + "?response_type=code" + "&client_id=" + clientId + "&state=" + state + "&scope=" + scope + - "&redirect_uri=" + JITCallbackUrl); + "&redirect_uri=" + JITCallbackUrl + + extraParamString); } catch (JITProvisionException | IOException ex) { log.error("Error occurred while processing JIT provisioning request", ex); } } + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) { + tenantDomain = request.getParameter("tenantDomain"); + try { + if (tenantDomain == null) { + HandlerUtil.handleError(response, HttpStatus.SC_BAD_REQUEST); + return; + } + + if (serviceProviders == null) { + loadServiceProviders(); + } + + List supportingServiceProviders = serviceProviders.values().stream(). + filter(serviceProvider -> Objects.equals(tenantDomain, + serviceProvider.getTenantDomain())).map(ServiceProvider::getWhiteLabel).collect(Collectors.toList()); + ProxyResponse proxyResponse = new ProxyResponse(); + proxyResponse.setData(gson.toJson(supportingServiceProviders)); + proxyResponse.setStatus(ProxyResponse.Status.SUCCESS); + proxyResponse.setCode(HttpStatus.SC_OK); + HandlerUtil.handleSuccess(response, proxyResponse); + } catch (JITProvisionException | IOException ex) { + log.error("Error occurred while processing request", ex); + } + } + /*** * Retrieve JIT data from current session if session exists, otherwise build and return * @param session - {@link HttpSession} @@ -130,60 +179,52 @@ public class JITProvisionHandler extends HttpServlet { private void persistJITData(HttpSession session) { JITData JITInfo = getJITData(session); JITInfo.setEncodedClientCredentials(encodedClientCredentials); + JITInfo.setClientId(clientId); + JITInfo.setClientSecret(clientSecret); JITInfo.setTenantDomain(tenantDomain); JITInfo.setRedirectUrl(redirectUrl); JITInfo.setSp(JITServiceProviderName); + JITInfo.setApplicationUrl(applicationUrl); session.setMaxInactiveInterval(3600); session.setAttribute("state", state); - session.setAttribute(HandlerConstants.SESSION_JIT_DATA_KEY, JITInfo); - } - - /*** - * Find the tenant based configurations and return - * @param tenantDomain - Domain of the tenant - * @param document - Config doc - * @return {@link Element} If config found return configuration element, otherwise null - */ - private Element findServiceProvider(String tenantDomain, Document document) { - NodeList serviceProviderConfiguration = document.getElementsByTagName("ServiceProvider"); - for (int idx = 0; idx < serviceProviderConfiguration.getLength(); idx++) { - Node configNode = serviceProviderConfiguration.item(idx); - if (configNode.getNodeType() == Node.ELEMENT_NODE) { - Element configElement = (Element) configNode; - if (Objects.equals(configElement.getAttributes(). - getNamedItem("tenantDomain").getNodeValue(), tenantDomain) && - Objects.equals(configElement.getAttributes().getNamedItem("name").getNodeValue(), - JITServiceProviderName)) { - return configElement; - } - } + session.setAttribute("scope", scope); + if (!Objects.equals(tenantDomain, "carbon.super")) { + session.setAttribute(HandlerConstants.API_DOMAIN_PREFIX, "/t/" + tenantDomain); } - return null; + session.setAttribute(HandlerConstants.SESSION_JIT_DATA_KEY, JITInfo); } - /*** - * Initialize JIT configurations - * @return boolean true when successful initialization, otherwise false - * @throws JITProvisionException throws when error occurred - */ - private boolean initializeJITConfigurations() throws JITProvisionException { + private void loadServiceProviders() throws JITProvisionException { + serviceProviders = new ConcurrentHashMap<>(); try { - Element serviceProvider = tenantConfigs.get(tenantDomain); - if (serviceProvider == null) { - File JITConfigurationFile = new File(JITConfigurationPath); - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - Document JITConfigurationDoc = documentBuilder.parse(JITConfigurationFile); - JITConfigurationDoc.getDocumentElement().normalize(); - serviceProvider = findServiceProvider(tenantDomain, JITConfigurationDoc); - if (serviceProvider == null) return false; - tenantConfigs.put(tenantDomain, serviceProvider); + File JITConfigurationFile = new File(JITConfigurationPath); + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + Document JITConfigurationDoc = documentBuilder.parse(JITConfigurationFile); + JITConfigurationDoc.getDocumentElement().normalize(); + NodeList serviceProviderConfiguration = JITConfigurationDoc.getElementsByTagName("ServiceProvider"); + for (int idx = 0; idx < serviceProviderConfiguration.getLength(); idx++) { + Node configNode = serviceProviderConfiguration.item(idx); + if (configNode.getNodeType() == Node.ELEMENT_NODE) { + Element configElement = (Element) configNode; + ServiceProvider serviceProvider = new ServiceProvider(); + serviceProvider.setTenantDomain(configElement.getAttributes().getNamedItem("tenantDomain"). + getNodeValue()); + serviceProvider.setName(configElement.getAttributes().getNamedItem("name").getNodeValue()); + serviceProvider.setClientId(configElement.getElementsByTagName("ClientId").item(0). + getTextContent()); + serviceProvider.setClientSecret(configElement.getElementsByTagName("ClientSecret").item(0). + getTextContent()); + ServiceProvider.WhiteLabel whiteLabel = new ServiceProvider.WhiteLabel(configElement.getElementsByTagName("DisplayName").item(0). + getTextContent(), configElement.getElementsByTagName("IconUrl").item(0). + getTextContent()); + whiteLabel.setTenantDomain(serviceProvider.getTenantDomain()); + whiteLabel.setName(serviceProvider.getName()); + serviceProvider.setWhiteLabel(whiteLabel); + String spKey = serviceProvider.getName() + "@" + serviceProvider.getTenantDomain(); + serviceProviders.putIfAbsent(spKey, serviceProvider); + } } - clientId = serviceProvider.getElementsByTagName("ClientId").item(0).getTextContent(); - String clientSecret = serviceProvider.getElementsByTagName("ClientSecret").item(0).getTextContent(); - String headerValue = clientId + ":" + clientSecret; - encodedClientCredentials = Base64.getEncoder().encodeToString(headerValue.getBytes()); - return true; } catch (ParserConfigurationException ex) { String msg = "Error occurred when document builder creating the file configuration"; throw new JITProvisionException(msg, ex); @@ -195,4 +236,20 @@ public class JITProvisionHandler extends HttpServlet { throw new JITProvisionException(msg, ex); } } + + /*** + * Initialize JIT configurations + * @return boolean true when successful initialization, otherwise false + */ + private boolean initializeJITConfigurations() { + ServiceProvider serviceProvider = serviceProviders.get(JITServiceProviderName + "@" + tenantDomain); + if (serviceProvider == null) { + return false; + } + clientId = serviceProvider.getClientId(); + clientSecret = serviceProvider.getClientSecret(); + String headerValue = clientId + ":" + clientSecret; + encodedClientCredentials = Base64.getEncoder().encodeToString(headerValue.getBytes()); + return true; + } } 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 78fb91f7ae..5caedbb8ba 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 @@ -130,12 +130,16 @@ public class SsoLoginHandler extends HttpServlet { String loginCallbackUrl = iotsCoreUrl + baseContextPath + HandlerConstants.SSO_LOGIN_CALLBACK; persistAuthSessionData(req, oAuthApp.getClientId(), oAuthApp.getClientSecret(), oAuthApp.getEncodedClientApp(), scopesSsoString, state); + JsonObject ssoConfigurations = uiConfigJsonObject.getAsJsonObject("ssoConfiguration"); + JsonArray authEndpointExtraQueryParam = ssoConfigurations.getAsJsonArray("authEndpointExtraQueryParam"); + String extraParamString = HandlerUtil.getAuthEndpointExtraQueryParamString(authEndpointExtraQueryParam); resp.sendRedirect(keyManagerUrl + HandlerConstants.AUTHORIZATION_ENDPOINT + "?response_type=code" + "&state=" + state + "&client_id=" + clientId + "&scope=openid " + scopesSsoString + - "&redirect_uri=" + loginCallbackUrl); + "&redirect_uri=" + loginCallbackUrl + + extraParamString); } catch (IOException e) { log.error("Error occurred while sending the response into the socket. ", e); } catch (JsonSyntaxException 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/beans/JITData.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/beans/JITData.java index 0e5f1769e7..ec21418f6f 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/beans/JITData.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/beans/JITData.java @@ -25,6 +25,9 @@ public class JITData { private String redirectUrl; private String sp; private String encodedClientCredentials; + private String clientId; + private String clientSecret; + private String applicationUrl; public String getUsername() { return username; @@ -65,4 +68,28 @@ public class JITData { public void setEncodedClientCredentials(String encodedClientCredentials) { this.encodedClientCredentials = encodedClientCredentials; } + + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getClientSecret() { + return clientSecret; + } + + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } + + public String getApplicationUrl() { + return applicationUrl; + } + + public void setApplicationUrl(String applicationUrl) { + this.applicationUrl = applicationUrl; + } } 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/beans/ServiceProvider.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/beans/ServiceProvider.java new file mode 100644 index 0000000000..2f35e7d122 --- /dev/null +++ b/components/ui-request-interceptor/io.entgra.device.mgt.core.ui.request.interceptor/src/main/java/io/entgra/device/mgt/core/ui/request/interceptor/beans/ServiceProvider.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2018 - 2024, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.ui.request.interceptor.beans; + +public class ServiceProvider { + private String tenantDomain; + private String name; + private String clientId; + private String clientSecret; + private WhiteLabel whiteLabel; + + public String getTenantDomain() { + return tenantDomain; + } + + public void setTenantDomain(String tenantDomain) { + this.tenantDomain = tenantDomain; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getClientId() { + return clientId; + } + + public void setClientId(String clientId) { + this.clientId = clientId; + } + + public String getClientSecret() { + return clientSecret; + } + + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } + + public WhiteLabel getWhiteLabel() { + return whiteLabel; + } + + public void setWhiteLabel(WhiteLabel whiteLabel) { + this.whiteLabel = whiteLabel; + } + + public static class WhiteLabel { + private String displayName; + private String iconUrl; + private String tenantDomain; + private String name; + + public WhiteLabel(String displayName, String iconUrl) { + this.displayName = displayName; + this.iconUrl = iconUrl; + } + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public String getIconUrl() { + return iconUrl; + } + + public void setIconUrl(String iconUrl) { + this.iconUrl = iconUrl; + } + + public String getTenantDomain() { + return tenantDomain; + } + + public void setTenantDomain(String tenantDomain) { + this.tenantDomain = tenantDomain; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } +} 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/util/HandlerConstants.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/util/HandlerConstants.java index d38b9942d3..f398c8deea 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/util/HandlerConstants.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/util/HandlerConstants.java @@ -108,6 +108,7 @@ public class HandlerConstants { public static final String USER_SCOPES = "userScopes"; public static final String HUBSPOT_CHAT_URL = "api.hubapi.com"; public static final String USERNAME_WITH_DOMAIN = "usernameWithDomain"; + public static final String API_DOMAIN_PREFIX = "apiDomainPrefix"; public static final String JIT_PROVISION_CALLBACK_URL = "/jit-provision-callback"; public static final String JIT_ENROLLMENT_HANDLER_CALLBACK_URL = "/jit-enrollment-callback"; public static final String DCR_URL = "/client-registration/v0.17/register"; 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/util/HandlerUtil.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/util/HandlerUtil.java index 0d991c8693..4047a7479c 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/util/HandlerUtil.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/util/HandlerUtil.java @@ -799,4 +799,18 @@ public class HandlerUtil { public static String generateStateToken() { return new BigInteger(130, new SecureRandom()).toString(32); } + + public static String getAuthEndpointExtraQueryParamString(JsonArray extraQueryParams) { + StringBuilder stringBuilder = new StringBuilder(); + if (extraQueryParams != null && extraQueryParams.size() > 0) { + for (JsonElement param : extraQueryParams) { + if (param.isJsonObject()) { + JsonObject paramObj = param.getAsJsonObject(); + stringBuilder.append("&").append(paramObj.get("queryParam").getAsString()).append("="). + append(paramObj.get("paramValue").getAsString()); + } + } + } + return stringBuilder.toString(); + } } diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/jit-config.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/jit-config.xml index 1b72287a08..9c455ebb1c 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/jit-config.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/jit-config.xml @@ -39,6 +39,8 @@ \ No newline at end of file diff --git a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml index da4191cff2..9293499104 100644 --- a/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml +++ b/features/device-mgt/io.entgra.device.mgt.core.device.mgt.basics.feature/src/main/resources/conf/mdm-ui-config.xml @@ -429,6 +429,16 @@ device-mgt + + + idpAvailability + false + + + idpLoginProviderEndpoint + https://localhost:9443/enroll-web-agent/idp/login + +