Search in sources :

Example 86 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class APIProviderImpl method addAPI.

/**
 * Add API metadata, local scopes and URI templates to the database and KeyManager.
 *
 * @param api      API to add
 * @param tenantId Tenant Id
 * @throws APIManagementException if an error occurs while adding the API
 */
private void addAPI(API api, int tenantId) throws APIManagementException {
    int apiId = apiMgtDAO.addAPI(api, tenantId, api.getOrganization());
    addLocalScopes(api.getId().getApiName(), api.getUriTemplates(), api.getOrganization());
    String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
    validateOperationPolicyParameters(api, tenantDomain);
    addURITemplates(apiId, api, tenantId);
    APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_CREATE.name(), tenantId, tenantDomain, api.getId().getApiName(), apiId, api.getUuid(), api.getId().getVersion(), api.getType(), api.getContext(), APIUtil.replaceEmailDomainBack(api.getId().getProviderName()), api.getStatus());
    APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
}
Also used : APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent)

Example 87 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class APIProviderImpl method updateSharedScope.

/**
 * Update a shared scope.
 *
 * @param sharedScope  Shared Scope
 * @param tenantDomain tenant domain
 * @throws APIManagementException If failed to update
 */
@Override
public void updateSharedScope(Scope sharedScope, String tenantDomain) throws APIManagementException {
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getTenantKeyManagers(tenantDomain);
    for (Map.Entry<String, KeyManagerDto> keyManagerEntry : tenantKeyManagers.entrySet()) {
        KeyManager keyManager = keyManagerEntry.getValue().getKeyManager();
        if (keyManager != null) {
            try {
                keyManager.updateScope(sharedScope);
            } catch (APIManagementException e) {
                log.error("Error while Updating Shared Scope " + sharedScope.getKey() + " from Key Manager " + keyManagerEntry.getKey(), e);
            }
        }
    }
    updateScope(sharedScope, tenantId);
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) KeyManagerDto(org.wso2.carbon.apimgt.impl.dto.KeyManagerDto) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager)

Example 88 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class APIProviderImpl method addLocalScopes.

/**
 * Add local scopes for the API if the scopes does not exist as shared scopes. The local scopes to add will be
 * take from the URI templates.
 *
 * @param apiName API name
 * @param uriTemplates  URI Templates
 * @param organization  Organization
 * @throws APIManagementException if fails to add local scopes for the API
 */
private void addLocalScopes(String apiName, Set<URITemplate> uriTemplates, String organization) throws APIManagementException {
    int tenantId = APIUtil.getInternalOrganizationId(organization);
    String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId);
    Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getTenantKeyManagers(tenantDomain);
    // Get the local scopes set to register for the API from URI templates
    Set<Scope> scopesToRegister = getScopesToRegisterFromURITemplates(apiName, organization, uriTemplates);
    // Register scopes
    for (Scope scope : scopesToRegister) {
        for (Map.Entry<String, KeyManagerDto> keyManagerDtoEntry : tenantKeyManagers.entrySet()) {
            KeyManager keyManager = keyManagerDtoEntry.getValue().getKeyManager();
            if (keyManager != null) {
                String scopeKey = scope.getKey();
                try {
                    // version.
                    if (!keyManager.isScopeExists(scopeKey)) {
                        // register scope in KM
                        keyManager.registerScope(scope);
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("Scope: " + scopeKey + " already registered in KM. Skipping registering scope.");
                        }
                    }
                } catch (APIManagementException e) {
                    log.error("Error while registering Scope " + scopeKey + "in Key Manager " + keyManagerDtoEntry.getKey(), e);
                }
            }
        }
    }
    addScopes(scopesToRegister, tenantId);
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) KeyManagerDto(org.wso2.carbon.apimgt.impl.dto.KeyManagerDto) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager)

Example 89 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class APIProviderImpl method validateKeyManagers.

private void validateKeyManagers(API api) throws APIManagementException {
    List<KeyManagerConfigurationDTO> keyManagerConfigurationsByTenant = apiMgtDAO.getKeyManagerConfigurationsByOrganization(tenantDomain);
    List<String> configuredMissingKeyManagers = new ArrayList<>();
    for (String keyManager : api.getKeyManagers()) {
        if (!APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS.equals(keyManager)) {
            KeyManagerConfigurationDTO selectedKeyManager = null;
            for (KeyManagerConfigurationDTO keyManagerConfigurationDTO : keyManagerConfigurationsByTenant) {
                if (keyManager.equals(keyManagerConfigurationDTO.getName())) {
                    selectedKeyManager = keyManagerConfigurationDTO;
                    break;
                }
            }
            if (selectedKeyManager == null) {
                configuredMissingKeyManagers.add(keyManager);
            }
        }
    }
    if (!configuredMissingKeyManagers.isEmpty()) {
        throw new APIManagementException("Key Manager(s) Not found :" + String.join(" , ", configuredMissingKeyManagers), ExceptionCodes.KEY_MANAGER_NOT_REGISTERED);
    }
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArrayList(java.util.ArrayList)

Example 90 with KeyManager

use of org.wso2.carbon.apimgt.api.model.KeyManager in project carbon-apimgt by wso2.

the class AbstractAPIManager method getApplicationKeys.

/**
 * Returns the key associated with given application id.
 *
 * @param applicationId Id of the Application.
 * @return APIKey The key of the application.
 * @throws APIManagementException
 */
protected Set<APIKey> getApplicationKeys(int applicationId, String xWso2Tenant) throws APIManagementException {
    Set<APIKey> apiKeyList = apiMgtDAO.getKeyMappingsFromApplicationId(applicationId);
    if (StringUtils.isNotEmpty(xWso2Tenant)) {
        int tenantId = APIUtil.getInternalOrganizationId(xWso2Tenant);
        // To handle choreo scenario. due to keymanagers are not per organization atm. using ST
        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
            xWso2Tenant = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }
    }
    Set<APIKey> resultantApiKeyList = new HashSet<>();
    for (APIKey apiKey : apiKeyList) {
        String keyManagerName = apiKey.getKeyManager();
        String consumerKey = apiKey.getConsumerKey();
        String tenantDomain = this.tenantDomain;
        if (StringUtils.isNotEmpty(xWso2Tenant)) {
            tenantDomain = xWso2Tenant;
        }
        KeyManagerConfigurationDTO keyManagerConfigurationDTO = apiMgtDAO.getKeyManagerConfigurationByName(tenantDomain, keyManagerName);
        if (keyManagerConfigurationDTO == null) {
            keyManagerConfigurationDTO = apiMgtDAO.getKeyManagerConfigurationByUUID(keyManagerName);
            if (keyManagerConfigurationDTO != null) {
                keyManagerName = keyManagerConfigurationDTO.getName();
            } else {
                log.error("Key Manager: " + keyManagerName + " not found in database.");
                continue;
            }
        }
        if (tenantDomain != null && !tenantDomain.equalsIgnoreCase(keyManagerConfigurationDTO.getOrganization())) {
            continue;
        }
        KeyManager keyManager = null;
        if (keyManagerConfigurationDTO.isEnabled()) {
            keyManager = KeyManagerHolder.getKeyManagerInstance(tenantDomain, keyManagerName);
        } else {
            continue;
        }
        apiKey.setKeyManager(keyManagerConfigurationDTO.getName());
        if (StringUtils.isNotEmpty(consumerKey)) {
            if (keyManager != null) {
                if (APIConstants.OAuthAppMode.MAPPED.name().equalsIgnoreCase(apiKey.getCreateMode()) && !isOauthAppValidation()) {
                    resultantApiKeyList.add(apiKey);
                } else {
                    OAuthApplicationInfo oAuthApplicationInfo = null;
                    try {
                        oAuthApplicationInfo = keyManager.retrieveApplication(consumerKey);
                    } catch (APIManagementException e) {
                        log.error("Error while retrieving Application Information", e);
                        continue;
                    }
                    if (StringUtils.isNotEmpty(apiKey.getAppMetaData())) {
                        OAuthApplicationInfo storedOAuthApplicationInfo = new Gson().fromJson(apiKey.getAppMetaData(), OAuthApplicationInfo.class);
                        if (oAuthApplicationInfo == null) {
                            oAuthApplicationInfo = storedOAuthApplicationInfo;
                        } else {
                            if (StringUtils.isEmpty(oAuthApplicationInfo.getCallBackURL())) {
                                oAuthApplicationInfo.setCallBackURL(storedOAuthApplicationInfo.getCallBackURL());
                            }
                            if ("null".equalsIgnoreCase(oAuthApplicationInfo.getCallBackURL())) {
                                oAuthApplicationInfo.setCallBackURL("");
                            }
                            if (oAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES) == null && storedOAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES) != null) {
                                if (storedOAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES) instanceof String) {
                                    oAuthApplicationInfo.addParameter(APIConstants.JSON_GRANT_TYPES, ((String) storedOAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES)).replace(",", " "));
                                } else {
                                    oAuthApplicationInfo.addParameter(APIConstants.JSON_GRANT_TYPES, storedOAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES));
                                }
                            }
                            if (StringUtils.isEmpty(oAuthApplicationInfo.getClientSecret()) && StringUtils.isNotEmpty(storedOAuthApplicationInfo.getClientSecret())) {
                                oAuthApplicationInfo.setClientSecret(storedOAuthApplicationInfo.getClientSecret());
                            }
                        }
                    }
                    AccessTokenInfo tokenInfo = keyManager.getAccessTokenByConsumerKey(consumerKey);
                    if (oAuthApplicationInfo != null) {
                        apiKey.setConsumerSecret(oAuthApplicationInfo.getClientSecret());
                        apiKey.setCallbackUrl(oAuthApplicationInfo.getCallBackURL());
                        apiKey.setGrantTypes((String) oAuthApplicationInfo.getParameter(APIConstants.JSON_GRANT_TYPES));
                        if (oAuthApplicationInfo.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES) != null) {
                            apiKey.setAdditionalProperties(oAuthApplicationInfo.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES));
                        }
                    }
                    if (tokenInfo != null) {
                        apiKey.setAccessToken(tokenInfo.getAccessToken());
                        apiKey.setValidityPeriod(tokenInfo.getValidityPeriod());
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("Access token does not exist for Consumer Key: " + consumerKey);
                        }
                    }
                    resultantApiKeyList.add(apiKey);
                }
            } else {
                log.error("Key Manager " + keyManagerName + " not initialized in tenant " + tenantDomain);
            }
        } else {
            resultantApiKeyList.add(apiKey);
        }
    }
    return resultantApiKeyList;
}
Also used : APIKey(org.wso2.carbon.apimgt.api.model.APIKey) KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) Gson(com.google.gson.Gson) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)39 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)38 Test (org.junit.Test)29 KeyManager (org.wso2.carbon.apimgt.core.api.KeyManager)25 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)22 HashMap (java.util.HashMap)21 Test (org.testng.annotations.Test)18 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)18 FileInputStream (java.io.FileInputStream)16 KeyManagerConfigurationDTO (org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO)16 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)16 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)16 IdentityProvider (org.wso2.carbon.apimgt.core.api.IdentityProvider)16 Map (java.util.Map)14 API (org.wso2.carbon.apimgt.core.models.API)14 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)13 Scope (org.wso2.carbon.apimgt.core.models.Scope)13 KeyManagerDto (org.wso2.carbon.apimgt.impl.dto.KeyManagerDto)13 TreeMap (java.util.TreeMap)11 AccessTokenRequest (org.wso2.carbon.apimgt.api.model.AccessTokenRequest)11