Search in sources :

Example 41 with Property

use of org.wso2.carbon.identity.application.common.model.idp.xsd.Property in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method createAuditApi.

/**
 * Send API Definition to Security Audit for the first time
 * @param collectionId Collection ID in which the Definition should be sent to
 * @param apiToken API Token to access Security Audit
 * @param apiIdentifier API Identifier object
 * @param apiDefinition API Definition of API
 * @param baseUrl Base URL to communicate with Security Audit
 * @param isDebugEnabled Boolean whether debug is enabled
 * @param organization Organization
 * @return String UUID of API in Security Audit
 * @throws IOException In the event of any problems in the request
 * @throws APIManagementException In the event of unexpected response
 * @throws ParseException In the event of any parse errors from the response
 */
private String createAuditApi(String collectionId, String apiToken, APIIdentifier apiIdentifier, String apiDefinition, String baseUrl, boolean isDebugEnabled, String organization) throws IOException, APIManagementException, ParseException {
    HttpURLConnection httpConn;
    OutputStream outputStream;
    PrintWriter writer;
    String auditUuid = null;
    URL url = new URL(baseUrl);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    // indicates POST method
    httpConn.setDoOutput(true);
    httpConn.setDoInput(true);
    httpConn.setRequestProperty(APIConstants.HEADER_CONTENT_TYPE, APIConstants.MULTIPART_CONTENT_TYPE + APIConstants.MULTIPART_FORM_BOUNDARY);
    httpConn.setRequestProperty(APIConstants.HEADER_ACCEPT, APIConstants.APPLICATION_JSON_MEDIA_TYPE);
    httpConn.setRequestProperty(APIConstants.HEADER_API_TOKEN, apiToken);
    httpConn.setRequestProperty(APIConstants.HEADER_USER_AGENT, APIConstants.USER_AGENT_APIM);
    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8), true);
    // Name property
    writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY).append(APIConstants.MULTIPART_LINE_FEED).append("Content-Disposition: form-data; name=\"name\"").append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.MULTIPART_LINE_FEED).append(apiIdentifier.getApiName()).append(APIConstants.MULTIPART_LINE_FEED);
    writer.flush();
    // Specfile property
    writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY).append(APIConstants.MULTIPART_LINE_FEED).append("Content-Disposition: form-data; name=\"specfile\"; filename=\"swagger.json\"").append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.HEADER_CONTENT_TYPE + ": " + APIConstants.APPLICATION_JSON_MEDIA_TYPE).append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.MULTIPART_LINE_FEED).append(apiDefinition).append(APIConstants.MULTIPART_LINE_FEED);
    writer.flush();
    // CollectionID property
    writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY).append(APIConstants.MULTIPART_LINE_FEED).append("Content-Disposition: form-data; name=\"cid\"").append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.MULTIPART_LINE_FEED).append(collectionId).append(APIConstants.MULTIPART_LINE_FEED);
    writer.flush();
    writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY + "--").append(APIConstants.MULTIPART_LINE_FEED);
    writer.close();
    // Checks server's status code first
    int status = httpConn.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK) {
        if (isDebugEnabled) {
            log.debug("HTTP status " + status);
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), StandardCharsets.UTF_8));
        String inputLine;
        StringBuilder responseString = new StringBuilder();
        while ((inputLine = reader.readLine()) != null) {
            responseString.append(inputLine);
        }
        reader.close();
        httpConn.disconnect();
        JSONObject responseJson = (JSONObject) new JSONParser().parse(responseString.toString());
        auditUuid = (String) ((JSONObject) responseJson.get(APIConstants.DESC)).get(APIConstants.ID);
        ApiMgtDAO.getInstance().addAuditApiMapping(apiIdentifier, auditUuid, organization);
    } else {
        if (httpConn.getErrorStream() != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getErrorStream(), StandardCharsets.UTF_8));
            String inputLine;
            StringBuilder responseString = new StringBuilder();
            while ((inputLine = reader.readLine()) != null) {
                responseString.append(inputLine);
            }
            reader.close();
            httpConn.disconnect();
            JSONObject responseJson = (JSONObject) new JSONParser().parse(responseString.toString());
            String errorMessage = httpConn.getResponseMessage();
            if (responseJson.containsKey("message")) {
                errorMessage = (String) responseJson.get("message");
            }
            throw new APIManagementException("Error while retrieving data for the API Security Audit Report. Found http status: " + httpConn.getResponseCode() + " - " + errorMessage);
        } else {
            throw new APIManagementException("Error while retrieving data for the API Security Audit Report. Found http status: " + httpConn.getResponseCode() + " - " + httpConn.getResponseMessage());
        }
    }
    return auditUuid;
}
Also used : InputStreamReader(java.io.InputStreamReader) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) JSONParser(org.json.simple.parser.JSONParser) PrintWriter(java.io.PrintWriter)

Example 42 with Property

use of org.wso2.carbon.identity.application.common.model.idp.xsd.Property in project carbon-apimgt by wso2.

the class TemplateBuilderUtil method retrieveGatewayAPIDto.

public static GatewayAPIDTO retrieveGatewayAPIDto(API api, Environment environment, String tenantDomain, APIDTO apidto, String extractedFolderPath) throws APIManagementException, XMLStreamException, APITemplateException {
    List<ClientCertificateDTO> clientCertificatesDTOList = ImportUtils.retrieveClientCertificates(extractedFolderPath);
    List<SoapToRestMediationDto> soapToRestInMediationDtoList = ImportUtils.retrieveSoapToRestFlowMediations(extractedFolderPath, ImportUtils.IN);
    List<SoapToRestMediationDto> soapToRestOutMediationDtoList = ImportUtils.retrieveSoapToRestFlowMediations(extractedFolderPath, ImportUtils.OUT);
    JSONObject originalProperties = api.getAdditionalProperties();
    // add new property for entires that has a __display suffix
    JSONObject modifiedProperties = getModifiedProperties(originalProperties);
    api.setAdditionalProperties(modifiedProperties);
    APITemplateBuilder apiTemplateBuilder = TemplateBuilderUtil.getAPITemplateBuilder(api, tenantDomain, clientCertificatesDTOList, soapToRestInMediationDtoList, soapToRestOutMediationDtoList);
    GatewayAPIDTO gatewaAPIDto = createAPIGatewayDTOtoPublishAPI(environment, api, apiTemplateBuilder, tenantDomain, extractedFolderPath, apidto, clientCertificatesDTOList);
    // Reset the additional properties to the original values
    if (originalProperties != null) {
        api.setAdditionalProperties(originalProperties);
    }
    return gatewaAPIDto;
}
Also used : GatewayAPIDTO(org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO) JSONObject(org.json.simple.JSONObject) SoapToRestMediationDto(org.wso2.carbon.apimgt.impl.dto.SoapToRestMediationDto) APITemplateBuilder(org.wso2.carbon.apimgt.impl.template.APITemplateBuilder) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO)

Example 43 with Property

use of org.wso2.carbon.identity.application.common.model.idp.xsd.Property in project carbon-apimgt by wso2.

the class RestApiUtil method handleMigrationSpecificPermissionViolations.

/**
 * Handle if any cross tenant access permission violations detected. Cross tenant resources (apis/apps) can be
 * retrieved only by super tenant admin user, only while a migration process(2.6.0 to 3.0.0). APIM server has to be
 * started with the system property 'migrationMode=true' if a migration related exports are to be done.
 *
 * @param targetTenantDomain Tenant domain of which resources are requested
 * @param username           Logged in user name
 * @throws ForbiddenException
 */
public static void handleMigrationSpecificPermissionViolations(String targetTenantDomain, String username) throws ForbiddenException {
    boolean isCrossTenantAccess = !targetTenantDomain.equals(MultitenantUtils.getTenantDomain(username));
    if (!isCrossTenantAccess) {
        return;
    }
    String superAdminRole = null;
    try {
        superAdminRole = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(MultitenantConstants.SUPER_TENANT_ID).getRealmConfiguration().getAdminRoleName();
    } catch (UserStoreException e) {
        RestApiUtil.handleInternalServerError("Error in getting super admin role name", e, log);
    }
    // check whether logged in user is a super tenant user
    String superTenantDomain = null;
    try {
        superTenantDomain = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getSuperTenantDomain();
    } catch (UserStoreException e) {
        RestApiUtil.handleInternalServerError("Error in getting the super tenant domain", e, log);
    }
    boolean isSuperTenantUser = RestApiCommonUtil.getLoggedInUserTenantDomain().equals(superTenantDomain);
    if (!isSuperTenantUser) {
        String errorMsg = "Cross Tenant resource access is not allowed for this request. User " + username + " is not allowed to access resources in " + targetTenantDomain + " as the requester is not a super " + "tenant user";
        log.error(errorMsg);
        ErrorDTO errorDTO = getErrorDTO(RestApiConstants.STATUS_FORBIDDEN_MESSAGE_DEFAULT, 403l, errorMsg);
        throw new ForbiddenException(errorDTO);
    }
    // check whether the user has super tenant admin role
    boolean isSuperAdminRoleNameExist = false;
    try {
        isSuperAdminRoleNameExist = APIUtil.isUserInRole(username, superAdminRole);
    } catch (UserStoreException | APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error in checking whether the user has admin role", e, log);
    }
    if (!isSuperAdminRoleNameExist) {
        String errorMsg = "Cross Tenant resource access is not allowed for this request. User " + username + " is not allowed to access resources in " + targetTenantDomain + " as the requester is not a " + "super tenant admin";
        log.error(errorMsg);
        ErrorDTO errorDTO = getErrorDTO(RestApiConstants.STATUS_FORBIDDEN_MESSAGE_DEFAULT, 403l, errorMsg);
        throw new ForbiddenException(errorDTO);
    }
}
Also used : ForbiddenException(org.wso2.carbon.apimgt.rest.api.util.exception.ForbiddenException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) UserStoreException(org.wso2.carbon.user.api.UserStoreException)

Example 44 with Property

use of org.wso2.carbon.identity.application.common.model.idp.xsd.Property in project carbon-apimgt by wso2.

the class SettingsMappingUtil method fromSettingstoDTO.

public SettingsDTO fromSettingstoDTO(Boolean isUserAvailable, Boolean moneatizationEnabled, boolean recommendationEnabled, boolean anonymousEnabled, String organization) throws APIManagementException {
    SettingsDTO settingsDTO = new SettingsDTO();
    settingsDTO.setScopes(GetScopeList());
    settingsDTO.setApplicationSharingEnabled(APIUtil.isMultiGroupAppSharingEnabled());
    settingsDTO.setRecommendationEnabled(recommendationEnabled);
    settingsDTO.setMapExistingAuthApps(APIUtil.isMapExistingAuthAppsEnabled());
    settingsDTO.setMonetizationEnabled(moneatizationEnabled);
    SettingsIdentityProviderDTO identityProviderDTO = new SettingsIdentityProviderDTO();
    identityProviderDTO.setExternal(APIUtil.getIdentityProviderConfig() != null);
    settingsDTO.setIdentityProvider(identityProviderDTO);
    settingsDTO.setIsAnonymousModeEnabled(anonymousEnabled);
    APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
    boolean enableChangePassword = Boolean.parseBoolean(config.getFirstProperty(APIConstants.ENABLE_CHANGE_PASSWORD));
    settingsDTO.setIsPasswordChangeEnabled(enableChangePassword);
    String username = RestApiCommonUtil.getLoggedInUsername();
    String tenantDomain = MultitenantUtils.getTenantDomain(username);
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    String userStorePasswordPattern = null;
    String passwordPolicyPattern = null;
    int passwordPolicyMinLength = -1;
    int passwordPolicyMaxLength = -1;
    try {
        // Get password pattern from the UserStoreManager configuration
        RealmConfiguration realmConfiguration = null;
        RealmService realmService = ServiceReferenceHolder.getInstance().getRealmService();
        if (realmService != null && tenantId != MultitenantConstants.INVALID_TENANT_ID) {
            UserStoreManager userStoreManager = null;
            userStoreManager = (UserStoreManager) realmService.getTenantUserRealm(tenantId).getUserStoreManager();
            realmConfiguration = userStoreManager.getRealmConfiguration();
        }
        if (realmConfiguration != null) {
            String passwordJavaRegEx = realmConfiguration.getUserStoreProperty(APIConstants.PASSWORD_JAVA_REGEX_PROPERTY);
            if (passwordJavaRegEx != null && !passwordJavaRegEx.trim().isEmpty()) {
                userStorePasswordPattern = passwordJavaRegEx;
            }
        }
        // Get password pattern from the Password policy
        Property passwordPolicyEnabledProperty = FrameworkUtils.getResidentIdpConfiguration(APIConstants.IS_PASSWORD_POLICY_ENABLED_PROPERTY, tenantDomain);
        boolean isPasswordPolicyEnabled = Boolean.parseBoolean(passwordPolicyEnabledProperty.getValue());
        if (isPasswordPolicyEnabled) {
            passwordPolicyPattern = FrameworkUtils.getResidentIdpConfiguration(APIConstants.PASSWORD_POLICY_PATTERN_PROPERTY, tenantDomain).getValue();
            passwordPolicyMinLength = Integer.parseInt(FrameworkUtils.getResidentIdpConfiguration(APIConstants.PASSWORD_POLICY_MIN_LENGTH_PROPERTY, tenantDomain).getValue());
            passwordPolicyMaxLength = Integer.parseInt(FrameworkUtils.getResidentIdpConfiguration(APIConstants.PASSWORD_POLICY_MAX_LENGTH_PROPERTY, tenantDomain).getValue());
        }
    } catch (UserStoreException e) {
        String errorMessage = "Error occurred in getting userRealm for the tenant: " + tenantId;
        throw new APIManagementException(errorMessage, e);
    } catch (FrameworkException e) {
        String errorMessage = "Error occurred in getting Resident Idp Configurations for tenant: " + tenantId;
        throw new APIManagementException(errorMessage, e);
    }
    settingsDTO.setUserStorePasswordPattern(userStorePasswordPattern);
    settingsDTO.setPasswordPolicyPattern(passwordPolicyPattern);
    settingsDTO.setPasswordPolicyMinLength(passwordPolicyMinLength);
    settingsDTO.setPasswordPolicyMaxLength(passwordPolicyMaxLength);
    if (isUserAvailable) {
        settingsDTO.setGrantTypes(APIUtil.getGrantTypes());
        Map<String, Environment> environments = APIUtil.getEnvironments(organization);
        if (environments.isEmpty()) {
            settingsDTO.apiGatewayEndpoint("http://localhost:8280, https://localhost:8243");
        } else {
            for (Map.Entry<String, Environment> entry : environments.entrySet()) {
                Environment environment = environments.get(entry.getKey());
                if (environment.isDefault()) {
                    settingsDTO.apiGatewayEndpoint(environment.getApiGatewayEndpoint());
                    break;
                }
            }
            if (settingsDTO.getApiGatewayEndpoint() == null) {
                Map.Entry<String, Environment> entry = environments.entrySet().iterator().next();
                Environment environment = environments.get(entry.getKey());
                settingsDTO.apiGatewayEndpoint(environment.getApiGatewayEndpoint());
            }
        }
    }
    return settingsDTO;
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) UserStoreManager(org.wso2.carbon.user.core.UserStoreManager) SettingsIdentityProviderDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.SettingsIdentityProviderDTO) RealmConfiguration(org.wso2.carbon.user.api.RealmConfiguration) SettingsDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.SettingsDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreException(org.wso2.carbon.user.api.UserStoreException) Environment(org.wso2.carbon.apimgt.api.model.Environment) Property(org.wso2.carbon.identity.application.common.model.Property) Map(java.util.Map)

Example 45 with Property

use of org.wso2.carbon.identity.application.common.model.idp.xsd.Property in project carbon-apimgt by wso2.

the class BasicAuthenticationInterceptor method handleMessage.

/**
 * This method handles the incoming message by checking if an anonymous api is being called or invalid
 * authorization headers are present in the request. If not, authenticate the request.
 *
 * @param inMessage cxf Message
 */
@Override
@MethodStats
public void handleMessage(Message inMessage) {
    // by-passes the interceptor if user calls an anonymous api
    if (RestApiUtil.checkIfAnonymousAPI(inMessage)) {
        return;
    }
    String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    inMessage.put(RestApiConstants.TENANT_DOMAIN, tenantDomain);
    // Extract and check if "Authorization: Basic" is present in the request. If not, by-passes the interceptor.
    // If yes, set the request_authentication_scheme property in the message as basic_auth and execute the basic
    // authentication flow.
    AuthorizationPolicy policy = inMessage.get(AuthorizationPolicy.class);
    if (policy != null) {
        inMessage.put(RestApiConstants.REQUEST_AUTHENTICATION_SCHEME, RestApiConstants.BASIC_AUTHENTICATION);
        // Extract user credentials from the auth header and validate.
        String username = StringUtils.trim(policy.getUserName());
        String password = StringUtils.trim(policy.getPassword());
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            String errorMessage = StringUtils.isEmpty(username) ? "username cannot be null/empty." : "password cannot be null/empty.";
            log.error("Basic Authentication failed: " + errorMessage);
            throw new AuthenticationException("Unauthenticated request");
        } else if (!authenticate(inMessage, username, password)) {
            throw new AuthenticationException("Unauthenticated request");
        }
        log.debug("User logged into web app using Basic Authentication");
    }
}
Also used : AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) AuthenticationException(org.apache.cxf.interceptor.security.AuthenticationException) MethodStats(org.wso2.carbon.apimgt.rest.api.util.MethodStats)

Aggregations

ArrayList (java.util.ArrayList)114 HashMap (java.util.HashMap)114 Property (org.wso2.carbon.identity.application.common.model.Property)105 Map (java.util.Map)62 IdentityProviderProperty (org.wso2.carbon.identity.application.common.model.IdentityProviderProperty)50 Test (org.testng.annotations.Test)42 UserStoreException (org.wso2.carbon.user.api.UserStoreException)38 IOException (java.io.IOException)37 Property (org.wso2.carbon.identity.application.common.model.idp.xsd.Property)36 InboundAuthenticationRequestConfig (org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationRequestConfig)33 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)32 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)31 List (java.util.List)30 FederatedAuthenticatorConfig (org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig)29 Resource (org.wso2.carbon.registry.core.Resource)29 IdentityProvider (org.wso2.carbon.identity.application.common.model.IdentityProvider)27 OMElement (org.apache.axiom.om.OMElement)24 PreparedStatement (java.sql.PreparedStatement)23 ProvisioningConnectorConfig (org.wso2.carbon.identity.application.common.model.ProvisioningConnectorConfig)23 Property (org.wso2.carbon.identity.application.common.model.xsd.Property)23