Search in sources :

Example 36 with OAuth

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;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) AMDefaultKeyManagerImpl(org.wso2.carbon.apimgt.impl.AMDefaultKeyManagerImpl)

Example 37 with OAuth

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);
    }
}
Also used : ApplicationDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationDTO) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) ApplicationInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationInfoDTO) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApplicationKeyDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO) JsonElement(com.google.gson.JsonElement) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application) APIInfoListDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIInfoListDTO) JsonParser(com.google.gson.JsonParser)

Example 38 with OAuth

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);
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonElement(com.google.gson.JsonElement) JsonObject(com.google.gson.JsonObject)

Example 39 with OAuth

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;
}
Also used : IdentityOAuthAdminException(org.wso2.carbon.identity.oauth.IdentityOAuthAdminException) HashMap(java.util.HashMap) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) OAuthAdminService(org.wso2.carbon.identity.oauth.OAuthAdminService) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO)

Example 40 with OAuth

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;
}
Also used : InboundAuthenticationConfig(org.wso2.carbon.identity.application.common.model.InboundAuthenticationConfig) HashMap(java.util.HashMap) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO) InboundAuthenticationRequestConfig(org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) ApplicationManagementService(org.wso2.carbon.identity.application.mgt.ApplicationManagementService) ServiceProviderProperty(org.wso2.carbon.identity.application.common.model.ServiceProviderProperty) ServiceProviderProperty(org.wso2.carbon.identity.application.common.model.ServiceProviderProperty) Property(org.wso2.carbon.identity.application.common.model.Property)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)26 HashMap (java.util.HashMap)18 ArrayList (java.util.ArrayList)14 Test (org.junit.Test)14 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)13 Map (java.util.Map)11 JSONObject (org.json.simple.JSONObject)9 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)9 OAuthApplicationInfo (org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo)9 JsonObject (com.google.gson.JsonObject)8 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)8 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)8 TokenResponse (org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse)8 LinkedHashMap (java.util.LinkedHashMap)6 Test (org.testng.annotations.Test)6 IOException (java.io.IOException)5 ParseException (org.json.simple.parser.ParseException)5 OAuthAppRequest (org.wso2.carbon.apimgt.api.model.OAuthAppRequest)5 MultiEnvironmentOverview (org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview)5 APIMAppConfigurations (org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations)5