Search in sources :

Example 46 with Property

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

the class APIUtil method replaceSystemProperty.

/**
 * Resolves system properties and replaces in given in text
 *
 * @param text
 * @return System properties resolved text
 */
public static String replaceSystemProperty(String text) {
    int indexOfStartingChars = -1;
    int indexOfClosingBrace;
    // and are assumed to be System properties
    while (indexOfStartingChars < text.indexOf("${") && (indexOfStartingChars = text.indexOf("${")) != -1 && (indexOfClosingBrace = text.indexOf('}')) != -1) {
        // Is a
        // property
        // used?
        String sysProp = text.substring(indexOfStartingChars + 2, indexOfClosingBrace);
        String propValue = System.getProperty(sysProp);
        if (propValue == null) {
            if ("carbon.context".equals(sysProp)) {
                propValue = ServiceReferenceHolder.getContextService().getServerConfigContext().getContextRoot();
            } else if ("admin.username".equals(sysProp) || "admin.password".equals(sysProp)) {
                try {
                    RealmConfiguration realmConfig = new RealmConfigXMLProcessor().buildRealmConfigurationFromFile();
                    if ("admin.username".equals(sysProp)) {
                        propValue = realmConfig.getAdminUserName();
                    } else {
                        propValue = realmConfig.getAdminPassword();
                    }
                } catch (UserStoreException e) {
                    // Can't throw an exception because the server is
                    // starting and can't be halted.
                    log.error("Unable to build the Realm Configuration", e);
                    return null;
                }
            }
        }
        // Derive original text value with resolved system property value
        if (propValue != null) {
            text = text.substring(0, indexOfStartingChars) + propValue + text.substring(indexOfClosingBrace + 1);
        }
        if ("carbon.home".equals(sysProp) && propValue != null && ".".equals(propValue)) {
            text = new File(".").getAbsolutePath() + File.separator + text;
        }
    }
    return text;
}
Also used : RealmConfiguration(org.wso2.carbon.user.api.RealmConfiguration) RealmConfigXMLProcessor(org.wso2.carbon.user.core.config.RealmConfigXMLProcessor) UserStoreException(org.wso2.carbon.user.api.UserStoreException) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint)

Example 47 with Property

use of org.wso2.carbon.identity.application.common.model.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)

Example 48 with Property

use of org.wso2.carbon.identity.application.common.model.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 49 with Property

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

the class ApisApiServiceImpl method importAsyncAPISpecification.

/**
 * Importing and AsyncAPI Specification and create and API
 *
 * @param fileInputStream InputStream for the provided file
 * @param fileDetail File meta-data
 * @param url URL of the AsyncAPI Specification
 * @param additionalProperties API object (json) including additional properties like name, version, context
 * @param messageContext CXF message context
 * @return API import using AsyncAPI specification response
 */
@Override
public Response importAsyncAPISpecification(InputStream fileInputStream, Attachment fileDetail, String url, String additionalProperties, MessageContext messageContext) throws APIManagementException {
    // validate 'additionalProperties' json
    if (StringUtils.isBlank(additionalProperties)) {
        RestApiUtil.handleBadRequest("'additionalProperties' is required and should not be null", log);
    }
    // Convert the 'additionalProperties' json into an APIDTO object
    ObjectMapper objectMapper = new ObjectMapper();
    APIDTO apiDTOFromProperties;
    try {
        apiDTOFromProperties = objectMapper.readValue(additionalProperties, APIDTO.class);
        if (apiDTOFromProperties.getType() == null) {
            RestApiUtil.handleBadRequest("Required property protocol is not specified for the Async API", log);
        }
    } catch (IOException e) {
        throw RestApiUtil.buildBadRequestException("Error while parsing 'additionalProperties'", e);
    }
    // validate whether ASYNC APIs created without advertise only enabled
    if (APIDTO.TypeEnum.ASYNC.equals(apiDTOFromProperties.getType()) && (apiDTOFromProperties.getAdvertiseInfo() == null || !apiDTOFromProperties.getAdvertiseInfo().isAdvertised())) {
        RestApiUtil.handleBadRequest("ASYNC type APIs only can be created as third party APIs", log);
    }
    // validate websocket url and change transport types
    if (PublisherCommonUtils.isValidWSAPI(apiDTOFromProperties)) {
        ArrayList<String> websocketTransports = new ArrayList<>();
        websocketTransports.add(APIConstants.WS_PROTOCOL);
        websocketTransports.add(APIConstants.WSS_PROTOCOL);
        apiDTOFromProperties.setTransport(websocketTransports);
    }
    // Import the API and Definition
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIDTO createdAPIDTO = importAsyncAPISpecification(fileInputStream, url, apiDTOFromProperties, fileDetail, null, organization);
        URI createdApiUri = new URI(RestApiConstants.RESOURCE_PATH_APIS + "/" + createdAPIDTO.getId());
        return Response.created(createdApiUri).entity(createdAPIDTO).build();
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving API location : " + apiDTOFromProperties.getProvider() + "-" + apiDTOFromProperties.getName() + "-" + apiDTOFromProperties.getVersion();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) ArrayList(java.util.ArrayList) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 50 with Property

use of org.wso2.carbon.identity.application.common.model.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)

Aggregations

HashMap (java.util.HashMap)42 ArrayList (java.util.ArrayList)32 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)32 Resource (org.wso2.carbon.registry.core.Resource)23 Map (java.util.Map)21 Test (org.junit.Test)21 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)21 DataResponse (org.wso2.carbon.bpmn.rest.model.common.DataResponse)17 API (org.wso2.carbon.apimgt.api.model.API)16 UserStoreException (org.wso2.carbon.user.api.UserStoreException)16 Path (javax.ws.rs.Path)14 Produces (javax.ws.rs.Produces)14 JSONObject (org.json.simple.JSONObject)14 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)14 List (java.util.List)13 IOException (java.io.IOException)11 QName (javax.xml.namespace.QName)11 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)11 Properties (java.util.Properties)10 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)10