Add JWT support

remotes/1725333865317989910/tmp_refs/heads/master
Dharmakeerthi Lasantha 1 year ago
parent 82b7513c01
commit bfaeb1778f

@ -55,6 +55,11 @@ public interface APIManagementProviderService {
boolean isAllowedAllDomains, boolean isAllowedAllDomains,
String validityTime, String password) throws APIManagerException; String validityTime, String password) throws APIManagerException;
ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String[] tags,
String keyType,
boolean isAllowedAllDomains,
String validityTime, String accessToken) throws APIManagerException;
/** /**
* Remove APIM Application. * Remove APIM Application.
*/ */

@ -114,6 +114,138 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
} }
@Override
public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String[] tags,
String keyType,
boolean isAllowedAllDomains,
String validityTime, String accessToken) throws APIManagerException {
ConsumerRESTAPIServices consumerRESTAPIServices =
APIApplicationManagerExtensionDataHolder.getInstance().getConsumerRESTAPIServices();
try {
List<APIInfo> uniqueApiList = new ArrayList<>();
Map<String, String> headerParams = new HashMap<>();
if (!"carbon.super".equals(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true))) {
headerParams.put("X-WSO2-Tenant", "carbon.super");
}
for (String tag : tags) {
Map<String, String> queryParams = new HashMap<>();
queryParams.put("tag", tag);
APIInfo[] apiInfos = consumerRESTAPIServices.getAllApis(null, accessToken, queryParams, headerParams);
uniqueApiList.addAll(List.of(apiInfos));
Set<APIInfo> taggedAPISet = new HashSet<>(uniqueApiList);
uniqueApiList.clear();
uniqueApiList.addAll(taggedAPISet);
}
io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application[] applications =
consumerRESTAPIServices.getAllApplications(null, accessToken, applicationName);
io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application;
boolean isNewApplication = false;
if (applications.length == 0) {
isNewApplication = true;
application = new io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application();
application.setName(applicationName);
application = consumerRESTAPIServices.createApplication(null, accessToken, application);
addSubscriptions(application, uniqueApiList, accessToken);
} else {
if (applications.length == 1) {
Optional<io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application> applicationOpt =
Arrays.stream(applications).findFirst();
application = applicationOpt.get();
Subscription[] subscriptions = consumerRESTAPIServices.getAllSubscriptions(null, accessToken,
application.getApplicationId());
Arrays.stream(subscriptions).map(Subscription::getApiInfo).forEachOrdered(uniqueApiList::remove);
addSubscriptions(application, uniqueApiList, accessToken);
} else {
String msg = "Found more than one application for application name: " + applicationName;
log.error(msg);
throw new APIManagerException(msg);
}
}
MetadataManagementService metadataManagementService = APIApplicationManagerExtensionDataHolder.getInstance().getMetadataManagementService();
if (isNewApplication) {
KeyManager[] keyManagers = consumerRESTAPIServices.getAllKeyManagers(null, accessToken);
KeyManager keyManager;
if (keyManagers.length == 1) {
keyManager = keyManagers[0];
} else {
String msg =
"Found invalid number of key managers. No of key managers found from the APIM: " + keyManagers.length;
throw new APIManagerException(msg);
}
ApplicationKey applicationKey = consumerRESTAPIServices.generateApplicationKeys(null, accessToken,
application.getApplicationId(), keyManager.getName(), keyType, validityTime);
ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey());
apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret());
Metadata metaData = new Metadata();
metaData.setMetaKey(applicationName);
String metaValue = application.getApplicationId() + ":" + applicationKey.getKeyMappingId();
metaData.setMetaValue(metaValue);
try {
metadataManagementService.createMetadata(metaData);
return apiApplicationKey;
} catch (MetadataManagementException e) {
String msg = "Error occurred while creating the meta data entry for mata key: " + applicationName;
log.error(msg, e);
throw new APIManagerException(msg, e);
} catch (MetadataKeyAlreadyExistsException e) {
String msg = "Found duplicate meta value entry for meta key: " + applicationName;
log.error(msg, e);
throw new APIManagerException(msg, e);
}
} else {
try {
Metadata metaData = metadataManagementService.retrieveMetadata(applicationName);
if (metaData == null) {
String msg = "Couldn't find application key data from meta data mgt service. Meta key: "
+ applicationName;
log.error(msg);
throw new APIManagerException(msg);
}
String[] metaValues = metaData.getMetaValue().split(":");
if (metaValues.length != 2) {
String msg = "Found invalid Meta value for meta key: " + applicationName + ". Meta Value: "
+ metaData.getMetaValue();
log.error(msg);
throw new APIManagerException(msg);
}
String applicationId = metaValues[0];
String keyMappingId = metaValues[1];
ApplicationKey applicationKey = consumerRESTAPIServices.getKeyDetails(null, accessToken, applicationId,
keyMappingId);
ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey());
apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret());
return apiApplicationKey;
} catch (MetadataManagementException e) {
String msg = "Error occurred while getting meta data for meta key: " + applicationName;
log.error(msg, e);
throw new APIManagerException(msg, e);
}
}
} catch (APIServicesException e) {
String msg = "Error occurred while processing the response of APIM REST endpoints.";
log.error(msg, e);
throw new APIManagerException(msg, e);
} catch (BadRequestException e) {
String msg = "Provided incorrect payload when invoking APIM REST endpoints.";
log.error(msg, e);
throw new APIManagerException(msg, e);
} catch (UnexpectedResponseException e) {
String msg = "Error occurred while invoking APIM REST endpoints.";
log.error(msg, e);
throw new APIManagerException(msg, e);
}
}
@Override @Override
public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String[] tags, public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String[] tags,
String keyType, String username, String keyType, String username,
@ -278,6 +410,23 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
consumerRESTAPIServices.createSubscriptions(apiApplicationInfo, null, subscriptionList); consumerRESTAPIServices.createSubscriptions(apiApplicationInfo, null, subscriptionList);
} }
private void addSubscriptions(
io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application application,
List<APIInfo> apiInfos, String accessToken)
throws BadRequestException, UnexpectedResponseException, APIServicesException {
ConsumerRESTAPIServices consumerRESTAPIServices =
APIApplicationManagerExtensionDataHolder.getInstance().getConsumerRESTAPIServices();
List<Subscription> subscriptionList = new ArrayList<>();
apiInfos.forEach(apiInfo -> {
Subscription subscription = new Subscription();
subscription.setApiId(apiInfo.getId());
subscription.setApplicationId(application.getApplicationId());
subscriptionList.add(subscription);
});
consumerRESTAPIServices.createSubscriptions(null, accessToken, subscriptionList);
}
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */

@ -27,6 +27,7 @@ import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtExcepti
import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService; import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtService;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtServiceImpl; import io.entgra.device.mgt.core.apimgt.keymgt.extension.service.KeyMgtServiceImpl;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.UnAuthorizedException; import io.entgra.device.mgt.core.device.mgt.common.exceptions.UnAuthorizedException;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import javax.ws.rs.*; import javax.ws.rs.*;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
@ -47,7 +48,8 @@ public class KeyManagerServiceImpl implements KeyManagerService {
KeyMgtService keyMgtService = new KeyMgtServiceImpl(); KeyMgtService keyMgtService = new KeyMgtServiceImpl();
//todo lasantha - can pass password from here - modify DCRRequest object //todo lasantha - can pass password from here - modify DCRRequest object
DCRResponse resp = keyMgtService.dynamicClientRegistration(dcrRequest.getApplicationName(), dcrRequest.getUsername(), DCRResponse resp = keyMgtService.dynamicClientRegistration(dcrRequest.getApplicationName(), dcrRequest.getUsername(),
dcrRequest.getGrantTypes(), dcrRequest.getCallBackUrl(), dcrRequest.getTags(), dcrRequest.getIsSaasApp(), dcrRequest.getValidityPeriod()); dcrRequest.getGrantTypes(), dcrRequest.getCallBackUrl(), dcrRequest.getTags(),
dcrRequest.getIsSaasApp(), dcrRequest.getValidityPeriod(), dcrRequest.getPassword());
return Response.status(Response.Status.CREATED).entity(gson.toJson(resp)).build(); return Response.status(Response.Status.CREATED).entity(gson.toJson(resp)).build();
} catch (KeyMgtException e) { } catch (KeyMgtException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();

@ -35,11 +35,12 @@ public interface KeyMgtService {
* @param callBackUrl callback url of the application * @param callBackUrl callback url of the application
* @param tags api tags for api subscription of the application * @param tags api tags for api subscription of the application
* @param isSaasApp if the application is a saas app * @param isSaasApp if the application is a saas app
* @param password Password of the owner
* @return @{@link DCRResponse} DCR Response object with client credentials * @return @{@link DCRResponse} DCR Response object with client credentials
* @throws KeyMgtException if any error occurs during DCR process * @throws KeyMgtException if any error occurs during DCR process
*/ */
DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl, DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl,
String[] tags, boolean isSaasApp, int validityPeriod) throws KeyMgtException; String[] tags, boolean isSaasApp, int validityPeriod, String password) throws KeyMgtException;
/*** /***
* This method will handle the access token requests * This method will handle the access token requests

@ -19,9 +19,13 @@
package io.entgra.device.mgt.core.apimgt.keymgt.extension.service; package io.entgra.device.mgt.core.apimgt.keymgt.extension.service;
import com.google.gson.Gson; import com.google.gson.Gson;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.*; import io.entgra.device.mgt.core.apimgt.keymgt.extension.*;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.BadRequestException; import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.BadRequestException;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtException; import io.entgra.device.mgt.core.apimgt.keymgt.extension.exception.KeyMgtException;
import io.entgra.device.mgt.core.apimgt.keymgt.extension.internal.KeyMgtDataHolder;
import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceConfigurationManager;
import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig; import io.entgra.device.mgt.core.device.mgt.core.config.DeviceManagementConfig;
import io.entgra.device.mgt.core.device.mgt.core.config.keymanager.KeyManagerConfigurations; import io.entgra.device.mgt.core.device.mgt.core.config.keymanager.KeyManagerConfigurations;
@ -62,7 +66,7 @@ public class KeyMgtServiceImpl implements KeyMgtService {
String subTenantUserUsername, subTenantUserPassword, keyManagerName, msg = null; String subTenantUserUsername, subTenantUserPassword, keyManagerName, msg = null;
public DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl, public DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl,
String[] tags, boolean isSaasApp, int validityPeriod) throws KeyMgtException { String[] tags, boolean isSaasApp, int validityPeriod, String password) throws KeyMgtException {
if (owner == null) { if (owner == null) {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
@ -90,13 +94,14 @@ public class KeyMgtServiceImpl implements KeyMgtService {
kmConfig = getKeyManagerConfig(); kmConfig = getKeyManagerConfig();
if (KeyMgtConstants.SUPER_TENANT.equals(tenantDomain)) { if (KeyMgtConstants.SUPER_TENANT.equals(tenantDomain)) {
OAuthApplication dcrApplication = createOauthApplication(clientName, kmConfig.getAdminUsername(), tags, validityPeriod); OAuthApplication dcrApplication = createOauthApplication(clientName, kmConfig.getAdminUsername(), tags,
validityPeriod, kmConfig.getAdminPassword());
return new DCRResponse(dcrApplication.getClientId(), dcrApplication.getClientSecret()); return new DCRResponse(dcrApplication.getClientId(), dcrApplication.getClientSecret());
} else { } else {
// super-tenant admin dcr and token generation // super-tenant admin dcr and token generation
OAuthApplication superTenantOauthApp = createOauthApplication( OAuthApplication superTenantOauthApp = createOauthApplication(
KeyMgtConstants.RESERVED_OAUTH_APP_NAME_PREFIX + KeyMgtConstants.SUPER_TENANT, KeyMgtConstants.RESERVED_OAUTH_APP_NAME_PREFIX + KeyMgtConstants.SUPER_TENANT,
kmConfig.getAdminUsername(), null, validityPeriod); kmConfig.getAdminUsername(), null, validityPeriod, kmConfig.getAdminPassword());
String superAdminAccessToken = createAccessToken(superTenantOauthApp); String superAdminAccessToken = createAccessToken(superTenantOauthApp);
// create new key manager for the tenant, under super-tenant space // create new key manager for the tenant, under super-tenant space
@ -119,7 +124,7 @@ public class KeyMgtServiceImpl implements KeyMgtService {
// DCR for the requesting user // DCR for the requesting user
//todo lasantha -> need to pass password of user //todo lasantha -> need to pass password of user
OAuthApplication dcrApplication = createOauthApplication(clientName, owner, tags, validityPeriod); OAuthApplication dcrApplication = createOauthApplication(clientName, owner, tags, validityPeriod, password);
String requestingUserAccessToken = createAccessToken(dcrApplication); String requestingUserAccessToken = createAccessToken(dcrApplication);
// get application id // get application id
@ -311,14 +316,16 @@ public class KeyMgtServiceImpl implements KeyMgtService {
* @return @{@link OAuthApplication} OAuth application object * @return @{@link OAuthApplication} OAuth application object
* @throws KeyMgtException if any error occurs while creating response object * @throws KeyMgtException if any error occurs while creating response object
*/ */
private OAuthApplication createOauthApplication (String clientName, String owner, String[] tags, int validityPeriod) throws KeyMgtException { private OAuthApplication createOauthApplication (String clientName, String owner, String[] tags,
int validityPeriod, String ownerPassword) throws KeyMgtException {
//todo modify this to pass the password as well //todo modify this to pass the password as well
String oauthAppCreationPayloadStr = createOauthAppCreationPayload(clientName, owner, tags, validityPeriod); String oauthAppCreationPayloadStr = createOauthAppCreationPayload(clientName, owner, tags, validityPeriod, ownerPassword);
RequestBody oauthAppCreationPayload = RequestBody.Companion.create(oauthAppCreationPayloadStr, JSON); RequestBody oauthAppCreationPayload = RequestBody.Companion.create(oauthAppCreationPayloadStr, JSON);
kmConfig = getKeyManagerConfig(); kmConfig = getKeyManagerConfig();
String dcrEndpoint = kmConfig.getServerUrl() + KeyMgtConstants.DCR_ENDPOINT; String dcrEndpoint = kmConfig.getServerUrl() + KeyMgtConstants.DCR_ENDPOINT;
String username, password; String username, password;
//todo why can't we use owner details here?
if (KeyMgtConstants.SUPER_TENANT.equals(MultitenantUtils.getTenantDomain(owner))) { if (KeyMgtConstants.SUPER_TENANT.equals(MultitenantUtils.getTenantDomain(owner))) {
username = kmConfig.getAdminUsername(); username = kmConfig.getAdminUsername();
password = kmConfig.getAdminPassword(); password = kmConfig.getAdminPassword();
@ -327,6 +334,7 @@ public class KeyMgtServiceImpl implements KeyMgtService {
password = subTenantUserPassword; password = subTenantUserPassword;
} }
//todo why can't we use owner details for authentication
Request request = new Request.Builder() Request request = new Request.Builder()
.url(dcrEndpoint) .url(dcrEndpoint)
.addHeader(KeyMgtConstants.AUTHORIZATION_HEADER, Credentials.basic(username, password)) .addHeader(KeyMgtConstants.AUTHORIZATION_HEADER, Credentials.basic(username, password))
@ -420,27 +428,46 @@ public class KeyMgtServiceImpl implements KeyMgtService {
* @return @{@link Application} Application object * @return @{@link Application} Application object
* @throws KeyMgtException if any error occurs while retrieving the application * @throws KeyMgtException if any error occurs while retrieving the application
*/ */
private Application getApplication(String applicationName, String owner) throws KeyMgtException { private Application getApplication(String applicationName, String accessToken) throws KeyMgtException {
try { try {
APIManagerFactory apiManagerFactory = APIManagerFactory.getInstance(); APIManagerFactory apiManagerFactory = APIManagerFactory.getInstance();
APIConsumer apiConsumer = apiManagerFactory.getAPIConsumer(owner); // APIConsumer apiConsumer = apiManagerFactory.getAPIConsumer(owner);
ConsumerRESTAPIServices consumerRESTAPIServices =
KeyMgtDataHolder.getInstance().getConsumerRESTAPIServices();
io.entgra.device.mgt.core.apimgt.extension.rest.api.bean.APIMConsumer.Application[] applications =
consumerRESTAPIServices.getAllApplications(null, accessToken, applicationName);
//todo map Application and return
//todo modify the method signature and use access token and call REST API to get application data //todo modify the method signature and use access token and call REST API to get application data
return null; // todo:apim - apiConsumer.getApplicationsByName(owner, applicationName, ""); return null; // todo:apim - apiConsumer.getApplicationsByName(owner, applicationName, "");
// // curl -k -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" "https://localhost:9443/api/am/devportal/v3/applications?query=CalculatorApp" // // curl -k -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8" "https://localhost:9443/api/am/devportal/v3/applications?query=CalculatorApp"
} catch (APIManagementException e) { }
msg = "Error while trying to retrieve the application";
log.error(msg); // catch (APIManagementException e) {
throw new KeyMgtException(msg); // msg = "Error while trying to retrieve the application";
// log.error(msg);
// throw new KeyMgtException(msg);
// }
catch (io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException e) {
e.printStackTrace();
throw new KeyMgtException("");
} catch (UnexpectedResponseException e) {
throw new KeyMgtException("");
} catch (APIServicesException e) {
throw new KeyMgtException("");
} }
} }
private String createOauthAppCreationPayload(String clientName, String owner, String[] tags, int validityPeriod) { private String createOauthAppCreationPayload(String clientName, String owner, String[] tags, int validityPeriod,
String password) {
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put("applicationName", clientName); jsonObject.put("applicationName", clientName);
jsonObject.put("username", owner); jsonObject.put("username", owner);
jsonObject.put("tags", tags); jsonObject.put("tags", tags);
jsonObject.put("validityPeriod", validityPeriod); jsonObject.put("validityPeriod", validityPeriod);
jsonObject.put("password", password);
return jsonObject.toString(); return jsonObject.toString();
} }

@ -802,37 +802,40 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
KeyMgtService keyMgtService = new KeyMgtServiceImpl(); KeyMgtService keyMgtService = new KeyMgtServiceImpl();
try { try {
//todo - lasantha - can't get password from here //todo - lasantha - can't get password from here
ApiApplicationKey apiApplicationKey = null;
try { try {
// DCRResponse dcrResponse = keyMgtService.dynamicClientRegistration(applicationName, username, DCRResponse adminDCRResponse = keyMgtService.dynamicClientRegistration(applicationName,
// "client_credentials", null, new String[] {"device_management"}, false, validityTime); PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
// deviceConfig.setClientId(dcrResponse.getClientId()); .getRealmConfiguration().getAdminUserName(),
// deviceConfig.setClientSecret(dcrResponse.getClientSecret()); "client_credentials", null, new String[] {"device_management"}, false, validityTime, PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
.getRealmConfiguration().getAdminPassword());
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
JWTClientManagerService jwtClientManagerService = (JWTClientManagerService) ctx. JWTClientManagerService jwtClientManagerService = (JWTClientManagerService) ctx.
getOSGiService(JWTClientManagerService.class, null); getOSGiService(JWTClientManagerService.class, null);
JWTClient jwtClient = jwtClientManagerService.getJWTClient(); JWTClient jwtClient = jwtClientManagerService.getJWTClient();
// AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(), AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(adminDCRResponse.getClientId(),
// apiApplicationKey.getConsumerSecret(), adminDCRResponse.getClientSecret(),
// username, Constants.ApplicationInstall.SUBSCRIPTION_SCOPE); username, "appm:subscribe");
APIManagementProviderService apiManagementProviderService = DeviceMgtAPIUtils.getAPIManagementService();
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(applicationName,
new String[] {"device_management"}, null, false, String.valueOf(validityTime),
accessTokenInfo.getAccessToken());
} catch (JWTClientException e) { } catch (JWTClientException e) {
String msg = "Error while generating an OAuth token for user " + username; String msg = "Error while generating an application tokens for Tenant Admin.";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (UserStoreException e) {
String msg = "Error while getting user credentials.";
log.error(msg, e); log.error(msg, e);
return Response.serverError().entity( return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} }
//todo call REST APIs //todo call REST APIs
DCRResponse dcrResponse = keyMgtService.dynamicClientRegistration(applicationName, username,
"client_credentials", null, new String[] {"device_management"}, false, validityTime);
deviceConfig.setClientId(dcrResponse.getClientId());
deviceConfig.setClientSecret(dcrResponse.getClientSecret());
APIManagementProviderService apiManagementProviderService = new APIManagementProviderServiceImpl();
ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(applicationName,
new String[] {"device_management"}, null, username, false, String.valueOf(validityTime), null);
deviceConfig.setClientId(apiApplicationKey.getConsumerKey()); deviceConfig.setClientId(apiApplicationKey.getConsumerKey());
deviceConfig.setClientSecret(apiApplicationKey.getConsumerSecret()); deviceConfig.setClientSecret(apiApplicationKey.getConsumerSecret());
@ -852,7 +855,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
// add scopes for update operation /tenantDomain/deviceType/deviceId/update/operation // add scopes for update operation /tenantDomain/deviceType/deviceId/update/operation
scopes.append(" perm:topic:pub:" + tenantDomain + ":" + type + ":" + id + ":update:operation"); scopes.append(" perm:topic:pub:" + tenantDomain + ":" + type + ":" + id + ":update:operation");
TokenRequest tokenRequest = new TokenRequest(dcrResponse.getClientId(), dcrResponse.getClientSecret(), TokenRequest tokenRequest = new TokenRequest(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(),
null, scopes.toString(), "client_credentials", null, null, scopes.toString(), "client_credentials", null,
null, null, null, validityTime); null, null, null, validityTime);
TokenResponse tokenResponse = keyMgtService.generateAccessToken(tokenRequest); TokenResponse tokenResponse = keyMgtService.generateAccessToken(tokenRequest);

@ -18,6 +18,7 @@
package io.entgra.device.mgt.core.device.mgt.api.jaxrs.util; package io.entgra.device.mgt.core.device.mgt.api.jaxrs.util;
import io.entgra.device.mgt.core.apimgt.application.extension.APIManagementProviderService;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.ConsumerRESTAPIServices;
import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager; import io.entgra.device.mgt.core.application.mgt.common.services.ApplicationManager;
import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager; import io.entgra.device.mgt.core.application.mgt.common.services.SubscriptionManager;
@ -156,6 +157,7 @@ public class DeviceMgtAPIUtils {
private static volatile SubscriptionManager subscriptionManager; private static volatile SubscriptionManager subscriptionManager;
private static volatile ApplicationManager applicationManager; private static volatile ApplicationManager applicationManager;
private static volatile ConsumerRESTAPIServices consumerRESTAPIServices; private static volatile ConsumerRESTAPIServices consumerRESTAPIServices;
private static volatile APIManagementProviderService apiManagementProviderService;
static { static {
String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password"); String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password");
@ -408,6 +410,25 @@ public class DeviceMgtAPIUtils {
return consumerRESTAPIServices; return consumerRESTAPIServices;
} }
/**
* Initializing and accessing method for API management Provider Service.
*
* @return APIManagementProviderService instance
* @throws IllegalStateException if APIManagementProviderService cannot be initialized
*/
public static synchronized APIManagementProviderService getAPIManagementService() {
if (apiManagementProviderService == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
apiManagementProviderService = (APIManagementProviderService) ctx.getOSGiService(APIManagementProviderService.class, null);
if (apiManagementProviderService == null) {
String msg = "API Management Provider service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
}
return apiManagementProviderService;
}
public static RegistryService getRegistryService() { public static RegistryService getRegistryService() {
RegistryService registryService; RegistryService registryService;
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();

Loading…
Cancel
Save