Search in sources :

Example 91 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project wildfly by wildfly.

the class MicroProfileMetricsSecuredEndpointTestCase method securedHTTPEndpoint.

@Test
public void securedHTTPEndpoint() throws Exception {
    final String endpointURL = "http://" + managementClient.getMgmtAddress() + ":" + managementClient.getMgmtPort() + "/metrics";
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("testSuite", "testSuitePassword"));
        HttpClientContext hcContext = HttpClientContext.create();
        hcContext.setCredentialsProvider(credentialsProvider);
        CloseableHttpResponse resp = client.execute(new HttpGet(endpointURL), hcContext);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        String content = EntityUtils.toString(resp.getEntity());
        resp.close();
        // MicroProfile Metrics 2.0 has changed its Prometheus conversion format from "base:x" to "base_x"
        String expectedMetric = "base_jvm_uptime_seconds";
        assertTrue(expectedMetric + " metric is expected in the response", content.contains(expectedMetric));
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Test(org.junit.Test)

Example 92 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project wildfly by wildfly.

the class BootCheckApplication method invoke.

private Response invoke(final String url) throws IOException {
    HttpClientBuilder builder = HttpClients.custom();
    builder.setDefaultRequestConfig(RequestConfig.copy(RequestConfig.DEFAULT).setConnectTimeout(5000).build());
    builder.setDefaultSocketConfig(SocketConfig.copy(SocketConfig.DEFAULT).setSoTimeout(5000).build());
    try (CloseableHttpClient client = builder.build()) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("testSuite", "testSuitePassword"));
        HttpClientContext hcContext = HttpClientContext.create();
        hcContext.setCredentialsProvider(credentialsProvider);
        CloseableHttpResponse resp = client.execute(new HttpGet(url), hcContext);
        int respCode = resp.getStatusLine().getStatusCode();
        HttpEntity entity = resp.getEntity();
        String content = entity == null ? null : EntityUtils.toString(entity);
        resp.close();
        return new Response(respCode, content);
    }
}
Also used : CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 93 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project platform_external_apache-http by android.

the class DefaultRequestDirector method createTunnelToTarget.

// establishConnection
/**
 * Creates a tunnel to the target server.
 * The connection must be established to the (last) proxy.
 * A CONNECT request for tunnelling through the proxy will
 * be created and sent, the response received and checked.
 * This method does <i>not</i> update the connection with
 * information about the tunnel, that is left to the caller.
 *
 * @param route     the route to establish
 * @param context   the context for request execution
 *
 * @return  <code>true</code> if the tunnelled route is secure,
 *          <code>false</code> otherwise.
 *          The implementation here always returns <code>false</code>,
 *          but derived classes may override.
 *
 * @throws HttpException    in case of a problem
 * @throws IOException      in case of an IO problem
 */
protected boolean createTunnelToTarget(HttpRoute route, HttpContext context) throws HttpException, IOException {
    HttpHost proxy = route.getProxyHost();
    HttpHost target = route.getTargetHost();
    HttpResponse response = null;
    boolean done = false;
    while (!done) {
        done = true;
        if (!this.managedConn.isOpen()) {
            this.managedConn.open(route, context, this.params);
        }
        HttpRequest connect = createConnectRequest(route, context);
        String agent = HttpProtocolParams.getUserAgent(params);
        if (agent != null) {
            connect.addHeader(HTTP.USER_AGENT, agent);
        }
        connect.addHeader(HTTP.TARGET_HOST, target.toHostString());
        AuthScheme authScheme = this.proxyAuthState.getAuthScheme();
        AuthScope authScope = this.proxyAuthState.getAuthScope();
        Credentials creds = this.proxyAuthState.getCredentials();
        if (creds != null) {
            if (authScope != null || !authScheme.isConnectionBased()) {
                try {
                    connect.addHeader(authScheme.authenticate(creds, connect));
                } catch (AuthenticationException ex) {
                    if (this.log.isErrorEnabled()) {
                        this.log.error("Proxy authentication error: " + ex.getMessage());
                    }
                }
            }
        }
        response = requestExec.execute(connect, this.managedConn, context);
        int status = response.getStatusLine().getStatusCode();
        if (status < 200) {
            throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
        }
        CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
        if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
            if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
                this.log.debug("Proxy requested authentication");
                Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
                try {
                    processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
                } catch (AuthenticationException ex) {
                    if (this.log.isWarnEnabled()) {
                        this.log.warn("Authentication error: " + ex.getMessage());
                        break;
                    }
                }
                updateAuthState(this.proxyAuthState, proxy, credsProvider);
                if (this.proxyAuthState.getCredentials() != null) {
                    done = false;
                    // Retry request
                    if (this.reuseStrategy.keepAlive(response, context)) {
                        this.log.debug("Connection kept alive");
                        // Consume response content
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            entity.consumeContent();
                        }
                    } else {
                        this.managedConn.close();
                    }
                }
            } else {
                // Reset proxy auth scope
                this.proxyAuthState.setAuthScope(null);
            }
        }
    }
    int status = response.getStatusLine().getStatusCode();
    if (status > 299) {
        // Buffer response content
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            response.setEntity(new BufferedHttpEntity(entity));
        }
        this.managedConn.close();
        throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
    }
    this.managedConn.markReusable();
    // Leave it to derived classes, consider insecure by default here.
    return false;
}
Also used : HttpRequest(org.apache.http.HttpRequest) BasicHttpRequest(org.apache.http.message.BasicHttpRequest) AbortableHttpRequest(org.apache.http.client.methods.AbortableHttpRequest) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) AuthenticationException(org.apache.http.auth.AuthenticationException) HttpResponse(org.apache.http.HttpResponse) CredentialsProvider(org.apache.http.client.CredentialsProvider) AuthScheme(org.apache.http.auth.AuthScheme) Header(org.apache.http.Header) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) HttpException(org.apache.http.HttpException) Credentials(org.apache.http.auth.Credentials)

Example 94 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project platform_external_apache-http by android.

the class DefaultRequestDirector method handleResponse.

/**
 * Analyzes a response to check need for a followup.
 *
 * @param roureq    the request and route.
 * @param response  the response to analayze
 * @param context   the context used for the current request execution
 *
 * @return  the followup request and route if there is a followup, or
 *          <code>null</code> if the response should be returned as is
 *
 * @throws HttpException    in case of a problem
 * @throws IOException      in case of an IO problem
 */
protected RoutedRequest handleResponse(RoutedRequest roureq, HttpResponse response, HttpContext context) throws HttpException, IOException {
    HttpRoute route = roureq.getRoute();
    HttpHost proxy = route.getProxyHost();
    RequestWrapper request = roureq.getRequest();
    HttpParams params = request.getParams();
    if (HttpClientParams.isRedirecting(params) && this.redirectHandler.isRedirectRequested(response, context)) {
        if (redirectCount >= maxRedirects) {
            throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
        }
        redirectCount++;
        URI uri = this.redirectHandler.getLocationURI(response, context);
        HttpHost newTarget = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        HttpGet redirect = new HttpGet(uri);
        HttpRequest orig = request.getOriginal();
        redirect.setHeaders(orig.getAllHeaders());
        RequestWrapper wrapper = new RequestWrapper(redirect);
        wrapper.setParams(params);
        HttpRoute newRoute = determineRoute(newTarget, wrapper, context);
        RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute);
        if (this.log.isDebugEnabled()) {
            this.log.debug("Redirecting to '" + uri + "' via " + newRoute);
        }
        return newRequest;
    }
    CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
    if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
        if (this.targetAuthHandler.isAuthenticationRequested(response, context)) {
            HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            if (target == null) {
                target = route.getTargetHost();
            }
            this.log.debug("Target requested authentication");
            Map<String, Header> challenges = this.targetAuthHandler.getChallenges(response, context);
            try {
                processChallenges(challenges, this.targetAuthState, this.targetAuthHandler, response, context);
            } catch (AuthenticationException ex) {
                if (this.log.isWarnEnabled()) {
                    this.log.warn("Authentication error: " + ex.getMessage());
                    return null;
                }
            }
            updateAuthState(this.targetAuthState, target, credsProvider);
            if (this.targetAuthState.getCredentials() != null) {
                // Re-try the same request via the same route
                return roureq;
            } else {
                return null;
            }
        } else {
            // Reset target auth scope
            this.targetAuthState.setAuthScope(null);
        }
        if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
            this.log.debug("Proxy requested authentication");
            Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
            try {
                processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
            } catch (AuthenticationException ex) {
                if (this.log.isWarnEnabled()) {
                    this.log.warn("Authentication error: " + ex.getMessage());
                    return null;
                }
            }
            updateAuthState(this.proxyAuthState, proxy, credsProvider);
            if (this.proxyAuthState.getCredentials() != null) {
                // Re-try the same request via the same route
                return roureq;
            } else {
                return null;
            }
        } else {
            // Reset proxy auth scope
            this.proxyAuthState.setAuthScope(null);
        }
    }
    return null;
}
Also used : HttpRequest(org.apache.http.HttpRequest) BasicHttpRequest(org.apache.http.message.BasicHttpRequest) AbortableHttpRequest(org.apache.http.client.methods.AbortableHttpRequest) AuthenticationException(org.apache.http.auth.AuthenticationException) HttpGet(org.apache.http.client.methods.HttpGet) CredentialsProvider(org.apache.http.client.CredentialsProvider) URI(java.net.URI) HttpRoute(org.apache.http.conn.routing.HttpRoute) HttpParams(org.apache.http.params.HttpParams) Header(org.apache.http.Header) HttpHost(org.apache.http.HttpHost) RedirectException(org.apache.http.client.RedirectException)

Example 95 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project midpoint by Evolveum.

the class SmsMessageTransport method send.

@Override
public void send(Message message, String transportName, Event event, Task task, OperationResult parentResult) {
    OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
    result.addArbitraryObjectCollectionAsParam("message recipient(s)", message.getTo());
    result.addParam("message subject", message.getSubject());
    String logToFile = configuration.getLogToFile();
    if (logToFile != null) {
        TransportUtil.logToFile(logToFile, TransportUtil.formatToFileNew(message, transportName), LOGGER);
    }
    String file = configuration.getRedirectToFile();
    int optionsForFilteringRecipient = TransportUtil.optionsForFilteringRecipient(configuration);
    List<String> allowedRecipientTo = new ArrayList<>();
    List<String> forbiddenRecipientTo = new ArrayList<>();
    if (optionsForFilteringRecipient != 0) {
        TransportUtil.validateRecipient(allowedRecipientTo, forbiddenRecipientTo, message.getTo(), configuration, task, result, transportSupport.expressionFactory(), MiscSchemaUtil.getExpressionProfile(), LOGGER);
        if (file != null) {
            if (!forbiddenRecipientTo.isEmpty()) {
                message.setTo(forbiddenRecipientTo);
                writeToFile(message, file, null, emptyList(), null, result);
            }
            message.setTo(allowedRecipientTo);
        }
    } else if (file != null) {
        writeToFile(message, file, null, emptyList(), null, result);
        return;
    }
    if (configuration.getGateway().isEmpty()) {
        String msg = "SMS gateway(s) are not defined, notification to " + message.getTo() + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }
    String from;
    if (message.getFrom() != null) {
        from = message.getFrom();
    } else if (configuration.getDefaultFrom() != null) {
        from = configuration.getDefaultFrom();
    } else {
        from = "";
    }
    if (message.getTo().isEmpty()) {
        if (optionsForFilteringRecipient != 0) {
            String msg = "After recipient validation there is no recipient to send the notification to.";
            LOGGER.debug(msg);
            result.recordSuccess();
        } else {
            String msg = "There is no recipient to send the notification to.";
            LOGGER.warn(msg);
            result.recordWarning(msg);
        }
        return;
    }
    List<String> to = message.getTo();
    assert to.size() > 0;
    for (SmsGatewayConfigurationType smsGatewayConfigurationType : configuration.getGateway()) {
        OperationResult resultForGateway = result.createSubresult(DOT_CLASS + "send.forGateway");
        resultForGateway.addContext("gateway name", smsGatewayConfigurationType.getName());
        try {
            VariablesMap variables = getDefaultVariables(from, to, message);
            HttpMethodType method = defaultIfNull(smsGatewayConfigurationType.getMethod(), HttpMethodType.GET);
            ExpressionType urlExpression = defaultIfNull(smsGatewayConfigurationType.getUrlExpression(), null);
            String url = evaluateExpressionChecked(urlExpression, variables, "sms gateway request url", task, result);
            String proxyHost = smsGatewayConfigurationType.getProxyHost();
            String proxyPort = smsGatewayConfigurationType.getProxyPort();
            LOGGER.debug("Sending SMS to URL {} via proxy host {} and port {} (method {})", url, proxyHost, proxyPort, method);
            if (url == null) {
                throw new IllegalArgumentException("No URL specified");
            }
            List<String> headersList = evaluateExpressionsChecked(smsGatewayConfigurationType.getHeadersExpression(), variables, "sms gateway request headers", task, result);
            LOGGER.debug("Using request headers:\n{}", headersList);
            String encoding = defaultIfNull(smsGatewayConfigurationType.getBodyEncoding(), StandardCharsets.ISO_8859_1.name());
            String body = evaluateExpressionChecked(smsGatewayConfigurationType.getBodyExpression(), variables, "sms gateway request body", task, result);
            LOGGER.debug("Using request body text (encoding: {}):\n{}", encoding, body);
            if (smsGatewayConfigurationType.getLogToFile() != null) {
                TransportUtil.logToFile(smsGatewayConfigurationType.getLogToFile(), formatToFile(message, url, headersList, body), LOGGER);
            }
            if (smsGatewayConfigurationType.getRedirectToFile() != null) {
                writeToFile(message, smsGatewayConfigurationType.getRedirectToFile(), url, headersList, body, resultForGateway);
                result.computeStatus();
                return;
            } else {
                HttpClientBuilder builder = HttpClientBuilder.create();
                String username = smsGatewayConfigurationType.getUsername();
                ProtectedStringType password = smsGatewayConfigurationType.getPassword();
                CredentialsProvider provider = new BasicCredentialsProvider();
                if (username != null) {
                    String plainPassword = password != null ? transportSupport.protector().decryptString(password) : null;
                    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, plainPassword);
                    provider.setCredentials(AuthScope.ANY, credentials);
                    builder = builder.setDefaultCredentialsProvider(provider);
                }
                String proxyUsername = smsGatewayConfigurationType.getProxyUsername();
                ProtectedStringType proxyPassword = smsGatewayConfigurationType.getProxyPassword();
                if (StringUtils.isNotBlank(proxyHost)) {
                    HttpHost proxy;
                    if (StringUtils.isNotBlank(proxyPort) && isInteger(proxyPort)) {
                        int port = Integer.parseInt(proxyPort);
                        proxy = new HttpHost(proxyHost, port);
                    } else {
                        proxy = new HttpHost(proxyHost);
                    }
                    if (StringUtils.isNotBlank(proxyUsername)) {
                        String plainProxyPassword = proxyPassword != null ? transportSupport.protector().decryptString(proxyPassword) : null;
                        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(proxyUsername, plainProxyPassword);
                        provider.setCredentials(new AuthScope(proxy), credentials);
                    }
                    builder = builder.setDefaultCredentialsProvider(provider);
                    builder = builder.setProxy(proxy);
                }
                HttpClient client = builder.build();
                HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client);
                ClientHttpRequest request = requestFactory.createRequest(new URI(url), HttpUtil.toHttpMethod(method));
                setHeaders(request, headersList);
                if (body != null) {
                    request.getBody().write(body.getBytes(encoding));
                }
                ClientHttpResponse response = request.execute();
                LOGGER.debug("Result: " + response.getStatusCode() + "/" + response.getStatusText());
                if (response.getStatusCode().series() != HttpStatus.Series.SUCCESSFUL) {
                    throw new SystemException("SMS gateway communication failed: " + response.getStatusCode() + ": " + response.getStatusText());
                }
                LOGGER.debug("Message sent successfully to {} via gateway {}.", message.getTo(), smsGatewayConfigurationType.getName());
                resultForGateway.recordSuccess();
                result.recordSuccess();
                return;
            }
        } catch (Throwable t) {
            String msg = "Couldn't send SMS to " + message.getTo() + " via " + smsGatewayConfigurationType.getName() + ", trying another gateway, if there is any";
            LoggingUtils.logException(LOGGER, msg, t);
            resultForGateway.recordFatalError(msg, t);
        }
    }
    LOGGER.warn("No more SMS gateways to try, notification to " + message.getTo() + " will not be sent.");
    result.recordWarning("Notification to " + message.getTo() + " could not be sent.");
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) ArrayList(java.util.ArrayList) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) URI(java.net.URI) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) HttpHost(org.apache.http.HttpHost) HttpClient(org.apache.http.client.HttpClient) AuthScope(org.apache.http.auth.AuthScope) VariablesMap(com.evolveum.midpoint.schema.expression.VariablesMap) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse)

Aggregations

CredentialsProvider (org.apache.http.client.CredentialsProvider)271 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)223 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)201 AuthScope (org.apache.http.auth.AuthScope)138 HttpHost (org.apache.http.HttpHost)104 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)73 HttpGet (org.apache.http.client.methods.HttpGet)62 BasicScheme (org.apache.http.impl.auth.BasicScheme)49 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)48 HttpResponse (org.apache.http.HttpResponse)45 Test (org.junit.Test)44 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)41 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)40 IOException (java.io.IOException)39 URI (java.net.URI)36 Credentials (org.apache.http.auth.Credentials)36 AuthCache (org.apache.http.client.AuthCache)33 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)33 HttpClient (org.apache.http.client.HttpClient)31 RequestConfig (org.apache.http.client.config.RequestConfig)29