use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO in project carbon-apimgt by wso2.
the class ApplicationsApiServiceImpl method applicationsApplicationIdOauthKeysKeyMappingIdRegenerateSecretPost.
@Override
public Response applicationsApplicationIdOauthKeysKeyMappingIdRegenerateSecretPost(String applicationId, String keyMappingId, MessageContext messageContext) throws APIManagementException {
String username = RestApiCommonUtil.getLoggedInUsername();
Set<APIKey> applicationKeys = getApplicationKeys(applicationId);
if (applicationKeys == null) {
return null;
}
ApplicationKeyDTO applicationKeyDTO = getApplicationKeyByAppIDAndKeyMapping(applicationId, keyMappingId);
if (applicationKeyDTO != null) {
APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
String clientId = applicationKeyDTO.getConsumerKey();
String clientSecret = apiConsumer.renewConsumerSecret(clientId, applicationKeyDTO.getKeyManager());
ApplicationKeyDTO retrievedApplicationKey = new ApplicationKeyDTO();
retrievedApplicationKey.setConsumerKey(clientId);
retrievedApplicationKey.setConsumerSecret(clientSecret);
return Response.ok().entity(retrievedApplicationKey).build();
}
return null;
}
use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO in project carbon-apimgt by wso2.
the class ApplicationsApiServiceImpl method applicationsApplicationIdGenerateKeysPost.
/**
* Generate keys for a application
*
* @param applicationId application identifier
* @param body request body
* @return A response object containing application keys
*/
@Override
public Response applicationsApplicationIdGenerateKeysPost(String applicationId, ApplicationKeyGenerateRequestDTO body, String xWSO2Tenant, MessageContext messageContext) throws APIManagementException {
String username = RestApiCommonUtil.getLoggedInUsername();
try {
APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
Application application = apiConsumer.getApplicationByUUID(applicationId);
if (application != null) {
if (RestAPIStoreUtils.isUserOwnerOfApplication(application)) {
String[] accessAllowDomainsArray = { "ALL" };
JSONObject jsonParamObj = new JSONObject();
jsonParamObj.put(ApplicationConstants.OAUTH_CLIENT_USERNAME, username);
String grantTypes = StringUtils.join(body.getGrantTypesToBeSupported(), ',');
if (!StringUtils.isEmpty(grantTypes)) {
jsonParamObj.put(APIConstants.JSON_GRANT_TYPES, grantTypes);
}
/* Read clientId & clientSecret from ApplicationKeyGenerateRequestDTO object.
User can provide clientId only or both clientId and clientSecret
User cannot provide clientSecret only */
if (!StringUtils.isEmpty(body.getClientId())) {
jsonParamObj.put(APIConstants.JSON_CLIENT_ID, body.getClientId());
if (!StringUtils.isEmpty(body.getClientSecret())) {
jsonParamObj.put(APIConstants.JSON_CLIENT_SECRET, body.getClientSecret());
}
}
if (body.getAdditionalProperties() != null) {
if (body.getAdditionalProperties() instanceof String && StringUtils.isNotEmpty((String) body.getAdditionalProperties())) {
jsonParamObj.put(APIConstants.JSON_ADDITIONAL_PROPERTIES, body.getAdditionalProperties());
} else if (body.getAdditionalProperties() instanceof Map) {
String jsonContent = new Gson().toJson(body.getAdditionalProperties());
jsonParamObj.put(APIConstants.JSON_ADDITIONAL_PROPERTIES, jsonContent);
}
}
String jsonParams = jsonParamObj.toString();
String tokenScopes = StringUtils.join(body.getScopes(), " ");
String keyManagerName = APIConstants.KeyManager.DEFAULT_KEY_MANAGER;
if (StringUtils.isNotEmpty(body.getKeyManager())) {
keyManagerName = body.getKeyManager();
}
String organization = RestApiUtil.getValidatedOrganization(messageContext);
Map<String, Object> keyDetails = apiConsumer.requestApprovalForApplicationRegistration(username, application, body.getKeyType().toString(), body.getCallbackUrl(), accessAllowDomainsArray, body.getValidityTime(), tokenScopes, jsonParams, keyManagerName, organization, false);
ApplicationKeyDTO applicationKeyDTO = ApplicationKeyMappingUtil.fromApplicationKeyToDTO(keyDetails, body.getKeyType().toString());
applicationKeyDTO.setKeyManager(keyManagerName);
return Response.ok().entity(applicationKeyDTO).build();
} else {
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
}
} else {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
}
} catch (EmptyCallbackURLForCodeGrantsException e) {
RestApiUtil.handleBadRequest(e.getMessage(), log);
}
return null;
}
use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO in project carbon-apimgt by wso2.
the class ExportUtils method createApplicationDTOToExport.
/**
* Create an aggregated Application DTO to be exported.
*
* @param application Application{@link Application} to be exported
* @param apiConsumer API Consumer
* @param withKeys Export the Application with keys or not
* @return Exported application
* @throws APIManagementException If an error occurs while retrieving subscribed APIs
*/
private static ExportedApplication createApplicationDTOToExport(Application application, APIConsumer apiConsumer, Boolean withKeys) throws APIManagementException {
ApplicationDTO applicationDto = ApplicationMappingUtil.fromApplicationtoDTO(application);
// Set keys if withKeys is true
if (withKeys == null || !withKeys) {
application.clearOAuthApps();
} else {
List<ApplicationKeyDTO> applicationKeyDTOs = new ArrayList<>();
for (APIKey apiKey : application.getKeys()) {
// Encode the consumer secret and set it
apiKey.setConsumerSecret(new String(Base64.encodeBase64(apiKey.getConsumerSecret().getBytes(Charset.defaultCharset()))));
ApplicationKeyDTO applicationKeyDTO = ApplicationKeyMappingUtil.fromApplicationKeyToDTO(apiKey);
applicationKeyDTOs.add(applicationKeyDTO);
}
applicationDto.setKeys(applicationKeyDTOs);
}
// Get the subscribed API details and add it to a set
Set<SubscribedAPI> subscribedAPIs = apiConsumer.getSubscribedAPIs(application.getSubscriber(), application.getName(), application.getGroupId());
Set<ExportedSubscribedAPI> exportedSubscribedAPIs = new HashSet<>();
for (SubscribedAPI subscribedAPI : subscribedAPIs) {
ExportedSubscribedAPI exportedSubscribedAPI = new ExportedSubscribedAPI(subscribedAPI.getApiId(), subscribedAPI.getSubscriber(), subscribedAPI.getTier().getName());
exportedSubscribedAPIs.add(exportedSubscribedAPI);
}
// Set the subscription count by counting the number of subscribed APIs
applicationDto.setSubscriptionCount(exportedSubscribedAPIs.size());
// Set the application
ExportedApplication exportedApplication = new ExportedApplication(applicationDto);
// Set the subscribed APIs
exportedApplication.setSubscribedAPIs(exportedSubscribedAPIs);
return exportedApplication;
}
use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO in project carbon-apimgt by wso2.
the class ApplicationKeyMappingUtil method fromApplicationKeyToDTO.
/**
* Insert the application related details to a DTO Object
*
* @param keyDetails Application related details map
* @param applicationKeyType Key type of the application
* @return DTO object with application related details
*/
@SuppressWarnings("unchecked")
public static ApplicationKeyDTO fromApplicationKeyToDTO(Map<String, Object> keyDetails, String applicationKeyType) {
ApplicationKeyDTO applicationKeyDTO = new ApplicationKeyDTO();
applicationKeyDTO.setConsumerKey((String) keyDetails.get(APIConstants.FrontEndParameterNames.CONSUMER_KEY));
applicationKeyDTO.setKeyMappingId((String) keyDetails.get(APIConstants.FrontEndParameterNames.KEY_MAPPING_ID));
applicationKeyDTO.setConsumerSecret((String) keyDetails.get(APIConstants.FrontEndParameterNames.CONSUMER_SECRET));
applicationKeyDTO.setKeyState((String) keyDetails.get(APIConstants.FrontEndParameterNames.KEY_STATE));
applicationKeyDTO.setKeyType(ApplicationKeyDTO.KeyTypeEnum.valueOf(applicationKeyType));
Object mode = keyDetails.get(APIConstants.FrontEndParameterNames.MODE);
if (mode != null) {
applicationKeyDTO.setMode(ApplicationKeyDTO.ModeEnum.valueOf((String) mode));
}
try {
String appDetailsString = (String) keyDetails.get(ApplicationConstants.OAUTH_APP_DETAILS);
if (appDetailsString != null) {
JSONObject appDetailsJsonObj = (JSONObject) new JSONParser().parse(appDetailsString);
if (appDetailsJsonObj != null) {
String supportedGrantTypes = (String) appDetailsJsonObj.get(ApplicationConstants.OAUTH_CLIENT_GRANT);
if (supportedGrantTypes != null) {
applicationKeyDTO.setSupportedGrantTypes(Arrays.asList(supportedGrantTypes.split(" ")));
}
String callbackUrl = (String) appDetailsJsonObj.get(ApplicationConstants.OAUTH_REDIRECT_URIS);
applicationKeyDTO.setCallbackUrl(callbackUrl);
Object additionalPropertiesObj = appDetailsJsonObj.get(APIConstants.JSON_ADDITIONAL_PROPERTIES);
if (additionalPropertiesObj != null) {
if (additionalPropertiesObj instanceof JSONObject) {
Map additionalPropertiesMap = new HashMap();
additionalPropertiesMap.putAll((Map) additionalPropertiesObj);
applicationKeyDTO.setAdditionalProperties(additionalPropertiesMap);
} else if (additionalPropertiesObj instanceof String) {
applicationKeyDTO.setAdditionalProperties(additionalPropertiesObj);
}
}
}
}
ApplicationTokenDTO tokenDTO = new ApplicationTokenDTO();
tokenDTO.setValidityTime((Long) keyDetails.get(APIConstants.AccessTokenConstants.VALIDITY_TIME));
tokenDTO.setAccessToken((String) keyDetails.get(APIConstants.AccessTokenConstants.ACCESS_TOKEN));
String[] tokenScopes = (String[]) keyDetails.get(APIConstants.AccessTokenConstants.TOKEN_SCOPES);
if (tokenScopes != null) {
tokenDTO.setTokenScopes(Arrays.asList(tokenScopes));
}
applicationKeyDTO.setToken(tokenDTO);
} catch (ParseException e) {
String errorMsg = "Error while parsing application details string";
log.error(errorMsg, e);
throw new InternalServerErrorException(errorMsg, e);
}
return applicationKeyDTO;
}
use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO in project carbon-apimgt by wso2.
the class ApplicationsApiServiceImpl method applicationsApplicationIdKeysKeyTypeGenerateTokenPost.
@Override
public Response applicationsApplicationIdKeysKeyTypeGenerateTokenPost(String applicationId, String keyType, ApplicationTokenGenerateRequestDTO body, String ifMatch, MessageContext messageContext) {
try {
String username = RestApiCommonUtil.getLoggedInUsername();
APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
Application application = apiConsumer.getApplicationByUUID(applicationId);
if (application != null) {
if (RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
ApplicationKeyDTO appKey = getApplicationKeyByAppIDAndKeyType(applicationId, keyType);
if (appKey != null) {
String jsonInput = null;
String grantType;
if (ApplicationTokenGenerateRequestDTO.GrantTypeEnum.TOKEN_EXCHANGE.equals(body.getGrantType())) {
grantType = APIConstants.OAuthConstants.TOKEN_EXCHANGE;
} else {
grantType = APIConstants.GRANT_TYPE_CLIENT_CREDENTIALS;
}
try {
// verify that the provided jsonInput is a valid json
if (body.getAdditionalProperties() != null && !body.getAdditionalProperties().toString().isEmpty()) {
jsonInput = validateAdditionalParameters(grantType, body);
}
} catch (JsonProcessingException | ParseException | ClassCastException e) {
RestApiUtil.handleBadRequest("Error while generating " + keyType + " token for " + "application " + applicationId + ". Invalid jsonInput '" + body.getAdditionalProperties() + "' provided.", log);
}
if (StringUtils.isNotEmpty(body.getConsumerSecret())) {
appKey.setConsumerSecret(body.getConsumerSecret());
}
String[] scopes = body.getScopes().toArray(new String[0]);
AccessTokenInfo response = apiConsumer.renewAccessToken(body.getRevokeToken(), appKey.getConsumerKey(), appKey.getConsumerSecret(), body.getValidityPeriod().toString(), scopes, jsonInput, APIConstants.KeyManager.DEFAULT_KEY_MANAGER, grantType);
ApplicationTokenDTO appToken = new ApplicationTokenDTO();
appToken.setAccessToken(response.getAccessToken());
appToken.setTokenScopes(Arrays.asList(response.getScopes()));
appToken.setValidityTime(response.getValidityPeriod());
return Response.ok().entity(appToken).build();
} else {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APP_CONSUMER_KEY, keyType, log);
}
} else {
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
}
} else {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
}
} catch (APIManagementException e) {
RestApiUtil.handleInternalServerError("Error while generating " + keyType + " token for application " + applicationId, e, log);
}
return null;
}
Aggregations