Search in sources :

Example 11 with KeyManagerConfiguration

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

the class AMDefaultKeyManagerImpl method loadConfiguration.

@Override
public void loadConfiguration(KeyManagerConfiguration configuration) throws APIManagementException {
    this.configuration = configuration;
    String username = (String) configuration.getParameter(APIConstants.KEY_MANAGER_USERNAME);
    String password = (String) configuration.getParameter(APIConstants.KEY_MANAGER_PASSWORD);
    String keyManagerServiceUrl = (String) configuration.getParameter(APIConstants.AUTHSERVER_URL);
    String dcrEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.CLIENT_REGISTRATION_ENDPOINT) != null) {
        dcrEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.CLIENT_REGISTRATION_ENDPOINT);
    } else {
        dcrEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(getTenantAwareContext().trim()).concat(APIConstants.KeyManager.KEY_MANAGER_OPERATIONS_DCR_ENDPOINT);
    }
    String tokenEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.TOKEN_ENDPOINT) != null) {
        tokenEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.TOKEN_ENDPOINT);
    } else {
        tokenEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat("/oauth2/token");
    }
    addKeyManagerConfigsAsSystemProperties(tokenEndpoint);
    String revokeEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.REVOKE_ENDPOINT) != null) {
        revokeEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.REVOKE_ENDPOINT);
    } else {
        revokeEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat("/oauth2/revoke");
    }
    String scopeEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.SCOPE_MANAGEMENT_ENDPOINT) != null) {
        scopeEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.SCOPE_MANAGEMENT_ENDPOINT);
    } else {
        scopeEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(getTenantAwareContext().trim()).concat(APIConstants.KEY_MANAGER_OAUTH2_SCOPES_REST_API_BASE_PATH);
    }
    String introspectionEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.INTROSPECTION_ENDPOINT) != null) {
        introspectionEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.INTROSPECTION_ENDPOINT);
    } else {
        introspectionEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(getTenantAwareContext().trim()).concat("/oauth2/introspect");
    }
    String userInfoEndpoint;
    if (configuration.getParameter(APIConstants.KeyManager.USERINFO_ENDPOINT) != null) {
        userInfoEndpoint = (String) configuration.getParameter(APIConstants.KeyManager.USERINFO_ENDPOINT);
    } else {
        userInfoEndpoint = keyManagerServiceUrl.split("/" + APIConstants.SERVICES_URL_RELATIVE_PATH)[0].concat(getTenantAwareContext().trim()).concat(APIConstants.KeyManager.KEY_MANAGER_OPERATIONS_USERINFO_ENDPOINT);
    }
    dcrClient = Feign.builder().client(new ApacheFeignHttpClient(APIUtil.getHttpClient(dcrEndpoint))).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger()).requestInterceptor(new BasicAuthRequestInterceptor(username, password)).requestInterceptor(new TenantHeaderInterceptor(tenantDomain)).errorDecoder(new KMClientErrorDecoder()).target(DCRClient.class, dcrEndpoint);
    authClient = Feign.builder().client(new ApacheFeignHttpClient(APIUtil.getHttpClient(tokenEndpoint))).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger()).errorDecoder(new KMClientErrorDecoder()).encoder(new FormEncoder()).target(AuthClient.class, tokenEndpoint);
    introspectionClient = Feign.builder().client(new ApacheFeignHttpClient(APIUtil.getHttpClient(introspectionEndpoint))).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger()).requestInterceptor(new BasicAuthRequestInterceptor(username, password)).requestInterceptor(new TenantHeaderInterceptor(tenantDomain)).errorDecoder(new KMClientErrorDecoder()).encoder(new FormEncoder()).target(IntrospectionClient.class, introspectionEndpoint);
    scopeClient = Feign.builder().client(new ApacheFeignHttpClient(APIUtil.getHttpClient(scopeEndpoint))).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger()).requestInterceptor(new BasicAuthRequestInterceptor(username, password)).requestInterceptor(new TenantHeaderInterceptor(tenantDomain)).errorDecoder(new KMClientErrorDecoder()).target(ScopeClient.class, scopeEndpoint);
    userClient = Feign.builder().client(new ApacheFeignHttpClient(APIUtil.getHttpClient(userInfoEndpoint))).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger()).requestInterceptor(new BasicAuthRequestInterceptor(username, password)).requestInterceptor(new TenantHeaderInterceptor(tenantDomain)).errorDecoder(new KMClientErrorDecoder()).target(UserClient.class, userInfoEndpoint);
}
Also used : UserClient(org.wso2.carbon.apimgt.impl.kmclient.model.UserClient) BasicAuthRequestInterceptor(feign.auth.BasicAuthRequestInterceptor) Slf4jLogger(feign.slf4j.Slf4jLogger) AuthClient(org.wso2.carbon.apimgt.impl.kmclient.model.AuthClient) TenantHeaderInterceptor(org.wso2.carbon.apimgt.impl.kmclient.model.TenantHeaderInterceptor) DCRClient(org.wso2.carbon.apimgt.impl.kmclient.model.DCRClient) KMClientErrorDecoder(org.wso2.carbon.apimgt.impl.kmclient.KMClientErrorDecoder) GsonEncoder(feign.gson.GsonEncoder) ScopeClient(org.wso2.carbon.apimgt.impl.kmclient.model.ScopeClient) IntrospectionClient(org.wso2.carbon.apimgt.impl.kmclient.model.IntrospectionClient) GsonDecoder(feign.gson.GsonDecoder) ApacheFeignHttpClient(org.wso2.carbon.apimgt.impl.kmclient.ApacheFeignHttpClient) FormEncoder(org.wso2.carbon.apimgt.impl.kmclient.FormEncoder)

Example 12 with KeyManagerConfiguration

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

the class KeyManagerConfigurationDataRetriever method run.

@Override
public void run() {
    APIManagerConfiguration apiManagerConfiguration = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
    if (apiManagerConfiguration != null) {
        EventHubConfigurationDto eventHubConfigurationDto = apiManagerConfiguration.getEventHubConfigurationDto();
        if (eventHubConfigurationDto != null && eventHubConfigurationDto.isEnabled()) {
            try {
                String url = eventHubConfigurationDto.getServiceUrl().concat(APIConstants.INTERNAL_WEB_APP_EP).concat("/keymanagers");
                byte[] credentials = Base64.encodeBase64((eventHubConfigurationDto.getUsername() + ":" + eventHubConfigurationDto.getPassword()).getBytes());
                HttpGet method = new HttpGet(url);
                method.setHeader("Authorization", "Basic " + new String(credentials, StandardCharsets.UTF_8));
                method.setHeader(APIConstants.HEADER_TENANT, tenantDomain);
                URL configUrl = new URL(url);
                int port = configUrl.getPort();
                String protocol = configUrl.getProtocol();
                HttpClient httpClient = APIUtil.getHttpClient(port, protocol);
                HttpResponse httpResponse = null;
                int retryCount = 0;
                boolean retry;
                do {
                    try {
                        httpResponse = httpClient.execute(method);
                        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                            String responseString = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
                            KeyManagerConfiguration[] keyManagerConfigurations = new Gson().fromJson(responseString, KeyManagerConfiguration[].class);
                            for (KeyManagerConfiguration keyManagerConfiguration : keyManagerConfigurations) {
                                if (keyManagerConfiguration.isEnabled()) {
                                    try {
                                        ServiceReferenceHolder.getInstance().getKeyManagerConfigurationService().addKeyManagerConfiguration(keyManagerConfiguration.getTenantDomain(), keyManagerConfiguration.getName(), keyManagerConfiguration.getType(), keyManagerConfiguration);
                                    } catch (APIManagementException e) {
                                        log.error("Error while configuring Key Manager " + keyManagerConfiguration.getName() + " in tenant " + keyManagerConfiguration.getTenantDomain(), e);
                                    }
                                }
                            }
                            retry = false;
                        } else {
                            retry = true;
                            retryCount++;
                        }
                    } catch (IOException ex) {
                        retryCount++;
                        int maxRetries = 15;
                        if (retryCount < maxRetries) {
                            retry = true;
                            long retryTimeout = (long) Math.min(Math.pow(2, retryCount), 300);
                            log.warn("Failed retrieving Key Manager Configurations from remote " + "endpoint: " + ex.getMessage() + ". Retrying after " + retryTimeout + " seconds...");
                            Thread.sleep(retryTimeout * 1000);
                        } else {
                            throw ex;
                        }
                    }
                } while (retry);
            } catch (InterruptedException | IOException e) {
                log.error("Error while retrieving key manager configurations", e);
            }
        }
    }
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) Gson(com.google.gson.Gson) IOException(java.io.IOException) URL(java.net.URL) EventHubConfigurationDto(org.wso2.carbon.apimgt.impl.dto.EventHubConfigurationDto) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpClient(org.apache.http.client.HttpClient) KeyManagerConfiguration(org.wso2.carbon.apimgt.api.model.KeyManagerConfiguration)

Example 13 with KeyManagerConfiguration

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

the class KeyManagerJMSMessageListener method onMessage.

public void onMessage(Message message) {
    try {
        if (message != null) {
            if (log.isDebugEnabled()) {
                log.debug("Event received in JMS Event Receiver - " + message);
            }
            Topic jmsDestination = (Topic) message.getJMSDestination();
            if (message instanceof TextMessage) {
                String textMessage = ((TextMessage) message).getText();
                JsonNode payloadData = new ObjectMapper().readTree(textMessage).path(APIConstants.EVENT_PAYLOAD).path(APIConstants.EVENT_PAYLOAD_DATA);
                if (JMSConstants.TOPIC_KEY_MANAGER.equalsIgnoreCase(jmsDestination.getTopicName())) {
                    if (APIConstants.KeyManager.KeyManagerEvent.KEY_MANAGER_CONFIGURATION.equals(payloadData.get(APIConstants.KeyManager.KeyManagerEvent.EVENT_TYPE).asText())) {
                        String name = payloadData.get(APIConstants.KeyManager.KeyManagerEvent.NAME).asText();
                        String organization = payloadData.get(APIConstants.KeyManager.KeyManagerEvent.ORGANIZATION).asText();
                        String action = payloadData.get(APIConstants.KeyManager.KeyManagerEvent.ACTION).asText();
                        String type = payloadData.get(APIConstants.KeyManager.KeyManagerEvent.TYPE).asText();
                        String tokenType = payloadData.get(APIConstants.KeyManager.KeyManagerEvent.TOKEN_TYPE).asText();
                        boolean enabled = payloadData.get(APIConstants.KeyManager.KeyManagerEvent.ENABLED).asBoolean();
                        String value = payloadData.get(APIConstants.KeyManager.KeyManagerEvent.VALUE).asText();
                        if (StringUtils.isNotEmpty(value)) {
                            KeyManagerConfiguration keyManagerConfiguration = APIUtil.toKeyManagerConfiguration(value);
                            keyManagerConfiguration.setTokenType(KeyManagerConfiguration.TokenType.valueOf(tokenType.toUpperCase()));
                            keyManagerConfiguration.setEnabled(enabled);
                            keyManagerConfiguration.setName(name);
                            keyManagerConfiguration.setType(type);
                            keyManagerConfiguration.setTenantDomain(organization);
                            if (APIConstants.KeyManager.KeyManagerEvent.ACTION_ADD.equals(action)) {
                                ServiceReferenceHolder.getInstance().getKeyManagerService().addKeyManagerConfiguration(organization, name, type, keyManagerConfiguration);
                            }
                            if (APIConstants.KeyManager.KeyManagerEvent.ACTION_UPDATE.equals(action)) {
                                ServiceReferenceHolder.getInstance().getKeyManagerService().updateKeyManagerConfiguration(organization, name, type, keyManagerConfiguration);
                            }
                        }
                        if (APIConstants.KeyManager.KeyManagerEvent.ACTION_DELETE.equals(action)) {
                            ServiceReferenceHolder.getInstance().getKeyManagerService().removeKeyManagerConfiguration(organization, name);
                        }
                    }
                }
            } else {
                log.warn("Event dropped due to unsupported message type " + message.getClass());
            }
        } else {
            log.warn("Dropping the empty/null event received through jms receiver");
        }
    } catch (JMSException | JsonProcessingException e) {
        log.error("JMSException occurred when processing the received message ", e);
    } catch (APIManagementException e) {
        log.error("Error occurred while registering Key Manager", e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonNode(com.fasterxml.jackson.databind.JsonNode) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) KeyManagerConfiguration(org.wso2.carbon.apimgt.api.model.KeyManagerConfiguration)

Example 14 with KeyManagerConfiguration

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

the class ApplicationRegistrationSimpleWorkflowExecutorTest method init.

@Before
public void init() throws APIManagementException {
    PowerMockito.mockStatic(ApiMgtDAO.class);
    PowerMockito.mockStatic(KeyManagerHolder.class);
    apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    keyManager = Mockito.mock(KeyManager.class);
    application = new Application("test", new Subscriber("testUser"));
    oAuthAppRequest = new OAuthAppRequest();
    oAuthApplicationInfo = new OAuthApplicationInfo();
    oAuthAppRequest.setOAuthApplicationInfo(oAuthApplicationInfo);
    workflowDTO = new ApplicationRegistrationWorkflowDTO();
    workflowDTO.setWorkflowReference("1");
    workflowDTO.setApplication(application);
    workflowDTO.setAppInfoDTO(oAuthAppRequest);
    workflowDTO.setKeyManager("default");
    KeyManagerConfigurationDTO kmConfigDTO = new KeyManagerConfigurationDTO();
    kmConfigDTO.setOrganization("carbon.super");
    kmConfigDTO.setName("default");
    PowerMockito.when(apiMgtDAO.getKeyManagerConfigurationByUUID("default")).thenReturn(kmConfigDTO);
    PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
    PowerMockito.when(KeyManagerHolder.getKeyManagerInstance("carbon.super", "default")).thenReturn(keyManager);
    KeyManagerConfiguration keyManagerConfiguration = new KeyManagerConfiguration();
    Mockito.when(keyManager.getKeyManagerConfiguration()).thenReturn(keyManagerConfiguration);
    applicationRegistrationSimpleWorkflowExecutor = new ApplicationRegistrationSimpleWorkflowExecutor();
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) ApplicationRegistrationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) OAuthAppRequest(org.wso2.carbon.apimgt.api.model.OAuthAppRequest) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager) Application(org.wso2.carbon.apimgt.api.model.Application) KeyManagerConfiguration(org.wso2.carbon.apimgt.api.model.KeyManagerConfiguration) Before(org.junit.Before)

Example 15 with KeyManagerConfiguration

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

the class KeymanagersApiServiceImpl method keymanagersGet.

public Response keymanagersGet(String xWSO2Tenant, MessageContext messageContext) {
    xWSO2Tenant = SubscriptionValidationDataUtil.validateTenantDomain(xWSO2Tenant, messageContext);
    try {
        APIAdmin apiAdmin = new APIAdminImpl();
        List<KeyManagerConfigurationDTO> keyManagerConfigurations = apiAdmin.getKeyManagerConfigurationsByOrganization(xWSO2Tenant);
        List<KeyManagerDTO> keyManagerDTOList = new ArrayList<>();
        for (KeyManagerConfigurationDTO keyManagerConfiguration : keyManagerConfigurations) {
            keyManagerDTOList.add(toKeyManagerDTO(xWSO2Tenant, keyManagerConfiguration));
        }
        return Response.ok(keyManagerDTOList).build();
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while retrieving key manager configurations", e, log);
    }
    return null;
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIAdmin(org.wso2.carbon.apimgt.api.APIAdmin) ArrayList(java.util.ArrayList) KeyManagerDTO(org.wso2.carbon.apimgt.internal.service.dto.KeyManagerDTO) APIAdminImpl(org.wso2.carbon.apimgt.impl.APIAdminImpl)

Aggregations

KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)14 KeyManagerConfiguration (org.wso2.carbon.apimgt.api.model.KeyManagerConfiguration)14 KeyManagerConfigurationDTO (org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO)12 Test (org.junit.Test)11 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)11 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)10 ModelKeyManagerForTest (org.wso2.carbon.apimgt.impl.factory.ModelKeyManagerForTest)8 HashMap (java.util.HashMap)7 OAuthAppRequest (org.wso2.carbon.apimgt.api.model.OAuthAppRequest)7 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)7 JSONObject (org.json.simple.JSONObject)4 KeyMgtConfigurations (org.wso2.carbon.apimgt.core.configuration.models.KeyMgtConfigurations)4 Gson (com.google.gson.Gson)3 AccessTokenInfo (org.wso2.carbon.apimgt.api.model.AccessTokenInfo)3 AccessTokenRequest (org.wso2.carbon.apimgt.api.model.AccessTokenRequest)3 Application (org.wso2.carbon.apimgt.api.model.Application)3 Subscriber (org.wso2.carbon.apimgt.api.model.Subscriber)3 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2