Search in sources :

Example 61 with Property

use of org.wso2.carbon.governance.custom.lifecycles.checklist.util.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 62 with Property

use of org.wso2.carbon.governance.custom.lifecycles.checklist.util.Property in project carbon-apimgt by wso2.

the class EntitlementClientUtils method loadConfigProperties.

/**
 * reads values from config property file
 *
 * @throws APIManagementException throws, if fails
 */
public static void loadConfigProperties() throws APIManagementException {
    Properties properties = new Properties();
    InputStream inputStream = null;
    try {
        File file = new File((new File(".")).getCanonicalPath() + File.separator + "resources" + File.separator + "config.properties");
        if (file.exists()) {
            inputStream = new FileInputStream(file);
        } else {
            String msg = "File does not exist : " + "config.properties";
            logger.error(msg);
        }
        try {
            if (inputStream != null) {
                properties.load(inputStream);
                configProperties = properties;
            }
        } catch (IOException e) {
            String msg = "Error loading properties from config.properties file";
            logger.error(msg, e);
            throw new APIManagementException(msg, e);
        }
    } catch (FileNotFoundException e) {
        String msg = "File can not be found : " + "config.properties";
        logger.error(msg, e);
        throw new APIManagementException(msg, e);
    } catch (IOException e) {
        String msg = "Can not create the canonical file path for given file : " + "config.properties";
        logger.error(msg, e);
        throw new APIManagementException(msg, e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Properties(java.util.Properties)

Example 63 with Property

use of org.wso2.carbon.governance.custom.lifecycles.checklist.util.Property 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)

Example 64 with Property

use of org.wso2.carbon.governance.custom.lifecycles.checklist.util.Property in project carbon-apimgt by wso2.

the class SecurityConfigContextTest method testSecurityConfigContextForAPIProduct.

@Test
public void testSecurityConfigContextForAPIProduct() throws Exception {
    APIProduct apiProduct = new APIProduct(new APIProductIdentifier("admin", "TestProduct", "1.0.0"));
    apiProduct.setUuid(UUID.randomUUID().toString());
    String apiid = UUID.randomUUID().toString();
    List<APIProductResource> apiProductResourceList = new ArrayList<>();
    APIProductResource apiProductResource = new APIProductResource();
    apiProductResource.setApiIdentifier(new APIIdentifier("admin_api1_v1"));
    apiProductResource.setApiId(apiid);
    Map<String, EndpointSecurity> endpointSecurityMap = new HashMap<>();
    EndpointSecurity endpointSecurity = new EndpointSecurity();
    endpointSecurity.setType("BASIC");
    endpointSecurity.setUsername("admin");
    endpointSecurity.setPassword("admin123");
    endpointSecurity.setEnabled(true);
    endpointSecurityMap.put("production", endpointSecurity);
    apiProductResource.setApiId(apiid);
    apiProductResource.setEndpointSecurityMap(endpointSecurityMap);
    apiProductResourceList.add(apiProductResource);
    apiProduct.setProductResources(apiProductResourceList);
    ConfigContext configcontext = new APIConfigContext(apiProduct);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.API_SECUREVAULT_ENABLE)).thenReturn("true");
    Map<String, APIDTO> apidtoMap = new HashMap<>();
    apidtoMap.put(apiid, new APIDTO().name("api1").version("v1").provider("admin"));
    SecurityConfigContext securityConfigContext = new SecurityConfigContextWrapper(configcontext, apiProduct, apiManagerConfiguration, apidtoMap);
    securityConfigContext.validate();
    VelocityContext velocityContext = securityConfigContext.getContext();
    Assert.assertNotNull(velocityContext.get("endpoint_security"));
    Map<String, Map<String, EndpointSecurityModel>> endpointSecurityModelMap = (Map<String, Map<String, EndpointSecurityModel>>) velocityContext.get("endpoint_security");
    Map<String, EndpointSecurityModel> endpointSecurityModelMap1 = endpointSecurityModelMap.get(apiProductResource.getApiId());
    EndpointSecurityModel production = endpointSecurityModelMap1.get("production");
    Assert.assertTrue("Property enabled cannot be false.", production.isEnabled());
    Assert.assertTrue("Property type cannot be other.", production.getType().equalsIgnoreCase("basic"));
    Assert.assertTrue("Property username does not match.", "admin".equals(production.getUsername()));
    Assert.assertTrue("Property base64value does not match. ", new String(Base64.encodeBase64("admin:admin123".getBytes())).equalsIgnoreCase(production.getBase64EncodedPassword()));
    Assert.assertTrue("Property securevault_alias does not match.", "TestProduct--v1.0.0--api1--vv1--production".equalsIgnoreCase(production.getAlias()));
    Assert.assertTrue("Property isSecureVaultEnabled cannot be false. ", velocityContext.get("isSecureVaultEnabled").equals(true));
}
Also used : SecurityConfigContext(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.SecurityConfigContext) HashMap(java.util.HashMap) VelocityContext(org.apache.velocity.VelocityContext) ArrayList(java.util.ArrayList) EndpointSecurity(org.wso2.carbon.apimgt.api.model.EndpointSecurity) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) EndpointSecurityModel(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.EndpointSecurityModel) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) HashMap(java.util.HashMap) Map(java.util.Map) APIConfigContext(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.APIConfigContext) ConfigContext(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.ConfigContext) SecurityConfigContext(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.SecurityConfigContext) APIConfigContext(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.APIConfigContext) Test(org.junit.Test)

Example 65 with Property

use of org.wso2.carbon.governance.custom.lifecycles.checklist.util.Property in project carbon-apimgt by wso2.

the class SecurityConfigContextTest method testSecurityConfigContextPerEndpointBothType.

@Test
public void testSecurityConfigContextPerEndpointBothType() throws Exception {
    String json = "{\"endpoint_security\":{\n" + "  \"production\":{\n" + "    \"enabled\":true,\n" + "    \"type\":\"BASIC\",\n" + "    \"username\":\"admin\",\n" + "    \"password\":\"admin123#QA\"\n" + "  },\n" + "  \"sandbox\":{\n" + "    \"enabled\":true,\n" + "    \"type\":\"DIGEST\",\n" + "    \"username\":\"admin\",\n" + "    \"password\":\"admin123\"\n" + "  }\n" + "  }\n" + "}";
    API api = new API(new APIIdentifier("admin", "TestAPI", "1.0.0"));
    api.setStatus(APIConstants.CREATED);
    api.setContextTemplate("/");
    api.setTransports(Constants.TRANSPORT_HTTP);
    api.setEndpointConfig(json);
    ConfigContext configcontext = new APIConfigContext(api);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.API_SECUREVAULT_ENABLE)).thenReturn("true");
    SecurityConfigContext securityConfigContext = new SecurityConfigContextWrapper(configcontext, api, apiManagerConfiguration);
    securityConfigContext.validate();
    VelocityContext velocityContext = securityConfigContext.getContext();
    Assert.assertNotNull(velocityContext.get("endpoint_security"));
    Map<String, EndpointSecurityModel> endpointSecurityModelMap = (Map<String, EndpointSecurityModel>) velocityContext.get("endpoint_security");
    EndpointSecurityModel production = endpointSecurityModelMap.get("production");
    Assert.assertTrue("Property enabled cannot be false.", production.isEnabled());
    Assert.assertTrue("Property type cannot be other.", production.getType().equalsIgnoreCase("basic"));
    Assert.assertTrue("Property username does not match.", "admin".equals(production.getUsername()));
    Assert.assertTrue("Property base64value does not match. ", new String(Base64.encodeBase64("admin:admin123#QA".getBytes())).equalsIgnoreCase(production.getBase64EncodedPassword()));
    Assert.assertTrue("Property securevault_alias does not match.", "TestAPI--v1.0.0--production".equalsIgnoreCase(production.getAlias()));
    EndpointSecurityModel sandbox = endpointSecurityModelMap.get("sandbox");
    Assert.assertTrue("Property enabled cannot be false.", sandbox.isEnabled());
    Assert.assertTrue("Property type cannot be other.", sandbox.getType().equalsIgnoreCase("digest"));
    Assert.assertTrue("Property username does not match.", "admin".equals(sandbox.getUsername()));
    Assert.assertTrue("Property base64value does not match. ", new String(Base64.encodeBase64("admin:admin123".getBytes())).equalsIgnoreCase(sandbox.getBase64EncodedPassword()));
    Assert.assertTrue("Property securevault_alias does not match.", "TestAPI--v1.0.0--sandbox".equalsIgnoreCase(sandbox.getAlias()));
    Assert.assertTrue("Property isSecureVaultEnabled cannot be false. ", velocityContext.get("isSecureVaultEnabled").equals(true));
}
Also used : SecurityConfigContext(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.SecurityConfigContext) VelocityContext(org.apache.velocity.VelocityContext) EndpointSecurityModel(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.EndpointSecurityModel) API(org.wso2.carbon.apimgt.api.model.API) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) HashMap(java.util.HashMap) Map(java.util.Map) APIConfigContext(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.APIConfigContext) ConfigContext(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.ConfigContext) SecurityConfigContext(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.SecurityConfigContext) APIConfigContext(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.APIConfigContext) Test(org.junit.Test)

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