Search in sources :

Example 31 with Property

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

the class DataProcessAndPublishingAgent method run.

public void run() {
    JSONObject jsonObMap = new JSONObject();
    org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    if (ipAddress != null && ipAddress.length() > 0) {
        if (ipAddress.contains(":") && ipAddress.split(":").length == 2) {
            log.warn("Client port will be ignored and only the IP address (IPV4) will concern from " + ipAddress);
            ipAddress = ipAddress.split(":")[0];
        }
        try {
            InetAddress address = APIUtil.getAddress(ipAddress);
            if (address instanceof Inet4Address) {
                jsonObMap.put(APIThrottleConstants.IP, APIUtil.ipToLong(ipAddress));
                jsonObMap.put(APIThrottleConstants.IPv6, 0);
            } else if (address instanceof Inet6Address) {
                jsonObMap.put(APIThrottleConstants.IPv6, APIUtil.ipToBigInteger(ipAddress));
                jsonObMap.put(APIThrottleConstants.IP, 0);
            }
        } catch (UnknownHostException e) {
            // send empty value as ip
            log.error("Error while parsing host IP " + ipAddress, e);
            jsonObMap.put(APIThrottleConstants.IPv6, 0);
            jsonObMap.put(APIThrottleConstants.IP, 0);
        }
    }
    // HeaderMap will only be set if the Header Publishing has been enabled.
    if (getThrottleProperties().isEnableHeaderConditions()) {
        if (this.headersMap != null) {
            jsonObMap.putAll(this.headersMap);
        }
    }
    // adding any custom property if available to stream's property map
    if (this.customPropertyMap != null) {
        jsonObMap.putAll(this.customPropertyMap);
    }
    // Setting query parameters
    if (getThrottleProperties().isEnableQueryParamConditions()) {
        Map<String, String> queryParams = GatewayUtils.getQueryParams(axis2MessageContext);
        if (queryParams != null) {
            jsonObMap.putAll(queryParams);
        }
    }
    // Publish jwt claims
    if (getThrottleProperties().isEnableJwtConditions()) {
        if (authenticationContext.getCallerToken() != null) {
            Map<String, String> assertions = JWTUtil.getJWTClaims(authenticationContext.getCallerToken());
            if (assertions != null) {
                jsonObMap.putAll(assertions);
            }
        }
    }
    // this parameter will be used to capture message size and pass it to calculation logic
    ArrayList<VerbInfoDTO> list = (ArrayList<VerbInfoDTO>) messageContext.getProperty(APIConstants.VERB_INFO_DTO);
    boolean isVerbInfoContentAware = false;
    if (list != null && !list.isEmpty()) {
        VerbInfoDTO verbInfoDTO = list.get(0);
        isVerbInfoContentAware = verbInfoDTO.isContentAware();
    }
    if (authenticationContext.isContentAwareTierPresent() || isVerbInfoContentAware) {
        if (log.isDebugEnabled()) {
            log.debug("Message size: " + messageSizeInBytes + "B");
        }
        jsonObMap.put(APIThrottleConstants.MESSAGE_SIZE, messageSizeInBytes);
        if (!StringUtils.isEmpty(authenticationContext.getApplicationName())) {
            jsonObMap.put(APIThrottleConstants.APPLICATION_NAME, authenticationContext.getApplicationName());
        }
        if (!StringUtils.isEmpty(authenticationContext.getProductName()) && !StringUtils.isEmpty(authenticationContext.getProductProvider())) {
            jsonObMap.put(APIThrottleConstants.SUBSCRIPTION_TYPE, APIConstants.API_PRODUCT_SUBSCRIPTION_TYPE);
        } else {
            jsonObMap.put(APIThrottleConstants.SUBSCRIPTION_TYPE, APIConstants.API_SUBSCRIPTION_TYPE);
        }
    }
    Object[] objects = new Object[] { messageContext.getMessageID(), this.applicationLevelThrottleKey, this.applicationLevelTier, this.apiLevelThrottleKey, this.apiLevelTier, this.subscriptionLevelThrottleKey, this.subscriptionLevelTier, this.resourceLevelThrottleKey, this.resourceLevelTier, this.authorizedUser, this.apiContext, this.apiVersion, this.appTenant, this.apiTenant, this.appId, this.apiName, jsonObMap.toString() };
    org.wso2.carbon.databridge.commons.Event event = new org.wso2.carbon.databridge.commons.Event(streamID, System.currentTimeMillis(), null, null, objects);
    dataPublisher.tryPublish(event);
}
Also used : Inet4Address(java.net.Inet4Address) UnknownHostException(java.net.UnknownHostException) ArrayList(java.util.ArrayList) Inet6Address(java.net.Inet6Address) JSONObject(org.json.simple.JSONObject) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) JSONObject(org.json.simple.JSONObject) InetAddress(java.net.InetAddress) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 32 with Property

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

the class SystemScopesIssuer method getScopes.

/**
 * This method is used to retrieve the authorized scopes with respect to a token.
 *
 * @param tokReqMsgCtx token message context
 * @return authorized scopes list
 */
public List<String> getScopes(OAuthTokenReqMessageContext tokReqMsgCtx) {
    List<String> authorizedScopes = null;
    List<String> requestedScopes = new ArrayList<>(Arrays.asList(tokReqMsgCtx.getScope()));
    String clientId = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId();
    AuthenticatedUser authenticatedUser = tokReqMsgCtx.getAuthorizedUser();
    Map<String, String> appScopes = getAppScopes(clientId, authenticatedUser, requestedScopes);
    if (appScopes != null) {
        // If no scopes can be found in the context of the application
        if (isAppScopesEmpty(appScopes, clientId)) {
            return getAllowedScopes(requestedScopes);
        }
        String grantType = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getGrantType();
        String[] userRoles = null;
        // If GrantType is SAML20_BEARER and CHECK_ROLES_FROM_SAML_ASSERTION is true, or if GrantType is
        // JWT_BEARER and retrieveRolesFromUserStoreForScopeValidation system property is true,
        // use user roles from assertion or jwt otherwise use roles from userstore.
        String isSAML2Enabled = System.getProperty(APIConstants.SystemScopeConstants.CHECK_ROLES_FROM_SAML_ASSERTION);
        String isRetrieveRolesFromUserStoreForScopeValidation = System.getProperty(APIConstants.SystemScopeConstants.RETRIEVE_ROLES_FROM_USERSTORE_FOR_SCOPE_VALIDATION);
        if (GrantType.SAML20_BEARER.toString().equals(grantType) && Boolean.parseBoolean(isSAML2Enabled)) {
            authenticatedUser.setUserStoreDomain("FEDERATED");
            tokReqMsgCtx.setAuthorizedUser(authenticatedUser);
            Assertion assertion = (Assertion) tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.SAML2_ASSERTION);
            userRoles = getRolesFromAssertion(assertion);
        } else if (APIConstants.SystemScopeConstants.OAUTH_JWT_BEARER_GRANT_TYPE.equals(grantType) && !(Boolean.parseBoolean(isRetrieveRolesFromUserStoreForScopeValidation))) {
            configureForJWTGrant(tokReqMsgCtx);
            Map<ClaimMapping, String> userAttributes = authenticatedUser.getUserAttributes();
            if (tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM) != null) {
                userRoles = getRolesFromUserAttribute(userAttributes, tokReqMsgCtx.getProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM).toString());
            }
        } else {
            userRoles = getUserRoles(authenticatedUser);
        }
        authorizedScopes = getAuthorizedScopes(userRoles, requestedScopes, appScopes);
    }
    return authorizedScopes;
}
Also used : Assertion(org.opensaml.saml.saml2.core.Assertion) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Example 33 with Property

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

the class SystemScopesIssuer method validateScope.

@Override
public boolean validateScope(OAuth2TokenValidationMessageContext oAuth2TokenValidationMessageContext) throws IdentityOAuth2Exception {
    AccessTokenDO accessTokenDO = (AccessTokenDO) oAuth2TokenValidationMessageContext.getProperty(ACCESS_TOKEN_DO);
    if (accessTokenDO == null) {
        return false;
    }
    String resource = getResourceFromMessageContext(oAuth2TokenValidationMessageContext);
    // Return true if there is no resource to validate the token against.
    if (resource == null) {
        return true;
    }
    // Get the list of scopes associated with the access token
    String[] scopes = accessTokenDO.getScope();
    // If no scopes are associated with the token
    if (scopes == null || scopes.length == 0) {
        return true;
    }
    String resourceScope = null;
    int resourceTenantId = -1;
    boolean cacheHit = false;
    // Check the cache, if caching is enabled.
    OAuthCacheKey cacheKey = new OAuthCacheKey(resource);
    CacheEntry result = OAuthCache.getInstance().getValueFromCache(cacheKey);
    // Cache hit
    if (result != null && result instanceof ResourceScopeCacheEntry) {
        resourceScope = ((ResourceScopeCacheEntry) result).getScope();
        resourceTenantId = ((ResourceScopeCacheEntry) result).getTenantId();
        cacheHit = true;
    }
    // Cache was not hit. So retrieve from database.
    if (!cacheHit) {
        Pair<String, Integer> scopeMap = OAuthTokenPersistenceFactory.getInstance().getTokenManagementDAO().findTenantAndScopeOfResource(resource);
        if (scopeMap != null) {
            resourceScope = scopeMap.getLeft();
            resourceTenantId = scopeMap.getRight();
        }
        cacheKey = new OAuthCacheKey(resource);
        ResourceScopeCacheEntry cacheEntry = new ResourceScopeCacheEntry(resourceScope);
        cacheEntry.setTenantId(resourceTenantId);
        // Store resourceScope in cache even if it is null (to avoid database calls when accessing resources for
        // which scopes haven't been defined).
        OAuthCache.getInstance().addToCache(cacheKey, cacheEntry);
    }
    // Return TRUE if - There does not exist a scope definition for the resource
    if (resourceScope == null) {
        if (log.isDebugEnabled()) {
            log.debug("Resource '" + resource + "' is not protected with a scope");
        }
        return true;
    }
    List<String> scopeList = new ArrayList<>(Arrays.asList(scopes));
    // If the access token does not bear the scope required for accessing the Resource.
    if (!scopeList.contains(resourceScope)) {
        if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
            log.debug("Access token '" + accessTokenDO.getAccessToken() + "' does not bear the scope '" + resourceScope + "'");
        }
        return false;
    }
    // This system property is set at server start using -D option, Thus will be a permanent property.
    if (accessTokenDO.getAuthzUser().isFederatedUser() && (Boolean.parseBoolean(System.getProperty(CHECK_ROLES_FROM_SAML_ASSERTION)) || !(Boolean.parseBoolean(System.getProperty(RETRIEVE_ROLES_FROM_USERSTORE_FOR_SCOPE_VALIDATION))))) {
        return true;
    }
    AuthenticatedUser authenticatedUser = OAuthUtil.getAuthenticatedUser(oAuth2TokenValidationMessageContext.getResponseDTO().getAuthorizedUser());
    String clientId = accessTokenDO.getConsumerKey();
    List<String> requestedScopes = Arrays.asList(scopes);
    List<String> authorizedScopes = null;
    String[] userRoles = null;
    Map<String, String> appScopes = getAppScopes(clientId, authenticatedUser, requestedScopes);
    if (appScopes != null) {
        // If no scopes can be found in the context of the application
        if (isAppScopesEmpty(appScopes, clientId)) {
            authorizedScopes = getAllowedScopes(requestedScopes);
            oAuth2TokenValidationMessageContext.getResponseDTO().setScope(authorizedScopes.toArray(new String[authorizedScopes.size()]));
            return true;
        }
        userRoles = getUserRoles(authenticatedUser);
        authorizedScopes = getAuthorizedScopes(userRoles, requestedScopes, appScopes);
        oAuth2TokenValidationMessageContext.getResponseDTO().setScope(authorizedScopes.toArray(new String[authorizedScopes.size()]));
    }
    if (ArrayUtils.isEmpty(userRoles)) {
        if (log.isDebugEnabled()) {
            log.debug("No roles associated for the user " + authenticatedUser.getUserName());
        }
        return false;
    }
    return true;
}
Also used : ResourceScopeCacheEntry(org.wso2.carbon.identity.oauth2.model.ResourceScopeCacheEntry) CacheEntry(org.wso2.carbon.identity.oauth.cache.CacheEntry) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OAuthCacheKey(org.wso2.carbon.identity.oauth.cache.OAuthCacheKey) ResourceScopeCacheEntry(org.wso2.carbon.identity.oauth2.model.ResourceScopeCacheEntry)

Example 34 with Property

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

the class APIMappingUtil method fromDTOtoAPIProduct.

public static APIProduct fromDTOtoAPIProduct(APIProductDTO dto, String provider) throws APIManagementException {
    APIProduct product = new APIProduct();
    APIProductIdentifier id = new APIProductIdentifier(APIUtil.replaceEmailDomain(provider), dto.getName(), // todo: replace this with dto.getVersion
    APIConstants.API_PRODUCT_VERSION);
    product.setID(id);
    product.setUuid(dto.getId());
    product.setDescription(dto.getDescription());
    String context = dto.getContext();
    if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
        context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
    }
    context = context.startsWith("/") ? context : ("/" + context);
    String providerDomain = MultitenantUtils.getTenantDomain(provider);
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(providerDomain) && dto.getId() == null) {
        // Create tenant aware context for API
        context = "/t/" + providerDomain + context;
    }
    product.setType(APIConstants.API_PRODUCT_IDENTIFIER_TYPE.replaceAll("\\s", ""));
    product.setContext(context);
    context = checkAndSetVersionParam(context);
    product.setContextTemplate(context);
    List<String> apiProductTags = dto.getTags();
    Set<String> tagsToReturn = new HashSet<>(apiProductTags);
    product.addTags(tagsToReturn);
    if (dto.isEnableSchemaValidation() != null) {
        product.setEnableSchemaValidation(dto.isEnableSchemaValidation());
    }
    product.setEnableStore(true);
    if (dto.isResponseCachingEnabled() != null && dto.isResponseCachingEnabled()) {
        product.setResponseCache(APIConstants.ENABLED);
    } else {
        product.setResponseCache(APIConstants.DISABLED);
    }
    if (dto.getCacheTimeout() != null) {
        product.setCacheTimeout(dto.getCacheTimeout());
    } else {
        product.setCacheTimeout(APIConstants.API_RESPONSE_CACHE_TIMEOUT);
    }
    if (dto.getBusinessInformation() != null) {
        product.setBusinessOwner(dto.getBusinessInformation().getBusinessOwner());
        product.setBusinessOwnerEmail(dto.getBusinessInformation().getBusinessOwnerEmail());
        product.setTechnicalOwner(dto.getBusinessInformation().getTechnicalOwner());
        product.setTechnicalOwnerEmail(dto.getBusinessInformation().getTechnicalOwnerEmail());
    }
    Set<Tier> apiTiers = new HashSet<>();
    List<String> tiersFromDTO = dto.getPolicies();
    if (dto.getVisibility() != null) {
        product.setVisibility(mapVisibilityFromDTOtoAPIProduct(dto.getVisibility()));
    }
    if (dto.getVisibleRoles() != null) {
        String visibleRoles = StringUtils.join(dto.getVisibleRoles(), ',');
        product.setVisibleRoles(visibleRoles);
    }
    if (dto.getVisibleTenants() != null) {
        String visibleTenants = StringUtils.join(dto.getVisibleTenants(), ',');
        product.setVisibleTenants(visibleTenants);
    }
    List<String> accessControlRoles = dto.getAccessControlRoles();
    if (accessControlRoles == null || accessControlRoles.isEmpty()) {
        product.setAccessControl(APIConstants.NO_ACCESS_CONTROL);
        product.setAccessControlRoles("null");
    } else {
        product.setAccessControlRoles(StringUtils.join(accessControlRoles, ',').toLowerCase());
        product.setAccessControl(APIConstants.API_RESTRICTED_VISIBILITY);
    }
    for (String tier : tiersFromDTO) {
        apiTiers.add(new Tier(tier));
    }
    product.setAvailableTiers(apiTiers);
    product.setProductLevelPolicy(dto.getApiThrottlingPolicy());
    product.setGatewayVendor(dto.getGatewayVendor());
    if (dto.getSubscriptionAvailability() != null) {
        product.setSubscriptionAvailability(mapSubscriptionAvailabilityFromDTOtoAPIProduct(dto.getSubscriptionAvailability()));
    }
    List<APIInfoAdditionalPropertiesDTO> additionalProperties = dto.getAdditionalProperties();
    if (additionalProperties != null) {
        for (APIInfoAdditionalPropertiesDTO property : additionalProperties) {
            if (property.isDisplay()) {
                product.addProperty(property.getName() + APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX, property.getValue());
            } else {
                product.addProperty(property.getName(), property.getValue());
            }
        }
    }
    if (dto.getSubscriptionAvailableTenants() != null) {
        product.setSubscriptionAvailableTenants(StringUtils.join(dto.getSubscriptionAvailableTenants(), ","));
    }
    String transports = StringUtils.join(dto.getTransport(), ',');
    product.setTransports(transports);
    List<APIProductResource> productResources = new ArrayList<APIProductResource>();
    Set<String> verbResourceCombo = new HashSet<>();
    for (ProductAPIDTO res : dto.getApis()) {
        List<APIOperationsDTO> productAPIOperationsDTO = res.getOperations();
        for (APIOperationsDTO resourceItem : productAPIOperationsDTO) {
            if (!verbResourceCombo.add(resourceItem.getVerb() + resourceItem.getTarget())) {
                throw new APIManagementException("API Product resource: " + resourceItem.getTarget() + ", with verb: " + resourceItem.getVerb() + " , is duplicated for id " + id, ExceptionCodes.from(ExceptionCodes.API_PRODUCT_DUPLICATE_RESOURCE, resourceItem.getTarget(), resourceItem.getVerb()));
            }
            URITemplate template = new URITemplate();
            template.setHTTPVerb(resourceItem.getVerb());
            template.setHttpVerbs(resourceItem.getVerb());
            template.setResourceURI(resourceItem.getTarget());
            template.setUriTemplate(resourceItem.getTarget());
            template.setOperationPolicies(OperationPolicyMappingUtil.fromDTOToAPIOperationPoliciesList(resourceItem.getOperationPolicies()));
            APIProductResource resource = new APIProductResource();
            resource.setApiId(res.getApiId());
            resource.setUriTemplate(template);
            productResources.add(resource);
        }
    }
    Set<Scope> scopes = getScopes(dto);
    product.setScopes(scopes);
    APICorsConfigurationDTO apiCorsConfigurationDTO = dto.getCorsConfiguration();
    CORSConfiguration corsConfiguration;
    if (apiCorsConfigurationDTO != null) {
        corsConfiguration = new CORSConfiguration(apiCorsConfigurationDTO.isCorsConfigurationEnabled(), apiCorsConfigurationDTO.getAccessControlAllowOrigins(), apiCorsConfigurationDTO.isAccessControlAllowCredentials(), apiCorsConfigurationDTO.getAccessControlAllowHeaders(), apiCorsConfigurationDTO.getAccessControlAllowMethods());
    } else {
        corsConfiguration = APIUtil.getDefaultCorsConfiguration();
    }
    product.setCorsConfiguration(corsConfiguration);
    product.setProductResources(productResources);
    product.setApiSecurity(getSecurityScheme(dto.getSecurityScheme()));
    product.setAuthorizationHeader(dto.getAuthorizationHeader());
    // attach api categories to API model
    setAPICategoriesToModel(dto, product, provider);
    return product;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) ArrayList(java.util.ArrayList) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APICorsConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APICorsConfigurationDTO) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) APIInfoAdditionalPropertiesDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 35 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)

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