Add oauth token handling client

publisher-oauth-client-v5.2.3
Rajitha Kumara 1 month ago
parent 5f94113adf
commit 4d06dfd4d4

@ -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;
}

@ -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;
}
}
}

@ -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<APIRevisionDeployment> apiRevisionDeploymentList)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean deployAPIRevision(String uuid, String apiRevisionId,
List<APIRevisionDeployment> 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;
}

@ -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;
}
}

@ -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;
}
}

@ -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);
}
}

@ -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);

@ -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;
}

@ -0,0 +1,203 @@
/*
* 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.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.*;
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<String, PublisherOauthApp> publisherOauthAppCache = new ConcurrentHashMap<>();
private static final APIManagerConfiguration config = ServiceReferenceHolder.getInstance().
getAPIManagerConfigurationService().getAPIManagerConfiguration();
public static PublisherRESTAPIClientResponse execute(Request request) throws PublisherRESTAPIOauthClientException
, BadRequestException,
UnexpectedResponseException {
try {
request = addAuthorizationHeader(request);
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
return map(response);
}
if (response.code() == HttpStatus.SC_UNAUTHORIZED) {
updateCacheWithNewToken();
return execute(addAuthorizationHeader(request));
} else if (HttpStatus.SC_BAD_REQUEST == response.code()) {
String msg = "Encountered a bad request! Request 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 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);
}
}
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) {
if (APIConstants.SUPER_TENANT_DOMAIN.equals(tenantDomain)) {
return config.getFirstProperty(Constants.SERVER_USER);
} else {
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());
}
}

@ -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;
@ -158,9 +149,6 @@ public class APIPublisherServiceImpl implements APIPublisherService {
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);
@ -174,7 +162,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 +177,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 +185,14 @@ public class APIPublisherServiceImpl implements APIPublisherService {
List<String> 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 +202,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 +218,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
List<APIRevisionDeployment> 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 +241,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 +254,19 @@ public class APIPublisherServiceImpl implements APIPublisherService {
List<String> 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 +276,18 @@ public class APIPublisherServiceImpl implements APIPublisherService {
List<String> 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 +299,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 +337,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 +347,10 @@ public class APIPublisherServiceImpl implements APIPublisherService {
List<APIRevisionDeployment> 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 +380,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);
}
@ -461,7 +426,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) {
@ -470,16 +434,10 @@ public class APIPublisherServiceImpl implements APIPublisherService {
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<String> bindings = new ArrayList<>(
@ -489,7 +447,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) {
@ -511,12 +469,8 @@ public class APIPublisherServiceImpl implements APIPublisherService {
WebappPublisherConfig config = WebappPublisherConfig.getInstance();
List<String> 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;
@ -526,9 +480,6 @@ public class APIPublisherServiceImpl implements APIPublisherService {
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);
@ -599,7 +550,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 +562,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);
@ -661,15 +612,10 @@ 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);
@ -678,14 +624,14 @@ public class APIPublisherServiceImpl implements APIPublisherService {
try {
Scope[] scopeList = publisherRESTAPIServices.getScopes(apiApplicationKey, accessTokenInfo);
Scope[] scopeList = publisherRESTAPIServices.getScopes();
Map<String, String> 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 {
@ -717,17 +663,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<String, String> permScopeMap, boolean removingPermissions )
private void updateScopes (String roleName, PublisherRESTAPIServices publisherRESTAPIServices, Scope[] scopeList, String[] permissions, Map<String, String> permScopeMap, boolean removingPermissions )
throws APIManagerPublisherException {
for (String permission : permissions) {
String scopeValue = permScopeMap.get(permission);
@ -765,8 +707,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");

@ -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<APIConfig> unpublishedApis = new Stack<>();
private Map<String, String> 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;
}

@ -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");

@ -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<DeviceType, DeviceStatusTaskPluginConfig> 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

@ -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,18 +159,11 @@ 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);
@ -183,14 +172,14 @@ public class TenantCreateObserver extends AbstractAxis2ConfigurationContextObser
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 +219,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 +249,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 +264,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 {
@ -367,15 +353,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 +367,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 +380,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<Scope> scopeList, PublisherRESTAPIServices publisherRESTAPIServices,
APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo)
private void publishSharedScopes (List<Scope> 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);
}
}
}

Loading…
Cancel
Save