Search in sources :

Example 36 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class GoogleAnalyticsConfigDeployer method invokeService.

private CloseableHttpResponse invokeService(String endpoint, String tenantDomain) throws IOException, ArtifactSynchronizerException {
    HttpGet method = new HttpGet(endpoint);
    URL url = new URL(endpoint);
    String username = eventHubConfigurationDto.getUsername();
    String password = eventHubConfigurationDto.getPassword();
    byte[] credentials = Base64.encodeBase64((username + APIConstants.DELEM_COLON + password).getBytes(APIConstants.DigestAuthConstants.CHARSET));
    int port = url.getPort();
    String protocol = url.getProtocol();
    method.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BASIC + new String(credentials, APIConstants.DigestAuthConstants.CHARSET));
    if (tenantDomain != null) {
        method.setHeader(APIConstants.HEADER_TENANT, tenantDomain);
    }
    HttpClient httpClient = APIUtil.getHttpClient(port, protocol);
    try {
        return APIUtil.executeHTTPRequest(method, httpClient);
    } catch (APIManagementException e) {
        throw new ArtifactSynchronizerException(e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArtifactSynchronizerException(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException) HttpGet(org.apache.http.client.methods.HttpGet) HttpClient(org.apache.http.client.HttpClient) URL(java.net.URL)

Example 37 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class SystemApplicationDAO method getClientCredentialsForApplication.

/**
 * Method to retrieve client credentials for a given application name
 *
 * @param appName required parameter
 * @return SystemApplicationDTO which hold the retrieved client credentials
 * @throws APIMgtDAOException
 */
public SystemApplicationDTO getClientCredentialsForApplication(String appName, String tenantDomain) throws APIMgtDAOException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    SystemApplicationDTO systemApplicationDTO = null;
    String getCredentialsQuery = SQLConstants.SystemApplicationConstants.GET_CLIENT_CREDENTIALS_FOR_APPLICATION;
    try {
        connection = APIMgtDBUtil.getConnection();
        connection.setAutoCommit(false);
        connection.commit();
        preparedStatement = connection.prepareStatement(getCredentialsQuery);
        preparedStatement.setString(1, appName);
        preparedStatement.setString(2, tenantDomain);
        resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            systemApplicationDTO = new SystemApplicationDTO();
            systemApplicationDTO.setConsumerKey(resultSet.getString("CONSUMER_KEY"));
            systemApplicationDTO.setConsumerSecret(resultSet.getString("CONSUMER_SECRET"));
        }
    } catch (SQLException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error while retrieving client credentials for application: " + appName);
        }
        handleException("Error while retrieving client credentials for application: " + appName, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(preparedStatement, connection, resultSet);
    }
    return systemApplicationDTO;
}
Also used : SQLException(java.sql.SQLException) SystemApplicationDTO(org.wso2.carbon.apimgt.impl.dto.SystemApplicationDTO) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 38 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class SubscriptionDataLoaderImpl method invokeService.

private String invokeService(String path, String tenantDomain) throws DataLoadingException, IOException {
    String serviceURLStr = getEventHubConfigurationDto.getServiceUrl().concat(APIConstants.INTERNAL_WEB_APP_EP);
    HttpGet method = new HttpGet(serviceURLStr + path);
    URL serviceURL = new URL(serviceURLStr + path);
    byte[] credentials = getServiceCredentials(getEventHubConfigurationDto);
    int servicePort = serviceURL.getPort();
    String serviceProtocol = serviceURL.getProtocol();
    method.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BASIC + new String(credentials, StandardCharsets.UTF_8));
    if (tenantDomain != null) {
        method.setHeader(APIConstants.HEADER_TENANT, tenantDomain);
    }
    HttpClient httpClient = APIUtil.getHttpClient(servicePort, serviceProtocol);
    HttpResponse httpResponse = null;
    int retryCount = 0;
    boolean retry = false;
    do {
        try {
            httpResponse = httpClient.execute(method);
            if (HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode()) {
                log.error("Could not retrieve subscriptions for tenantDomain: " + tenantDomain + ". Received response with status code " + httpResponse.getStatusLine().getStatusCode());
                throw new DataLoadingException("Error while retrieving subscription");
            }
            retry = false;
        } catch (IOException | DataLoadingException ex) {
            retryCount++;
            if (retryCount < retrievalRetries) {
                retry = true;
                log.warn("Failed retrieving " + path + " from remote endpoint: " + ex.getMessage() + ". Retrying after " + retrievalTimeoutInSeconds + " seconds.");
                try {
                    Thread.sleep(retrievalTimeoutInSeconds * 1000);
                } catch (InterruptedException e) {
                // Ignore
                }
            } else {
                throw ex;
            }
        }
    } while (retry);
    if (HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode()) {
        log.error("Could not retrieve subscriptions for tenantDomain : " + tenantDomain);
        throw new DataLoadingException("Error while retrieving subscription from " + path);
    }
    String responseString = EntityUtils.toString(httpResponse.getEntity(), UTF8);
    if (log.isDebugEnabled()) {
        log.debug("Response : " + responseString);
    }
    return responseString;
}
Also used : DataLoadingException(org.wso2.carbon.apimgt.keymgt.model.exception.DataLoadingException) HttpGet(org.apache.http.client.methods.HttpGet) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) URL(java.net.URL)

Example 39 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class RevokedJWTTokensRetriever method retrieveRevokedJWTTokensData.

/**
 * This method will retrieve revoked JWT tokens by calling a web service.
 *
 * @return List of RevokedJWTTokensDTOs.
 */
private RevokedJWTTokenDTO[] retrieveRevokedJWTTokensData() {
    try {
        // The resource resides in the throttle web app. Hence reading throttle configs
        String url = getEventHubConfiguration().getServiceUrl().concat(APIConstants.INTERNAL_WEB_APP_EP).concat("/revokedjwt");
        HttpGet method = new HttpGet(url);
        byte[] credentials = Base64.encodeBase64((getEventHubConfiguration().getUsername() + ":" + getEventHubConfiguration().getPassword()).getBytes(StandardCharsets.UTF_8));
        method.setHeader("Authorization", "Basic " + new String(credentials, StandardCharsets.UTF_8));
        URL keyMgtURL = new URL(url);
        int keyMgtPort = keyMgtURL.getPort();
        String keyMgtProtocol = keyMgtURL.getProtocol();
        HttpClient httpClient = APIUtil.getHttpClient(keyMgtPort, keyMgtProtocol);
        HttpResponse httpResponse = null;
        int retryCount = 0;
        boolean retry;
        do {
            try {
                httpResponse = httpClient.execute(method);
                retry = false;
            } catch (IOException ex) {
                retryCount++;
                if (retryCount < revokedJWTTokensRetrievalRetries) {
                    retry = true;
                    log.warn("Failed retrieving revoked JWT token signatures from remote endpoint: " + ex.getMessage() + ". Retrying after " + revokedJWTTokensRetrievalTimeoutInSeconds + " seconds...");
                    Thread.sleep(revokedJWTTokensRetrievalTimeoutInSeconds * 1000);
                } else {
                    throw ex;
                }
            }
        } while (retry);
        String responseString = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        if (responseString != null && !responseString.isEmpty()) {
            return new Gson().fromJson(responseString, RevokedJWTTokenDTO[].class);
        }
    } catch (IOException | InterruptedException e) {
        log.error("Exception when retrieving revoked JWT tokens from remote endpoint ", e);
    }
    return null;
}
Also used : 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) RevokedJWTTokenDTO(org.wso2.carbon.apimgt.gateway.dto.RevokedJWTTokenDTO) HttpClient(org.apache.http.client.HttpClient)

Example 40 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class APIKeyMgtRemoteUserStoreMgtService method authenticate.

/**
 * validates a username,password combination. Works for any tenant domain.
 * @param username username of the user(including tenant domain)
 * @param password password of the user
 * @return true if username,password is correct
 * @throws APIManagementException
 */
public boolean authenticate(String username, String password) throws APIManagementException {
    String tenantDomain = MultitenantUtils.getTenantDomain(username);
    PrivilegedCarbonContext.startTenantFlow();
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
    UserStoreManager userStoreManager;
    boolean isAuthenticated = false;
    try {
        userStoreManager = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getUserStoreManager();
        String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(username);
        isAuthenticated = userStoreManager.authenticate(tenantAwareUserName, password);
    } catch (UserStoreException e) {
        APIUtil.handleException("Error occurred while validating credentials of user " + username, e);
    } finally {
        PrivilegedCarbonContext.getThreadLocalCarbonContext().endTenantFlow();
    }
    return isAuthenticated;
}
Also used : UserStoreException(org.wso2.carbon.user.api.UserStoreException) UserStoreManager(org.wso2.carbon.user.api.UserStoreManager)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)18 HttpClient (org.apache.http.client.HttpClient)12 URL (java.net.URL)10 ArrayList (java.util.ArrayList)9 HttpGet (org.apache.http.client.methods.HttpGet)9 IOException (java.io.IOException)8 HashMap (java.util.HashMap)8 HttpResponse (org.apache.http.HttpResponse)8 Gson (com.google.gson.Gson)6 JSONObject (org.json.simple.JSONObject)6 Test (org.junit.Test)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 Test (org.testng.annotations.Test)6 Response (feign.Response)4 WorkflowProperties (org.wso2.carbon.apimgt.impl.dto.WorkflowProperties)4 JSONParser (org.json.simple.parser.JSONParser)3 ParseException (org.json.simple.parser.ParseException)3 DCRMServiceStub (org.wso2.carbon.apimgt.core.auth.DCRMServiceStub)3 OAuth2ServiceStubs (org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs)3 ScopeRegistration (org.wso2.carbon.apimgt.core.auth.ScopeRegistration)3