Search in sources :

Example 16 with KeyManagerDTO

use of org.wso2.carbon.apimgt.rest.api.admin.v1.dto.KeyManagerDTO in project carbon-apimgt by wso2.

the class KeyManagerHolder method addGlobalJWTValidators.

public static void addGlobalJWTValidators(TokenIssuerDto tokenIssuerDto) {
    KeyManagerDto keyManagerDto = new KeyManagerDto();
    keyManagerDto.setIssuer(tokenIssuerDto.getIssuer());
    keyManagerDto.setName(APIConstants.KeyManager.DEFAULT_KEY_MANAGER);
    JWTValidator jwtValidator = new JWTValidatorImpl();
    jwtValidator.loadTokenIssuerConfiguration(tokenIssuerDto);
    keyManagerDto.setJwtValidator(jwtValidator);
    globalJWTValidatorMap.put(tokenIssuerDto.getIssuer(), keyManagerDto);
}
Also used : JWTValidatorImpl(org.wso2.carbon.apimgt.impl.jwt.JWTValidatorImpl) OrganizationKeyManagerDto(org.wso2.carbon.apimgt.impl.dto.OrganizationKeyManagerDto) KeyManagerDto(org.wso2.carbon.apimgt.impl.dto.KeyManagerDto) JWTValidator(org.wso2.carbon.apimgt.impl.jwt.JWTValidator)

Example 17 with KeyManagerDTO

use of org.wso2.carbon.apimgt.rest.api.admin.v1.dto.KeyManagerDTO in project carbon-apimgt by wso2.

the class KeyManagerHolder method addKeyManagerConfiguration.

public static void addKeyManagerConfiguration(String organization, String name, String type, KeyManagerConfiguration keyManagerConfiguration) throws APIManagementException {
    String issuer = (String) keyManagerConfiguration.getParameter(APIConstants.KeyManager.ISSUER);
    OrganizationKeyManagerDto organizationKeyManagerDto = organizationWiseMap.get(organization);
    if (organizationKeyManagerDto == null) {
        organizationKeyManagerDto = new OrganizationKeyManagerDto();
    }
    if (organizationKeyManagerDto.getKeyManagerByName(name) != null) {
        log.warn("Key Manager " + name + " already initialized in tenant " + organization);
    }
    if (keyManagerConfiguration.isEnabled() && !KeyManagerConfiguration.TokenType.EXCHANGED.equals(keyManagerConfiguration.getTokenType())) {
        KeyManager keyManager = null;
        JWTValidator jwtValidator = null;
        APIManagerConfiguration apiManagerConfiguration = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
        String defaultKeyManagerType = apiManagerConfiguration.getFirstProperty(APIConstants.DEFAULT_KEY_MANAGER_TYPE);
        KeyManagerConnectorConfiguration keyManagerConnectorConfiguration = ServiceReferenceHolder.getInstance().getKeyManagerConnectorConfiguration(type);
        if (keyManagerConnectorConfiguration != null) {
            if (StringUtils.isNotEmpty(keyManagerConnectorConfiguration.getImplementation())) {
                try {
                    keyManager = (KeyManager) Class.forName(keyManagerConnectorConfiguration.getImplementation()).newInstance();
                    keyManager.setTenantDomain(organization);
                    if (StringUtils.isNotEmpty(defaultKeyManagerType) && defaultKeyManagerType.equals(type)) {
                        keyManagerConfiguration.addParameter(APIConstants.KEY_MANAGER_USERNAME, apiManagerConfiguration.getFirstProperty(APIConstants.API_KEY_VALIDATOR_USERNAME));
                        keyManagerConfiguration.addParameter(APIConstants.KEY_MANAGER_PASSWORD, apiManagerConfiguration.getFirstProperty(APIConstants.API_KEY_VALIDATOR_PASSWORD));
                    }
                    keyManager.loadConfiguration(keyManagerConfiguration);
                } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                    throw new APIManagementException("Error while loading keyManager configuration", e);
                }
            }
            jwtValidator = getJWTValidator(keyManagerConfiguration, keyManagerConnectorConfiguration.getJWTValidator());
        } else {
            if (APIConstants.KeyManager.DEFAULT_KEY_MANAGER_TYPE.equals(type)) {
                keyManager = new AMDefaultKeyManagerImpl();
                keyManager.setTenantDomain(organization);
                keyManager.loadConfiguration(keyManagerConfiguration);
                jwtValidator = getJWTValidator(keyManagerConfiguration, null);
            }
        }
        KeyManagerDto keyManagerDto = new KeyManagerDto();
        keyManagerDto.setName(name);
        keyManagerDto.setIssuer(issuer);
        keyManagerDto.setJwtValidator(jwtValidator);
        keyManagerDto.setKeyManager(keyManager);
        organizationKeyManagerDto.putKeyManagerDto(keyManagerDto);
        organizationWiseMap.put(organization, organizationKeyManagerDto);
    }
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) OrganizationKeyManagerDto(org.wso2.carbon.apimgt.impl.dto.OrganizationKeyManagerDto) KeyManagerDto(org.wso2.carbon.apimgt.impl.dto.KeyManagerDto) AMDefaultKeyManagerImpl(org.wso2.carbon.apimgt.impl.AMDefaultKeyManagerImpl) KeyManagerConnectorConfiguration(org.wso2.carbon.apimgt.api.model.KeyManagerConnectorConfiguration) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OrganizationKeyManagerDto(org.wso2.carbon.apimgt.impl.dto.OrganizationKeyManagerDto) JWTValidator(org.wso2.carbon.apimgt.impl.jwt.JWTValidator) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager)

Example 18 with KeyManagerDTO

use of org.wso2.carbon.apimgt.rest.api.admin.v1.dto.KeyManagerDTO in project carbon-apimgt by wso2.

the class KeymanagersApiServiceImpl method toKeyManagerDTO.

public static KeyManagerDTO toKeyManagerDTO(String tenantDomain, KeyManagerConfigurationDTO keyManagerConfigurationDTO) {
    KeyManagerDTO keyManagerDTO = new KeyManagerDTO();
    keyManagerDTO.setEnabled(keyManagerConfigurationDTO.isEnabled());
    keyManagerDTO.setName(keyManagerConfigurationDTO.getName());
    keyManagerDTO.setTenantDomain(tenantDomain);
    keyManagerDTO.setType(keyManagerConfigurationDTO.getType());
    keyManagerDTO.setTokenType(KeyManagerDTO.TokenTypeEnum.fromValue(keyManagerConfigurationDTO.getTokenType()));
    keyManagerDTO.setConfiguration(keyManagerConfigurationDTO.getAdditionalProperties());
    return keyManagerDTO;
}
Also used : KeyManagerDTO(org.wso2.carbon.apimgt.internal.service.dto.KeyManagerDTO)

Example 19 with KeyManagerDTO

use of org.wso2.carbon.apimgt.rest.api.admin.v1.dto.KeyManagerDTO in project carbon-apimgt by wso2.

the class APIProviderImpl method deleteAPIFromDB.

/**
 * Deletes API from the database and delete local scopes and resource scope attachments from KM.
 *
 * @param api API to delete
 * @throws APIManagementException if fails to delete the API
 */
private void deleteAPIFromDB(API api) throws APIManagementException {
    APIIdentifier apiIdentifier = api.getId();
    int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName()));
    String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId);
    // Get local scopes for the given API which are not already assigned for different versions of the same API
    Set<String> localScopeKeysToDelete = apiMgtDAO.getUnversionedLocalScopeKeysForAPI(api.getUuid(), tenantId);
    // Get the URI Templates for the given API to detach the resources scopes from
    Set<URITemplate> uriTemplates = apiMgtDAO.getURITemplatesOfAPI(api.getUuid());
    // Detach all the resource scopes from the API resources in KM
    Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getTenantKeyManagers(tenantDomain);
    for (Map.Entry<String, KeyManagerDto> keyManagerDtoEntry : tenantKeyManagers.entrySet()) {
        KeyManager keyManager = keyManagerDtoEntry.getValue().getKeyManager();
        if (keyManager != null) {
            try {
                keyManager.detachResourceScopes(api, uriTemplates);
                if (log.isDebugEnabled()) {
                    log.debug("Resource scopes are successfully detached for the API : " + apiIdentifier + " from Key Manager :" + keyManagerDtoEntry.getKey() + ".");
                }
                // remove the local scopes from the KM
                for (String localScope : localScopeKeysToDelete) {
                    keyManager.deleteScope(localScope);
                }
                if (log.isDebugEnabled()) {
                    log.debug("Local scopes are successfully deleted for the API : " + apiIdentifier + " from Key Manager : " + keyManagerDtoEntry.getKey() + ".");
                }
            } catch (APIManagementException e) {
                log.error("Error while Detach and Delete Scope from Key Manager " + keyManagerDtoEntry.getKey(), e);
            }
        }
    }
    deleteScopes(localScopeKeysToDelete, tenantId);
    apiMgtDAO.deleteAPI(api.getUuid());
    if (log.isDebugEnabled()) {
        log.debug("API : " + apiIdentifier + " is successfully deleted from the database and Key Manager.");
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) 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 20 with KeyManagerDTO

use of org.wso2.carbon.apimgt.rest.api.admin.v1.dto.KeyManagerDTO in project carbon-apimgt by wso2.

the class APIProviderImpl method deleteAPI.

public void deleteAPI(String apiUuid, String organization) throws APIManagementException {
    boolean isError = false;
    int apiId = -1;
    API api = null;
    // get api object by uuid
    try {
        api = getAPIbyUUID(apiUuid, organization);
    } catch (APIManagementException e) {
        log.error("Error while getting API by uuid for deleting API " + apiUuid + " on organization " + organization);
        log.debug("Following steps will be skipped while deleting API " + apiUuid + "on organization " + organization + " due to api being null. " + "deleting Resource Registration from key managers, deleting on external API stores, " + "event publishing to gateways, logging audit message, extracting API details for " + "the recommendation system. ");
        isError = true;
    }
    // get api id from db
    try {
        apiId = apiMgtDAO.getAPIID(apiUuid);
    } catch (APIManagementException e) {
        log.error("Error while getting API ID from DB for deleting API " + apiUuid + " on organization " + organization, e);
        log.debug("Following steps will be skipped while deleting the API " + apiUuid + " on organization " + organization + "due to api id being null. cleanup workflow tasks of the API, " + "delete event publishing to gateways");
        isError = true;
    }
    // DB delete operations
    if (!isError && api != null) {
        try {
            deleteAPIRevisions(apiUuid, organization);
            deleteAPIFromDB(api);
            if (log.isDebugEnabled()) {
                String logMessage = "API Name: " + api.getId().getApiName() + ", API Version " + api.getId().getVersion() + " successfully removed from the database.";
                log.debug(logMessage);
            }
        } catch (APIManagementException e) {
            log.error("Error while executing API delete operations on DB for API " + apiUuid + " on organization " + organization, e);
            isError = true;
        }
    }
    // Deleting Resource Registration from key managers
    if (api != null && api.getId() != null && api.getId().toString() != null) {
        Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getTenantKeyManagers(tenantDomain);
        for (Map.Entry<String, KeyManagerDto> keyManagerDtoEntry : tenantKeyManagers.entrySet()) {
            KeyManager keyManager = keyManagerDtoEntry.getValue().getKeyManager();
            if (keyManager != null) {
                try {
                    keyManager.deleteRegisteredResourceByAPIId(api.getId().toString());
                    log.debug("API " + apiUuid + " on organization " + organization + " has successfully removed from the Key Manager " + keyManagerDtoEntry.getKey());
                } catch (APIManagementException e) {
                    log.error("Error while deleting Resource Registration for API " + apiUuid + " on organization " + organization + " in Key Manager " + keyManagerDtoEntry.getKey(), e);
                }
            }
        }
    }
    try {
        GatewayArtifactsMgtDAO.getInstance().deleteGatewayArtifacts(apiUuid);
        log.debug("API " + apiUuid + " on organization " + organization + " has successfully removed from the gateway artifacts.");
    } catch (APIManagementException e) {
        log.error("Error while executing API delete operation on gateway artifacts for API " + apiUuid, e);
        isError = true;
    }
    try {
        apiPersistenceInstance.deleteAPI(new Organization(organization), apiUuid);
        log.debug("API " + apiUuid + " on organization " + organization + " has successfully removed from the persistence instance.");
    } catch (APIPersistenceException e) {
        log.error("Error while executing API delete operation on persistence instance for API " + apiUuid + " on organization " + organization, e);
        isError = true;
    }
    // Deleting on external API stores
    if (api != null) {
        // gatewayType check is required when API Management is deployed on
        // other servers to avoid synapse
        // Check if there are already published external APIStores.If yes,removing APIs from them.
        Set<APIStore> apiStoreSet;
        try {
            apiStoreSet = getPublishedExternalAPIStores(apiUuid);
            WSO2APIPublisher wso2APIPublisher = new WSO2APIPublisher();
            if (apiStoreSet != null && !apiStoreSet.isEmpty()) {
                for (APIStore store : apiStoreSet) {
                    wso2APIPublisher.deleteFromStore(api.getId(), APIUtil.getExternalAPIStore(store.getName(), tenantId));
                }
            }
        } catch (APIManagementException e) {
            log.error("Error while executing API delete operation on external API stores for API " + apiUuid + " on organization " + organization, e);
            isError = true;
        }
    }
    if (apiId != -1) {
        try {
            cleanUpPendingAPIStateChangeTask(apiId, false);
        } catch (WorkflowException | APIManagementException e) {
            log.error("Error while executing API delete operation on cleanup workflow tasks for API " + apiUuid + " on organization " + organization, e);
            isError = true;
        }
    }
    // Delete event publishing to gateways
    if (api != null && apiId != -1) {
        APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_DELETE.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());
    } else {
        log.debug("Event has not published to gateways due to API id has failed to retrieve from DB for API " + apiUuid + " on organization " + organization);
    }
    // Logging audit message for API delete
    if (api != null) {
        JSONObject apiLogObject = new JSONObject();
        apiLogObject.put(APIConstants.AuditLogConstants.NAME, api.getId().getApiName());
        apiLogObject.put(APIConstants.AuditLogConstants.VERSION, api.getId().getVersion());
        apiLogObject.put(APIConstants.AuditLogConstants.PROVIDER, api.getId().getProviderName());
        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.API, apiLogObject.toString(), APIConstants.AuditLogConstants.DELETED, this.username);
    }
    // Extracting API details for the recommendation system
    if (api != null && recommendationEnvironment != null) {
        RecommenderEventPublisher extractor = new RecommenderDetailsExtractor(api, tenantDomain, APIConstants.DELETE_API);
        Thread recommendationThread = new Thread(extractor);
        recommendationThread.start();
    }
    // if one of the above has failed throw an error
    if (isError) {
        throw new APIManagementException("Error while deleting the API " + apiUuid + " on organization " + organization);
    }
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) RecommenderDetailsExtractor(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderDetailsExtractor) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) KeyManagerDto(org.wso2.carbon.apimgt.impl.dto.KeyManagerDto) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent) JSONObject(org.json.simple.JSONObject) RecommenderEventPublisher(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderEventPublisher) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) WSO2APIPublisher(org.wso2.carbon.apimgt.impl.publishers.WSO2APIPublisher) 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) APIStore(org.wso2.carbon.apimgt.api.model.APIStore)

Aggregations

KeyManagerDto (org.wso2.carbon.apimgt.impl.dto.KeyManagerDto)16 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)15 HashMap (java.util.HashMap)13 Map (java.util.Map)13 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)13 TreeMap (java.util.TreeMap)10 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)9 KeyManagerConfigurationDTO (org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO)5 Gson (com.google.gson.Gson)4 APIAdmin (org.wso2.carbon.apimgt.api.APIAdmin)4 APIAdminImpl (org.wso2.carbon.apimgt.impl.APIAdminImpl)4 JsonObject (com.google.gson.JsonObject)3 ArrayList (java.util.ArrayList)3 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)3 Scope (org.wso2.carbon.apimgt.api.model.Scope)3 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)3 KeyManagerDTO (org.wso2.carbon.apimgt.rest.api.admin.v1.dto.KeyManagerDTO)3 JsonArray (com.google.gson.JsonArray)2 HashSet (java.util.HashSet)2 List (java.util.List)2