use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.
the class RestApiUtil method registerOAuthApplication.
public static OAuthApplicationInfo registerOAuthApplication(OAuthAppRequest appRequest) {
// Create Oauth Application - Dynamic client registration service
AMDefaultKeyManagerImpl impl = new AMDefaultKeyManagerImpl();
OAuthApplicationInfo returnedAPP = null;
try {
returnedAPP = impl.createApplication(appRequest);
} catch (APIManagementException e) {
log.error("Cannot create OAuth application from provided information, for APP name: " + appRequest.getOAuthApplicationInfo().getClientName(), e);
}
return returnedAPP;
}
use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.
the class ApplicationsApiServiceImpl method applicationsImportPost.
/**
* Import an Application which has been exported to a zip file
*
* @param fileInputStream Content stream of the zip file which contains exported Application
* @param fileDetail Meta information of the zip file
* @param preserveOwner If true, preserve the original owner of the application
* @param skipSubscriptions If true, skip subscriptions of the application
* @param appOwner Target owner of the application
* @param skipApplicationKeys Skip application keys while importing
* @param update Update if existing application found or import
* @param messageContext Message Context
* @return imported Application
*/
@Override
public Response applicationsImportPost(InputStream fileInputStream, Attachment fileDetail, Boolean preserveOwner, Boolean skipSubscriptions, String appOwner, Boolean skipApplicationKeys, Boolean update, MessageContext messageContext) throws APIManagementException {
String ownerId;
Application application;
try {
String username = RestApiCommonUtil.getLoggedInUsername();
APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
String extractedFolderPath = CommonUtil.getArchivePathOfExtractedDirectory(fileInputStream, ImportExportConstants.UPLOAD_APPLICATION_FILE_NAME);
String jsonContent = ImportUtils.getApplicationDefinitionAsJson(extractedFolderPath);
// Retrieving the field "data" in api.yaml/json and convert it to a JSON object for further processing
JsonElement configElement = new JsonParser().parse(jsonContent).getAsJsonObject().get(APIConstants.DATA);
ExportedApplication exportedApplication = new Gson().fromJson(configElement, ExportedApplication.class);
// Retrieve the application DTO object from the aggregated exported application
ApplicationDTO applicationDTO = exportedApplication.getApplicationInfo();
if (!StringUtils.isBlank(appOwner)) {
ownerId = appOwner;
} else if (preserveOwner != null && preserveOwner) {
ownerId = applicationDTO.getOwner();
} else {
ownerId = username;
}
if (!MultitenantUtils.getTenantDomain(ownerId).equals(MultitenantUtils.getTenantDomain(username))) {
throw new APIManagementException("Cross Tenant Imports are not allowed", ExceptionCodes.TENANT_MISMATCH);
}
String applicationGroupId = String.join(",", applicationDTO.getGroups());
if (applicationDTO.getGroups() != null && applicationDTO.getGroups().size() > 0) {
ImportUtils.validateOwner(username, applicationGroupId, apiConsumer);
}
String organization = RestApiUtil.getValidatedOrganization(messageContext);
if (APIUtil.isApplicationExist(ownerId, applicationDTO.getName(), applicationGroupId, organization) && update != null && update) {
int appId = APIUtil.getApplicationId(applicationDTO.getName(), ownerId);
Application oldApplication = apiConsumer.getApplicationById(appId);
application = preProcessAndUpdateApplication(ownerId, applicationDTO, oldApplication, oldApplication.getUUID());
} else {
application = preProcessAndAddApplication(ownerId, applicationDTO, organization);
update = Boolean.FALSE;
}
List<APIIdentifier> skippedAPIs = new ArrayList<>();
if (skipSubscriptions == null || !skipSubscriptions) {
skippedAPIs = ImportUtils.importSubscriptions(exportedApplication.getSubscribedAPIs(), ownerId, application, update, apiConsumer, organization);
}
Application importedApplication = apiConsumer.getApplicationById(application.getId());
importedApplication.setOwner(ownerId);
ApplicationInfoDTO importedApplicationDTO = ApplicationMappingUtil.fromApplicationToInfoDTO(importedApplication);
URI location = new URI(RestApiConstants.RESOURCE_PATH_APPLICATIONS + "/" + importedApplicationDTO.getApplicationId());
// check whether keys need to be skipped while import
if (skipApplicationKeys == null || !skipApplicationKeys) {
// if this is an update, old keys will be removed and the OAuth app will be overridden with new values
if (update) {
if (applicationDTO.getKeys().size() > 0 && importedApplication.getKeys().size() > 0) {
importedApplication.getKeys().clear();
}
}
// Add application keys if present and keys does not exists in the current application
if (applicationDTO.getKeys().size() > 0 && importedApplication.getKeys().size() == 0) {
for (ApplicationKeyDTO applicationKeyDTO : applicationDTO.getKeys()) {
ImportUtils.addApplicationKey(ownerId, importedApplication, applicationKeyDTO, apiConsumer, update);
}
}
}
if (skippedAPIs.isEmpty()) {
return Response.created(location).entity(importedApplicationDTO).build();
} else {
APIInfoListDTO skippedAPIListDTO = APIInfoMappingUtil.fromAPIInfoListToDTO(skippedAPIs);
return Response.created(location).status(207).entity(skippedAPIListDTO).build();
}
} catch (URISyntaxException | UserStoreException | APIImportExportException e) {
throw new APIManagementException("Error while importing Application", e);
} catch (UnsupportedEncodingException e) {
throw new APIManagementException("Error while Decoding apiId", e);
} catch (IOException e) {
throw new APIManagementException("Error while reading the application definition", e);
}
}
use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.
the class APIControllerUtil method handleEndpointSecurityConfigs.
/**
* This method will be used to add Endpoint security related environment parameters to imported Api object.
*
* @param envParams Env params object with required parameters
* @param endpointConfig Endpoint config object to be updated
* @throws APIManagementException If an error occurs when setting security env parameters
*/
private static void handleEndpointSecurityConfigs(JsonObject envParams, JsonObject endpointConfig) throws APIManagementException {
// If the user has set (either true or false) the enabled field under security in the params file,
// the following code should be executed.
JsonObject security = envParams.getAsJsonObject(ImportExportConstants.ENDPOINT_SECURITY_FIELD);
if (security == null) {
return;
}
String[] endpointTypes = { APIConstants.ENDPOINT_SECURITY_PRODUCTION, APIConstants.ENDPOINT_SECURITY_SANDBOX };
for (String endpointType : endpointTypes) {
if (security.has(endpointType)) {
JsonObject endpointSecurityDetails = security.get(endpointType).getAsJsonObject();
if (endpointSecurityDetails.has(APIConstants.ENDPOINT_SECURITY_ENABLED) && (endpointSecurityDetails.get(APIConstants.ENDPOINT_SECURITY_ENABLED) != null || !endpointSecurityDetails.get(APIConstants.ENDPOINT_SECURITY_ENABLED).isJsonNull())) {
boolean securityEnabled = endpointSecurityDetails.get(APIConstants.ENDPOINT_SECURITY_ENABLED).getAsBoolean();
// Set endpoint security details to API
if (securityEnabled) {
String endpointSecurityType;
if (endpointSecurityDetails.has(APIConstants.ENDPOINT_SECURITY_TYPE) && (endpointSecurityDetails.get(APIConstants.ENDPOINT_SECURITY_TYPE) != null || !endpointSecurityDetails.get(APIConstants.ENDPOINT_SECURITY_TYPE).isJsonNull())) {
// Check whether the type is defined in the params file
JsonElement type = endpointSecurityDetails.get(APIConstants.ENDPOINT_SECURITY_TYPE);
endpointSecurityType = type.getAsString();
} else {
throw new APIManagementException("You have enabled endpoint security but the type is not found " + "in the params file. Please specify type field and continue...", ExceptionCodes.ERROR_READING_PARAMS_FILE);
}
// Setup security type (basic, digest or oauth)
endpointSecurityDetails.remove(APIConstants.ENDPOINT_SECURITY_TYPE);
if (StringUtils.equals(endpointSecurityType.toLowerCase(), APIConstants.ENDPOINT_SECURITY_TYPE_DIGEST)) {
endpointSecurityDetails.addProperty(APIConstants.ENDPOINT_SECURITY_TYPE, APIConstants.ENDPOINT_SECURITY_TYPE_DIGEST.toUpperCase());
validateEndpointSecurityUsernamePassword(endpointSecurityDetails);
} else if (StringUtils.equals(endpointSecurityType.toLowerCase(), APIConstants.ENDPOINT_SECURITY_TYPE_BASIC)) {
endpointSecurityDetails.addProperty(APIConstants.ENDPOINT_SECURITY_TYPE, APIConstants.ENDPOINT_SECURITY_TYPE_BASIC.toUpperCase());
validateEndpointSecurityUsernamePassword(endpointSecurityDetails);
} else if (StringUtils.equals(endpointSecurityType.toLowerCase(), APIConstants.ENDPOINT_SECURITY_TYPE_OAUTH)) {
endpointSecurityDetails.addProperty(APIConstants.ENDPOINT_SECURITY_TYPE, APIConstants.ENDPOINT_SECURITY_TYPE_OAUTH.toUpperCase());
validateEndpointSecurityOauth(endpointSecurityDetails);
} else {
// If the type is not either basic or digest, return an error
throw new APIManagementException("Invalid endpoint security type found in the params file. " + "Should be either basic, digest or oauth. " + "Please specify correct security types field and continue...", ExceptionCodes.ERROR_READING_PARAMS_FILE);
}
} else {
endpointSecurityDetails.addProperty(APIConstants.ENDPOINT_SECURITY_TYPE, ImportExportConstants.ENDPOINT_NONE_SECURITY_TYPE);
}
}
} else {
// Even though the security field is defined, if either production/sandbox is not defined
// under that,set endpoint security to none. Otherwise the security will be blank if you
// check from the UI.
JsonObject endpointSecurityForNotDefinedEndpointType = new JsonObject();
endpointSecurityForNotDefinedEndpointType.addProperty(APIConstants.ENDPOINT_SECURITY_TYPE, ImportExportConstants.ENDPOINT_NONE_SECURITY_TYPE);
endpointSecurityForNotDefinedEndpointType.addProperty(APIConstants.ENDPOINT_SECURITY_ENABLED, Boolean.FALSE);
security.add(endpointType, endpointSecurityForNotDefinedEndpointType);
}
}
endpointConfig.add(APIConstants.ENDPOINT_SECURITY, security);
}
use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.
the class RegistrationServiceImpl method getExistingApp.
/**
* Retrieve the existing application of given name
*
* @param applicationName application name
* @param saasApp value of IsSaasApp attribute of application.
* @return existing Application
*/
private OAuthApplicationInfo getExistingApp(String applicationName, boolean saasApp) {
OAuthApplicationInfo appToReturn = null;
OAuthAdminService oAuthAdminService = new OAuthAdminService();
try {
OAuthConsumerAppDTO consumerAppDTO = oAuthAdminService.getOAuthApplicationDataByAppName(applicationName);
Map<String, String> valueMap = new HashMap<String, String>();
valueMap.put(OAUTH_CLIENT_GRANT, consumerAppDTO.getGrantTypes());
appToReturn = this.fromAppDTOToApplicationInfo(consumerAppDTO.getOauthConsumerKey(), consumerAppDTO.getApplicationName(), consumerAppDTO.getCallbackUrl(), consumerAppDTO.getOauthConsumerSecret(), saasApp, null, valueMap);
} catch (IdentityOAuthAdminException e) {
log.error("error occurred while trying to get OAuth Application data", e);
}
return appToReturn;
}
use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.
the class RegistrationServiceImpl method createApplication.
/**
* Create a new client application
*
* @param appRequest OAuthAppRequest object with client's payload content
* @return created Application
* @throws APIKeyMgtException if failed to create the a new application
*/
private OAuthApplicationInfo createApplication(String applicationName, OAuthAppRequest appRequest, String grantType) throws APIManagementException {
String userName;
OAuthApplicationInfo applicationInfo = appRequest.getOAuthApplicationInfo();
String appName = applicationInfo.getClientName();
String userId = (String) applicationInfo.getParameter(OAUTH_CLIENT_USERNAME);
boolean isTenantFlowStarted = false;
if (userId == null || userId.isEmpty()) {
return null;
}
userName = MultitenantUtils.getTenantAwareUsername(userId);
String tenantDomain = MultitenantUtils.getTenantDomain(userId);
try {
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
isTenantFlowStarted = true;
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userName);
}
// Creating the service provider
ServiceProvider serviceProvider = new ServiceProvider();
serviceProvider.setApplicationName(applicationName);
serviceProvider.setDescription("Service Provider for application " + appName);
serviceProvider.setSaasApp(applicationInfo.getIsSaasApplication());
ServiceProviderProperty[] serviceProviderProperties = new ServiceProviderProperty[4];
ServiceProviderProperty serviceProviderProperty = new ServiceProviderProperty();
serviceProviderProperty.setName(APP_DISPLAY_NAME);
serviceProviderProperty.setValue(applicationName);
serviceProviderProperties[0] = serviceProviderProperty;
ServiceProviderProperty tokenTypeProviderProperty = new ServiceProviderProperty();
tokenTypeProviderProperty.setName(APIConstants.APP_TOKEN_TYPE);
tokenTypeProviderProperty.setValue(applicationInfo.getTokenType());
serviceProviderProperties[1] = tokenTypeProviderProperty;
ServiceProviderProperty consentProperty = new ServiceProviderProperty();
consentProperty.setDisplayName(APIConstants.APP_SKIP_CONSENT_DISPLAY);
consentProperty.setName(APIConstants.APP_SKIP_CONSENT_NAME);
consentProperty.setValue(APIConstants.APP_SKIP_CONSENT_VALUE);
serviceProviderProperties[2] = consentProperty;
ServiceProviderProperty logoutConsentProperty = new ServiceProviderProperty();
logoutConsentProperty.setDisplayName(APIConstants.APP_SKIP_LOGOUT_CONSENT_DISPLAY);
logoutConsentProperty.setName(APIConstants.APP_SKIP_LOGOUT_CONSENT_NAME);
logoutConsentProperty.setValue(APIConstants.APP_SKIP_LOGOUT_CONSENT_VALUE);
serviceProviderProperties[3] = logoutConsentProperty;
serviceProvider.setSpProperties(serviceProviderProperties);
ApplicationManagementService appMgtService = ApplicationManagementService.getInstance();
appMgtService.createApplication(serviceProvider, tenantDomain, userName);
// Retrieving the created service provider
ServiceProvider createdServiceProvider = appMgtService.getApplicationExcludingFileBasedSPs(applicationName, tenantDomain);
if (createdServiceProvider == null) {
throw new APIManagementException("Error occurred while creating Service Provider " + "Application" + appName);
}
// creating the OAuth app
OAuthConsumerAppDTO createdOauthApp = this.createOAuthApp(applicationName, applicationInfo, grantType, userName);
// Set the OAuthApp in InboundAuthenticationConfig
InboundAuthenticationConfig inboundAuthenticationConfig = new InboundAuthenticationConfig();
InboundAuthenticationRequestConfig[] inboundAuthenticationRequestConfigs = new InboundAuthenticationRequestConfig[1];
InboundAuthenticationRequestConfig inboundAuthenticationRequestConfig = new InboundAuthenticationRequestConfig();
String oAuthType = APIConstants.SWAGGER_12_OAUTH2;
inboundAuthenticationRequestConfig.setInboundAuthType(oAuthType);
inboundAuthenticationRequestConfig.setInboundAuthKey(createdOauthApp.getOauthConsumerKey());
String oauthConsumerSecret = createdOauthApp.getOauthConsumerSecret();
if (oauthConsumerSecret != null && !oauthConsumerSecret.isEmpty()) {
Property property = new Property();
property.setName(ApplicationConstants.INBOUNT_AUTH_CONSUMER_SECRET);
property.setValue(oauthConsumerSecret);
Property[] properties = { property };
inboundAuthenticationRequestConfig.setProperties(properties);
}
inboundAuthenticationRequestConfigs[0] = inboundAuthenticationRequestConfig;
inboundAuthenticationConfig.setInboundAuthenticationRequestConfigs(inboundAuthenticationRequestConfigs);
createdServiceProvider.setInboundAuthenticationConfig(inboundAuthenticationConfig);
// Setting the SaasApplication attribute to created service provider
createdServiceProvider.setSaasApp(applicationInfo.getIsSaasApplication());
createdServiceProvider.setSpProperties(serviceProviderProperties);
// Updating the service provider with Inbound Authentication Configs and SaasApplication
appMgtService.updateApplication(createdServiceProvider, tenantDomain, userName);
Map<String, String> valueMap = new HashMap<String, String>();
valueMap.put(OAUTH_REDIRECT_URIS, createdOauthApp.getCallbackUrl());
valueMap.put(OAUTH_CLIENT_NAME, createdOauthApp.getApplicationName());
valueMap.put(OAUTH_CLIENT_GRANT, createdOauthApp.getGrantTypes());
return this.fromAppDTOToApplicationInfo(createdOauthApp.getOauthConsumerKey(), applicationName, createdOauthApp.getCallbackUrl(), createdOauthApp.getOauthConsumerSecret(), createdServiceProvider.isSaasApp(), userId, valueMap);
} catch (IdentityApplicationManagementException e) {
log.error("Error occurred while creating the client application " + appName, e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.getThreadLocalCarbonContext().endTenantFlow();
}
}
return null;
}
Aggregations