Search in sources :

Example 1 with Origin

use of org.wso2.carbon.identity.cors.mgt.core.model.Origin in project carbon-apimgt by wso2.

the class APIUtil method getExternalIDPOrigin.

/**
 * Get the External IDP host name when UIs use an external IDP for SSO or other purpose
 * By default this is equal to $ref{server.base_path} (i:e https://localhost:9443)
 *
 * @return Origin string of the external IDP
 */
public static String getExternalIDPOrigin() throws APIManagementException {
    APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
    String idpEndpoint = config.getFirstProperty(APIConstants.IDENTITY_PROVIDER_SERVER_URL);
    if (idpEndpoint == null) {
        return getServerURL();
    } else {
        return idpEndpoint;
    }
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration)

Example 2 with Origin

use of org.wso2.carbon.identity.cors.mgt.core.model.Origin in project carbon-apimgt by wso2.

the class PersistenceHelper method getSampleAPIArtifactForTenant.

public static GenericArtifact getSampleAPIArtifactForTenant() throws GovernanceException {
    GenericArtifact artifact = new GenericArtifactImpl(new QName("", "PizzaShackAPI", ""), "application/vnd.wso2-api+xml");
    artifact.setAttribute("overview_endpointSecured", "false");
    artifact.setAttribute("overview_transports", "http,https");
    artifact.setAttribute("URITemplate_authType3", "Application & Application User");
    artifact.setAttribute("overview_wadl", null);
    artifact.setAttribute("URITemplate_authType4", "Application & Application User");
    artifact.setAttribute("overview_authorizationHeader", "Authorization");
    artifact.setAttribute("URITemplate_authType1", "Application & Application User");
    artifact.setAttribute("overview_visibleTenants", null);
    artifact.setAttribute("URITemplate_authType2", "Application & Application User");
    artifact.setAttribute("overview_wsdl", null);
    artifact.setAttribute("overview_apiSecurity", "oauth2,oauth_basic_auth_api_key_mandatory");
    artifact.setAttribute("URITemplate_authType0", "Application & Application User");
    artifact.setAttribute("overview_keyManagers", "[\"all\"]");
    artifact.setAttribute("overview_environments", "Default");
    artifact.setAttribute("overview_context", "/t/wso2.com/pizzashack/1.0.0");
    artifact.setAttribute("overview_visibility", "restricted");
    artifact.setAttribute("overview_isLatest", "true");
    artifact.setAttribute("overview_outSequence", "log_out_message");
    artifact.setAttribute("overview_provider", "admin-AT-wso2.com");
    artifact.setAttribute("apiCategories_categoryName", "testcategory");
    artifact.setAttribute("overview_thumbnail", "/t/wso2.com/t/wso2.com/registry/resource/_system/governance/apimgt/applicationdata/provider/admin-AT-wso2.com/PizzaShackAPI/1.0.0/icon");
    artifact.setAttribute("overview_contextTemplate", "/t/wso2.com/pizzashack/{version}");
    artifact.setAttribute("overview_description", "This is a simple API for Pizza Shack online pizza delivery store.");
    artifact.setAttribute("overview_technicalOwner", "John Doe");
    artifact.setAttribute("overview_type", "HTTP");
    artifact.setAttribute("overview_technicalOwnerEmail", "architecture@pizzashack.com");
    artifact.setAttribute("URITemplate_httpVerb4", "DELETE");
    artifact.setAttribute("overview_inSequence", "log_in_message");
    artifact.setAttribute("URITemplate_httpVerb2", "GET");
    artifact.setAttribute("URITemplate_httpVerb3", "PUT");
    artifact.setAttribute("URITemplate_httpVerb0", "POST");
    artifact.setAttribute("URITemplate_httpVerb1", "GET");
    artifact.setAttribute("labels_labelName", "gwlable");
    artifact.setAttribute("overview_businessOwner", "Jane Roe");
    artifact.setAttribute("overview_version", "1.0.0");
    artifact.setAttribute("overview_endpointConfig", "{\"endpoint_type\":\"http\",\"sandbox_endpoints\":{\"url\":\"https://localhost:9443/am/sample/pizzashack/v1/api/\"}," + "\"endpoint_security\":{\"production\":{\"password\":\"admin\",\"tokenUrl\":null,\"clientId\":null," + "\"clientSecret\":null,\"customParameters\":\"{}\",\"additionalProperties\":{},\"type\":\"BASIC\"," + "\"grantType\":null,\"enabled\":true,\"uniqueIdentifier\":null,\"username\":\"admin\"}," + "\"sandbox\":{\"password\":null,\"tokenUrl\":null,\"clientId\":null,\"clientSecret\":null," + "\"customParameters\":\"{}\",\"additionalProperties\":{},\"type\":null,\"grantType\":null,\"enabled\":false," + "\"uniqueIdentifier\":null,\"username\":null}},\"production_endpoints\":" + "{\"url\":\"https://localhost:9443/am/sample/pizzashack/v1/api/\"}}");
    artifact.setAttribute("overview_tier", "Bronze||Silver||Gold||Unlimited");
    artifact.setAttribute("overview_sandboxTps", "1000");
    artifact.setAttribute("overview_apiOwner", "admin@wso2.com");
    artifact.setAttribute("overview_businessOwnerEmail", "marketing@pizzashack.com");
    artifact.setAttribute("isMonetizationEnabled", "false");
    artifact.setAttribute("overview_implementation", "ENDPOINT");
    artifact.setAttribute("overview_deployments", "null");
    artifact.setAttribute("overview_redirectURL", null);
    artifact.setAttribute("monetizationProperties", "{}");
    artifact.setAttribute("overview_name", "PizzaShackAPI");
    artifact.setAttribute("overview_subscriptionAvailability", "current_tenant");
    artifact.setAttribute("overview_productionTps", "1000");
    artifact.setAttribute("overview_cacheTimeout", "300");
    artifact.setAttribute("overview_visibleRoles", "admin,internal/subscriber");
    artifact.setAttribute("overview_testKey", null);
    artifact.setAttribute("overview_corsConfiguration", "{\"corsConfigurationEnabled\":true,\"accessControlAllowOrigins\":[\"*\"]," + "\"accessControlAllowCredentials\":false,\"accessControlAllowHeaders\":[\"authorization\"," + "\"Access-Control-Allow-Origin\",\"Content-Type\",\"SOAPAction\",\"apikey\",\"testKey\"]," + "\"accessControlAllowMethods\":[\"GET\",\"PUT\",\"POST\",\"DELETE\",\"PATCH\",\"OPTIONS\"]}");
    artifact.setAttribute("overview_advertiseOnly", "false");
    artifact.setAttribute("overview_versionType", "context");
    artifact.setAttribute("overview_status", "PUBLISHED");
    artifact.setAttribute("overview_endpointPpassword", null);
    artifact.setAttribute("overview_tenants", null);
    artifact.setAttribute("overview_endpointAuthDigest", "false");
    artifact.setAttribute("overview_faultSequence", "json_fault");
    artifact.setAttribute("overview_responseCaching", "Enabled");
    artifact.setAttribute("URITemplate_urlPattern4", "/order/{orderId}");
    artifact.setAttribute("overview_isDefaultVersion", "true");
    artifact.setAttribute("URITemplate_urlPattern2", "/order/{orderId}");
    artifact.setAttribute("URITemplate_urlPattern3", "/order/{orderId}");
    artifact.setAttribute("URITemplate_urlPattern0", "/order");
    artifact.setAttribute("URITemplate_urlPattern1", "/menu");
    artifact.setAttribute("overview_enableStore", "true");
    artifact.setAttribute("overview_enableSchemaValidation", "true");
    artifact.setAttribute("overview_endpointUsername", null);
    artifact.setAttribute("overview_status", "PUBLISHED");
    artifact.setId("88e758b7-6924-4e9f-8882-431070b6492b");
    return artifact;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) QName(javax.xml.namespace.QName) GenericArtifactImpl(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifactImpl)

Example 3 with Origin

use of org.wso2.carbon.identity.cors.mgt.core.model.Origin in project carbon-apimgt by wso2.

the class PersistenceHelper method getSampleAPIProductArtifact.

public static GenericArtifact getSampleAPIProductArtifact() throws GovernanceException {
    GenericArtifact artifact = new GenericArtifactImpl(new QName("", "APIProductTest", ""), "application/vnd.wso2-api+xml");
    artifact.setAttribute("overview_transports", "http,https");
    artifact.setAttribute("monetizationProperties", "{}");
    artifact.setAttribute("overview_authorizationHeader", "Authorization");
    artifact.setAttribute("overview_visibleTenants", null);
    artifact.setAttribute("overview_name", "APIProductTest");
    artifact.setAttribute("overview_apiSecurity", "oauth2,oauth_basic_auth_api_key_mandatory,basic_auth,api_key");
    artifact.setAttribute("overview_environments", "Default");
    artifact.setAttribute("overview_subscriptionAvailability", "all_tenants");
    artifact.setAttribute("overview_context", "/prodcontext");
    artifact.setAttribute("overview_visibility", "restricted");
    artifact.setAttribute("overview_cacheTimeout", "300");
    artifact.setAttribute("overview_provider", "admin");
    artifact.setAttribute("overview_visibleRoles", "admin");
    artifact.setAttribute("apiCategories_categoryName", "testcategory");
    artifact.setAttribute("overview_contextTemplate", "/prodcontext/{version}");
    artifact.setAttribute("overview_thumbnail", null);
    artifact.setAttribute("overview_description", "sample product");
    artifact.setAttribute("overview_technicalOwner", null);
    artifact.setAttribute("overview_type", "APIProduct");
    artifact.setAttribute("overview_technicalOwnerEmail", null);
    artifact.setAttribute("overview_corsConfiguration", "{\"corsConfigurationEnabled\":false," + "\"accessControlAllowOrigins\":[\"*\"],\"accessControlAllowCredentials\":false," + "\"accessControlAllowHeaders\":[\"authorization\",\"Access-Control-Allow-Origin\",\"Content-Type\"," + "\"SOAPAction\",\"apikey\",\"testKey\"],\"accessControlAllowMethods\":[\"GET\",\"PUT\",\"POST\"," + "\"DELETE\",\"PATCH\",\"OPTIONS\"]}");
    artifact.setAttribute("overview_versionType", "context");
    artifact.setAttribute("overview_status", "PUBLISHED");
    artifact.setAttribute("overview_businessOwner", "productOwner");
    artifact.setAttribute("overview_version", "1.0.0");
    artifact.setAttribute("overview_tenants", null);
    artifact.setAttribute("overview_responseCaching", "Disabled");
    artifact.setAttribute("overview_tier", "Bronze||Gold");
    artifact.setAttribute("overview_businessOwnerEmail", "owner@test.com");
    artifact.setAttribute("isMonetizationEnabled", "false");
    artifact.setAttribute("overview_enableStore", "true");
    artifact.setAttribute("overview_enableSchemaValidation", "false");
    artifact.setId("88e758b7-6924-4e9f-8882-431070b6492b");
    return artifact;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) QName(javax.xml.namespace.QName) GenericArtifactImpl(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifactImpl)

Example 4 with Origin

use of org.wso2.carbon.identity.cors.mgt.core.model.Origin in project carbon-apimgt by wso2.

the class OAuthAuthenticator method authenticate.

@MethodStats
public AuthenticationResponse authenticate(MessageContext synCtx) throws APIManagementException {
    boolean isJwtToken = false;
    String accessToken = null;
    String remainingAuthHeader = "";
    boolean defaultVersionInvoked = false;
    Map headers = (Map) ((Axis2MessageContext) synCtx).getAxis2MessageContext().getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    String tenantDomain = GatewayUtils.getTenantDomain();
    keyManagerList = GatewayUtils.getKeyManagers(synCtx);
    if (keyValidator == null) {
        this.keyValidator = new APIKeyValidator();
    }
    if (jwtValidator == null) {
        this.jwtValidator = new JWTValidator(this.keyValidator, tenantDomain);
    }
    config = getApiManagerConfiguration();
    removeOAuthHeadersFromOutMessage = isRemoveOAuthHeadersFromOutMessage();
    securityContextHeader = getSecurityContextHeader();
    if (headers != null) {
        requestOrigin = (String) headers.get("Origin");
        // Extract the access token from auth header
        // From 1.0.7 version of this component onwards remove the OAuth authorization header from
        // the message is configurable. So we dont need to remove headers at this point.
        String authHeader = (String) headers.get(getSecurityHeader());
        if (authHeader == null) {
            if (log.isDebugEnabled()) {
                log.debug("OAuth2 Authentication: Expected authorization header with the name '".concat(getSecurityHeader()).concat("' was not found."));
            }
        } else {
            ArrayList<String> remainingAuthHeaders = new ArrayList<>();
            boolean consumerkeyFound = false;
            String[] splitHeaders = authHeader.split(oauthHeaderSplitter);
            if (splitHeaders != null) {
                for (int i = 0; i < splitHeaders.length; i++) {
                    String[] elements = splitHeaders[i].split(consumerKeySegmentDelimiter);
                    if (elements != null && elements.length > 1) {
                        int j = 0;
                        boolean isConsumerKeyHeaderAvailable = false;
                        for (String element : elements) {
                            if (!"".equals(element.trim())) {
                                if (consumerKeyHeaderSegment.equals(elements[j].trim())) {
                                    isConsumerKeyHeaderAvailable = true;
                                } else if (isConsumerKeyHeaderAvailable) {
                                    accessToken = removeLeadingAndTrailing(elements[j].trim());
                                    consumerkeyFound = true;
                                }
                            }
                            j++;
                        }
                    }
                    if (!consumerkeyFound) {
                        remainingAuthHeaders.add(splitHeaders[i]);
                    } else {
                        consumerkeyFound = false;
                    }
                }
            }
            remainingAuthHeader = String.join(oauthHeaderSplitter, remainingAuthHeaders);
        }
        if (log.isDebugEnabled()) {
            log.debug(accessToken != null ? "Received Token ".concat(accessToken) : "No valid Authorization header found");
        }
        // Check if client invoked the default version API (accessing API without version).
        defaultVersionInvoked = headers.containsKey(defaultAPIHeader);
    }
    if (log.isDebugEnabled()) {
        log.debug("Default Version API invoked");
    }
    if (removeOAuthHeadersFromOutMessage) {
        // Remove authorization headers sent for authentication at the gateway and pass others to the backend
        if (StringUtils.isNotBlank(remainingAuthHeader)) {
            if (log.isDebugEnabled()) {
                log.debug("Removing OAuth key from Authorization header");
            }
            headers.put(getSecurityHeader(), remainingAuthHeader);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Removing Authorization header from headers");
            }
            headers.remove(getSecurityHeader());
        }
    }
    if (removeDefaultAPIHeaderFromOutMessage) {
        headers.remove(defaultAPIHeader);
    }
    String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
    String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
    String httpMethod = (String) ((Axis2MessageContext) synCtx).getAxis2MessageContext().getProperty(Constants.Configuration.HTTP_METHOD);
    String matchingResource = (String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE);
    SignedJWTInfo signedJWTInfo = null;
    // If the matching resource does not require authentication
    Timer timer = getTimer(MetricManager.name(APIConstants.METRICS_PREFIX, this.getClass().getSimpleName(), "GET_RESOURCE_AUTH"));
    Timer.Context context = timer.start();
    org.apache.axis2.context.MessageContext axis2MessageCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
    org.apache.axis2.context.MessageContext.setCurrentMessageContext(axis2MessageCtx);
    String authenticationScheme;
    try {
        // Initial guess of a JWT token using the presence of a DOT.
        if (StringUtils.isNotEmpty(accessToken) && accessToken.contains(APIConstants.DOT)) {
            try {
                if (StringUtils.countMatches(accessToken, APIConstants.DOT) != 2) {
                    log.debug("Invalid JWT token. The expected token format is <header.payload.signature>");
                    throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, "Invalid JWT token");
                }
                signedJWTInfo = getSignedJwt(accessToken);
                if (GatewayUtils.isInternalKey(signedJWTInfo.getJwtClaimsSet()) || GatewayUtils.isAPIKey(signedJWTInfo.getJwtClaimsSet())) {
                    log.debug("Invalid Token Provided");
                    return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
                }
                String keyManager = ServiceReferenceHolder.getInstance().getJwtValidationService().getKeyManagerNameIfJwtValidatorExist(signedJWTInfo);
                if (StringUtils.isNotEmpty(keyManager)) {
                    if (log.isDebugEnabled()) {
                        log.debug("KeyManager " + keyManager + "found for authenticate token " + GatewayUtils.getMaskedToken(accessToken));
                    }
                    if (keyManagerList.contains(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS) || keyManagerList.contains(keyManager)) {
                        if (log.isDebugEnabled()) {
                            log.debug("Elected KeyManager " + keyManager + "found in API level list " + String.join(",", keyManagerList));
                        }
                        isJwtToken = true;
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("Elected KeyManager " + keyManager + " not found in API level list " + String.join(",", keyManagerList));
                        }
                        return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("KeyManager not found for accessToken " + GatewayUtils.getMaskedToken(accessToken));
                    }
                }
            } catch (ParseException | IllegalArgumentException e) {
                log.debug("Not a JWT token. Failed to decode the token header.", e);
            } catch (APIManagementException e) {
                log.error("error while check validation of JWt", e);
                return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
            }
        }
        authenticationScheme = getAPIKeyValidator().getResourceAuthenticationScheme(synCtx);
    } catch (APISecurityException ex) {
        return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
    }
    context.stop();
    APIKeyValidationInfoDTO info;
    if (APIConstants.NO_MATCHING_AUTH_SCHEME.equals(authenticationScheme)) {
        info = new APIKeyValidationInfoDTO();
        info.setAuthorized(false);
        info.setValidationStatus(900906);
    } else if (accessToken == null || apiContext == null || apiVersion == null) {
        if (log.isDebugEnabled()) {
            if (accessToken == null) {
                log.debug("OAuth headers not found");
            } else if (apiContext == null) {
                log.debug("Couldn't find API Context");
            } else {
                log.debug("Could not find api version");
            }
        }
        return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_MISSING_CREDENTIALS, "Required OAuth credentials not provided");
    } else {
        // Start JWT token validation
        if (isJwtToken) {
            try {
                AuthenticationContext authenticationContext = jwtValidator.authenticate(signedJWTInfo, synCtx);
                APISecurityUtils.setAuthenticationContext(synCtx, authenticationContext, securityContextHeader);
                log.debug("User is authorized using JWT token to access the resource.");
                synCtx.setProperty(APIMgtGatewayConstants.END_USER_NAME, authenticationContext.getUsername());
                return new AuthenticationResponse(true, isMandatory, false, 0, null);
            } catch (APISecurityException ex) {
                return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Matching resource is: ".concat(matchingResource));
        }
        timer = getTimer(MetricManager.name(APIConstants.METRICS_PREFIX, this.getClass().getSimpleName(), "GET_KEY_VALIDATION_INFO"));
        context = timer.start();
        try {
            info = getAPIKeyValidator().getKeyValidationInfo(apiContext, accessToken, apiVersion, authenticationScheme, matchingResource, httpMethod, defaultVersionInvoked, keyManagerList);
        } catch (APISecurityException ex) {
            return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
        }
        context.stop();
        synCtx.setProperty(APIMgtGatewayConstants.APPLICATION_NAME, info.getApplicationName());
        synCtx.setProperty(APIMgtGatewayConstants.END_USER_NAME, info.getEndUserName());
        synCtx.setProperty(APIMgtGatewayConstants.SCOPES, info.getScopes() == null ? null : info.getScopes().toString());
    }
    if (info.isAuthorized()) {
        AuthenticationContext authContext = new AuthenticationContext();
        authContext.setAuthenticated(true);
        authContext.setTier(info.getTier());
        authContext.setApiKey(accessToken);
        authContext.setKeyType(info.getType());
        if (info.getEndUserName() != null) {
            authContext.setUsername(info.getEndUserName());
        } else {
            authContext.setUsername(APIConstants.END_USER_ANONYMOUS);
        }
        authContext.setCallerToken(info.getEndUserToken());
        authContext.setApplicationId(info.getApplicationId());
        authContext.setApplicationUUID(info.getApplicationUUID());
        authContext.setApplicationName(info.getApplicationName());
        authContext.setApplicationTier(info.getApplicationTier());
        authContext.setSubscriber(info.getSubscriber());
        authContext.setConsumerKey(info.getConsumerKey());
        authContext.setApiTier(info.getApiTier());
        authContext.setThrottlingDataList(info.getThrottlingDataList());
        authContext.setSubscriberTenantDomain(info.getSubscriberTenantDomain());
        authContext.setSpikeArrestLimit(info.getSpikeArrestLimit());
        authContext.setSpikeArrestUnit(info.getSpikeArrestUnit());
        authContext.setStopOnQuotaReach(info.isStopOnQuotaReach());
        authContext.setIsContentAware(info.isContentAware());
        APISecurityUtils.setAuthenticationContext(synCtx, authContext, securityContextHeader);
        if (info.getProductName() != null && info.getProductProvider() != null) {
            authContext.setProductName(info.getProductName());
            authContext.setProductProvider(info.getProductProvider());
        }
        /* Synapse properties required for BAM Mediator*/
        // String tenantDomain = MultitenantUtils.getTenantDomain(info.getApiPublisher());
        synCtx.setProperty("api.ut.apiPublisher", info.getApiPublisher());
        synCtx.setProperty("API_NAME", info.getApiName());
        /* GraphQL Query Analysis Information */
        if (APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
            synCtx.setProperty(APIConstants.MAXIMUM_QUERY_DEPTH, info.getGraphQLMaxDepth());
            synCtx.setProperty(APIConstants.MAXIMUM_QUERY_COMPLEXITY, info.getGraphQLMaxComplexity());
        }
        if (log.isDebugEnabled()) {
            log.debug("User is authorized to access the Resource");
        }
        return new AuthenticationResponse(true, isMandatory, false, 0, null);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("User is NOT authorized to access the Resource");
        }
        return new AuthenticationResponse(false, isMandatory, true, info.getValidationStatus(), "Access failure for API: " + apiContext + ", version: " + apiVersion + " status: (" + info.getValidationStatus() + ") - " + APISecurityConstants.getAuthenticationFailureMessage(info.getValidationStatus()));
    }
}
Also used : APISecurityException(org.wso2.carbon.apimgt.gateway.handlers.security.APISecurityException) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) APIKeyValidator(org.wso2.carbon.apimgt.gateway.handlers.security.APIKeyValidator) ArrayList(java.util.ArrayList) AuthenticationResponse(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse) Timer(org.wso2.carbon.metrics.manager.Timer) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ParseException(java.text.ParseException) JWTValidator(org.wso2.carbon.apimgt.gateway.handlers.security.jwt.JWTValidator) SignedJWTInfo(org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo) Map(java.util.Map) TreeMap(java.util.TreeMap) APIKeyValidationInfoDTO(org.wso2.carbon.apimgt.impl.dto.APIKeyValidationInfoDTO) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) MethodStats(org.wso2.carbon.apimgt.gateway.MethodStats)

Example 5 with Origin

use of org.wso2.carbon.identity.cors.mgt.core.model.Origin in project carbon-apimgt by wso2.

the class TemplateBuilderUtil method getAPITemplateBuilder.

public static APITemplateBuilderImpl getAPITemplateBuilder(APIProduct apiProduct, String tenantDomain, List<ClientCertificateDTO> clientCertificateDTOS, Map<String, APIDTO> associatedAPIMap) throws APIManagementException {
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    APITemplateBuilderImpl vtb = new APITemplateBuilderImpl(apiProduct, associatedAPIMap);
    Map<String, String> latencyStatsProperties = new HashMap<String, String>();
    latencyStatsProperties.put(APIConstants.API_UUID, apiProduct.getUuid());
    if (!APIUtil.isStreamingApi(apiProduct)) {
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.common.APIMgtLatencyStatsHandler", latencyStatsProperties);
    }
    Map<String, String> corsProperties = new HashMap<>();
    corsProperties.put(APIConstants.CORSHeaders.IMPLEMENTATION_TYPE_HANDLER_VALUE, APIConstants.IMPLEMENTATION_TYPE_ENDPOINT);
    // Get authorization header from the API object or from the tenant registry
    String authorizationHeader;
    if (!StringUtils.isBlank(apiProduct.getAuthorizationHeader())) {
        authorizationHeader = apiProduct.getAuthorizationHeader();
    } else {
        // Retrieves the auth configuration from tenant registry or api-manager.xml if not available
        // in tenant registry
        authorizationHeader = APIUtil.getOAuthConfiguration(tenantDomain, APIConstants.AUTHORIZATION_HEADER);
    }
    if (!StringUtils.isBlank(authorizationHeader)) {
        corsProperties.put(APIConstants.AUTHORIZATION_HEADER, authorizationHeader);
    }
    if (apiProduct.getCorsConfiguration() != null && apiProduct.getCorsConfiguration().isCorsConfigurationEnabled()) {
        CORSConfiguration corsConfiguration = apiProduct.getCorsConfiguration();
        if (corsConfiguration.getAccessControlAllowHeaders() != null) {
            StringBuilder allowHeaders = new StringBuilder();
            for (String header : corsConfiguration.getAccessControlAllowHeaders()) {
                allowHeaders.append(header).append(',');
            }
            if (allowHeaders.length() != 0) {
                allowHeaders.deleteCharAt(allowHeaders.length() - 1);
                corsProperties.put(APIConstants.CORSHeaders.ALLOW_HEADERS_HANDLER_VALUE, allowHeaders.toString());
            }
        }
        if (corsConfiguration.getAccessControlAllowOrigins() != null) {
            StringBuilder allowOrigins = new StringBuilder();
            for (String origin : corsConfiguration.getAccessControlAllowOrigins()) {
                allowOrigins.append(origin).append(',');
            }
            if (allowOrigins.length() != 0) {
                allowOrigins.deleteCharAt(allowOrigins.length() - 1);
                corsProperties.put(APIConstants.CORSHeaders.ALLOW_ORIGIN_HANDLER_VALUE, allowOrigins.toString());
            }
        }
        if (corsConfiguration.getAccessControlAllowMethods() != null) {
            StringBuilder allowedMethods = new StringBuilder();
            for (String methods : corsConfiguration.getAccessControlAllowMethods()) {
                allowedMethods.append(methods).append(',');
            }
            if (allowedMethods.length() != 0) {
                allowedMethods.deleteCharAt(allowedMethods.length() - 1);
                corsProperties.put(APIConstants.CORSHeaders.ALLOW_METHODS_HANDLER_VALUE, allowedMethods.toString());
            }
        }
        if (corsConfiguration.isAccessControlAllowCredentials()) {
            corsProperties.put(APIConstants.CORSHeaders.ALLOW_CREDENTIALS_HANDLER_VALUE, String.valueOf(corsConfiguration.isAccessControlAllowCredentials()));
        }
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler", corsProperties);
    } else if (APIUtil.isCORSEnabled()) {
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler", corsProperties);
    }
    vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.common.APIStatusHandler", Collections.emptyMap());
    Map<String, String> clientCertificateObject = null;
    CertificateMgtUtils certificateMgtUtils = CertificateMgtUtils.getInstance();
    if (clientCertificateDTOS != null) {
        clientCertificateObject = new HashMap<>();
        for (ClientCertificateDTO clientCertificateDTO : clientCertificateDTOS) {
            clientCertificateObject.put(certificateMgtUtils.getUniqueIdentifierOfCertificate(clientCertificateDTO.getCertificate()), clientCertificateDTO.getTierName());
        }
    }
    Map<String, String> authProperties = new HashMap<String, String>();
    if (!StringUtils.isBlank(authorizationHeader)) {
        authProperties.put(APIConstants.AUTHORIZATION_HEADER, authorizationHeader);
    }
    String apiSecurity = apiProduct.getApiSecurity();
    String apiLevelPolicy = apiProduct.getProductLevelPolicy();
    authProperties.put(APIConstants.API_SECURITY, apiSecurity);
    authProperties.put(APIConstants.API_LEVEL_POLICY, apiLevelPolicy);
    if (clientCertificateObject != null) {
        authProperties.put(APIConstants.CERTIFICATE_INFORMATION, clientCertificateObject.toString());
    }
    // Get RemoveHeaderFromOutMessage from tenant registry or api-manager.xml
    String removeHeaderFromOutMessage = APIUtil.getOAuthConfiguration(tenantDomain, APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE);
    if (!StringUtils.isBlank(removeHeaderFromOutMessage)) {
        authProperties.put(APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE, removeHeaderFromOutMessage);
    } else {
        authProperties.put(APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE, APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE_DEFAULT);
    }
    authProperties.put("apiType", APIConstants.ApiTypes.PRODUCT_API.name());
    vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler", authProperties);
    Map<String, String> properties = new HashMap<String, String>();
    if (apiProduct.getProductionMaxTps() != null) {
        properties.put("productionMaxCount", apiProduct.getProductionMaxTps());
    }
    if (apiProduct.getSandboxMaxTps() != null) {
        properties.put("sandboxMaxCount", apiProduct.getSandboxMaxTps());
    }
    if (!APIUtil.isStreamingApi(apiProduct)) {
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.throttling.ThrottleHandler", properties);
        properties = new HashMap<String, String>();
        properties.put("configKey", APIConstants.GA_CONF_KEY);
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.analytics.APIMgtGoogleAnalyticsTrackingHandler", properties);
        String extensionHandlerPosition = getExtensionHandlerPosition(tenantDomain);
        if ("top".equalsIgnoreCase(extensionHandlerPosition)) {
            vtb.addHandlerPriority("org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler", Collections.emptyMap(), 2);
        } else {
            vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler", Collections.emptyMap());
        }
    }
    return vtb;
}
Also used : CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) HashMap(java.util.HashMap) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) CertificateMgtUtils(org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils) APITemplateBuilderImpl(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.APITemplateBuilderImpl)

Aggregations

Test (org.testng.annotations.Test)16 Origin (org.wso2.carbon.identity.cors.mgt.core.model.Origin)12 Connection (java.sql.Connection)9 SQLException (java.sql.SQLException)9 NamedPreparedStatement (org.wso2.carbon.database.utils.jdbc.NamedPreparedStatement)9 ResultSet (java.sql.ResultSet)8 CORSOrigin (org.wso2.carbon.identity.cors.mgt.core.model.CORSOrigin)8 CORSManagementServiceClientException (org.wso2.carbon.identity.cors.mgt.core.exception.CORSManagementServiceClientException)7 PreparedStatement (java.sql.PreparedStatement)6 ArrayList (java.util.ArrayList)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 QName (javax.xml.namespace.QName)3 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)3 HashMap (java.util.HashMap)2 HTTPTestRequest (org.ballerinalang.test.services.testutils.HTTPTestRequest)2 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)2 ClientCertificateDTO (org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO)2 CORSConfiguration (org.wso2.carbon.apimgt.api.model.CORSConfiguration)2 APIManagerConfiguration (org.wso2.carbon.apimgt.impl.APIManagerConfiguration)2 CertificateMgtUtils (org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils)2