Search in sources :

Example 66 with HttpHost

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpHost in project robovm by robovm.

the class RequestAddCookies method process.

public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (context == null) {
        throw new IllegalArgumentException("HTTP context may not be null");
    }
    // Obtain cookie store
    CookieStore cookieStore = (CookieStore) context.getAttribute(ClientContext.COOKIE_STORE);
    if (cookieStore == null) {
        this.log.info("Cookie store not available in HTTP context");
        return;
    }
    // Obtain the registry of cookie specs
    CookieSpecRegistry registry = (CookieSpecRegistry) context.getAttribute(ClientContext.COOKIESPEC_REGISTRY);
    if (registry == null) {
        this.log.info("CookieSpec registry not available in HTTP context");
        return;
    }
    // Obtain the target host (required)
    HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    if (targetHost == null) {
        throw new IllegalStateException("Target host not specified in HTTP context");
    }
    // Obtain the client connection (required)
    ManagedClientConnection conn = (ManagedClientConnection) context.getAttribute(ExecutionContext.HTTP_CONNECTION);
    if (conn == null) {
        throw new IllegalStateException("Client connection not specified in HTTP context");
    }
    String policy = HttpClientParams.getCookiePolicy(request.getParams());
    if (this.log.isDebugEnabled()) {
        this.log.debug("CookieSpec selected: " + policy);
    }
    URI requestURI;
    if (request instanceof HttpUriRequest) {
        requestURI = ((HttpUriRequest) request).getURI();
    } else {
        try {
            requestURI = new URI(request.getRequestLine().getUri());
        } catch (URISyntaxException ex) {
            throw new ProtocolException("Invalid request URI: " + request.getRequestLine().getUri(), ex);
        }
    }
    String hostName = targetHost.getHostName();
    int port = targetHost.getPort();
    if (port < 0) {
        port = conn.getRemotePort();
    }
    CookieOrigin cookieOrigin = new CookieOrigin(hostName, port, requestURI.getPath(), conn.isSecure());
    // Get an instance of the selected cookie policy
    CookieSpec cookieSpec = registry.getCookieSpec(policy, request.getParams());
    // Get all cookies available in the HTTP state
    List<Cookie> cookies = new ArrayList<Cookie>(cookieStore.getCookies());
    // Find cookies matching the given origin
    List<Cookie> matchedCookies = new ArrayList<Cookie>();
    for (Cookie cookie : cookies) {
        if (cookieSpec.match(cookie, cookieOrigin)) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Cookie " + cookie + " match " + cookieOrigin);
            }
            matchedCookies.add(cookie);
        }
    }
    // Generate Cookie request headers
    if (!matchedCookies.isEmpty()) {
        List<Header> headers = cookieSpec.formatCookies(matchedCookies);
        for (Header header : headers) {
            request.addHeader(header);
        }
    }
    int ver = cookieSpec.getVersion();
    if (ver > 0) {
        boolean needVersionHeader = false;
        for (Cookie cookie : matchedCookies) {
            if (ver != cookie.getVersion()) {
                needVersionHeader = true;
            }
        }
        if (needVersionHeader) {
            Header header = cookieSpec.getVersionHeader();
            if (header != null) {
                // Advertise cookie version support
                request.addHeader(header);
            }
        }
    }
    // Stick the CookieSpec and CookieOrigin instances to the HTTP context
    // so they could be obtained by the response interceptor
    context.setAttribute(ClientContext.COOKIE_SPEC, cookieSpec);
    context.setAttribute(ClientContext.COOKIE_ORIGIN, cookieOrigin);
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) Cookie(org.apache.http.cookie.Cookie) ProtocolException(org.apache.http.ProtocolException) ManagedClientConnection(org.apache.http.conn.ManagedClientConnection) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) CookieStore(org.apache.http.client.CookieStore) Header(org.apache.http.Header) HttpHost(org.apache.http.HttpHost) CookieSpec(org.apache.http.cookie.CookieSpec) CookieOrigin(org.apache.http.cookie.CookieOrigin) CookieSpecRegistry(org.apache.http.cookie.CookieSpecRegistry)

Example 67 with HttpHost

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpHost in project robovm by robovm.

the class HttpRoute method hashCode.

/**
     * Generates a hash code for this route.
     *
     * @return  the hash code
     */
@Override
public final int hashCode() {
    int hc = this.targetHost.hashCode();
    if (this.localAddress != null)
        hc ^= localAddress.hashCode();
    if (this.proxyChain != null) {
        hc ^= proxyChain.length;
        for (HttpHost aProxyChain : proxyChain) hc ^= aProxyChain.hashCode();
    }
    if (this.secure)
        hc ^= 0x11111111;
    hc ^= this.tunnelled.hashCode();
    hc ^= this.layered.hashCode();
    return hc;
}
Also used : HttpHost(org.apache.http.HttpHost)

Example 68 with HttpHost

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpHost in project cas by apereo.

the class CasRestAuthenticationConfiguration method restAuthenticationTemplate.

@Bean
@RefreshScope
@SneakyThrows
public RestTemplate restAuthenticationTemplate() {
    final URI casHost = new URI(casProperties.getServer().getName());
    final HttpHost host = new HttpHost(casHost.getHost(), casHost.getPort(), casHost.getScheme());
    final ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactoryBasicAuth(host);
    return new RestTemplate(factory);
}
Also used : ClientHttpRequestFactory(org.springframework.http.client.ClientHttpRequestFactory) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) HttpHost(org.apache.http.HttpHost) RestTemplate(org.springframework.web.client.RestTemplate) URI(java.net.URI) RefreshScope(org.springframework.cloud.context.config.annotation.RefreshScope) SneakyThrows(lombok.SneakyThrows) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) Bean(org.springframework.context.annotation.Bean)

Example 69 with HttpHost

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpHost in project dq-easy-cloud by dq-open-cloud.

the class DqHttpRequestTemplateBO method createCredentialsProvider.

/**
 * 创建凭据提供程序
 *
 * @param configStorage
 *            请求配置
 * @return 凭据提供程序
 */
public CredentialsProvider createCredentialsProvider(DqHttpConfigStorageDTO configStorage) {
    if (DqStringUtils.isNotEmpty(configStorage.getHttpProxyHost())) {
        // http代理地址设置
        httpProxy = new HttpHost(configStorage.getHttpProxyHost(), configStorage.getHttpProxyPort());
    }
    if (DqStringUtils.isEmpty(configStorage.getAuthUsername())) {
        return null;
    }
    // 需要用户认证的代理服务器
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(configStorage.getAuthUsername(), configStorage.getAuthPassword()));
    return credsProvider;
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 70 with HttpHost

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpHost in project nifi by apache.

the class TlsCertificateSigningRequestPerformer method perform.

/**
 * Submits a CSR to the Certificate authority, checks the resulting hmac, and returns the chain if everything succeeds
 *
 * @param keyPair the keypair to generate the csr for
 * @throws IOException if there is a problem during the process
 * @return the resulting certificate chain
 */
public X509Certificate[] perform(KeyPair keyPair) throws IOException {
    try {
        List<X509Certificate> certificates = new ArrayList<>();
        HttpClientBuilder httpClientBuilder = httpClientBuilderSupplier.get();
        SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
        sslContextBuilder.useProtocol("TLSv1.2");
        // We will be validating that we are talking to the correct host once we get the response's hmac of the token and public key of the ca
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        httpClientBuilder.setSSLSocketFactory(new TlsCertificateAuthorityClientSocketFactory(sslContextBuilder.build(), caHostname, certificates));
        String jsonResponseString;
        int responseCode;
        try (CloseableHttpClient client = httpClientBuilder.build()) {
            JcaPKCS10CertificationRequest request = TlsHelper.generateCertificationRequest(dn, domainAlternativeNames, keyPair, signingAlgorithm);
            TlsCertificateAuthorityRequest tlsCertificateAuthorityRequest = new TlsCertificateAuthorityRequest(TlsHelper.calculateHMac(token, request.getPublicKey()), TlsHelper.pemEncodeJcaObject(request));
            HttpPost httpPost = new HttpPost();
            httpPost.setEntity(new ByteArrayEntity(objectMapper.writeValueAsBytes(tlsCertificateAuthorityRequest)));
            if (logger.isInfoEnabled()) {
                logger.info("Requesting certificate with dn " + dn + " from " + caHostname + ":" + port);
            }
            try (CloseableHttpResponse response = client.execute(new HttpHost(caHostname, port, "https"), httpPost)) {
                jsonResponseString = IOUtils.toString(new BoundedInputStream(response.getEntity().getContent(), 1024 * 1024), StandardCharsets.UTF_8);
                responseCode = response.getStatusLine().getStatusCode();
            }
        }
        if (responseCode != Response.SC_OK) {
            throw new IOException(RECEIVED_RESPONSE_CODE + responseCode + " with payload " + jsonResponseString);
        }
        if (certificates.size() != 1) {
            throw new IOException(EXPECTED_ONE_CERTIFICATE);
        }
        TlsCertificateAuthorityResponse tlsCertificateAuthorityResponse = objectMapper.readValue(jsonResponseString, TlsCertificateAuthorityResponse.class);
        if (!tlsCertificateAuthorityResponse.hasHmac()) {
            throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_HMAC);
        }
        X509Certificate caCertificate = certificates.get(0);
        byte[] expectedHmac = TlsHelper.calculateHMac(token, caCertificate.getPublicKey());
        if (!MessageDigest.isEqual(expectedHmac, tlsCertificateAuthorityResponse.getHmac())) {
            throw new IOException(UNEXPECTED_HMAC_RECEIVED_POSSIBLE_MAN_IN_THE_MIDDLE);
        }
        if (!tlsCertificateAuthorityResponse.hasCertificate()) {
            throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_CERTIFICATE);
        }
        X509Certificate x509Certificate = TlsHelper.parseCertificate(new StringReader(tlsCertificateAuthorityResponse.getPemEncodedCertificate()));
        x509Certificate.verify(caCertificate.getPublicKey());
        if (logger.isInfoEnabled()) {
            logger.info("Got certificate with dn " + x509Certificate.getSubjectX500Principal());
        }
        return new X509Certificate[] { x509Certificate, caCertificate };
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new IOException(e);
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) JcaPKCS10CertificationRequest(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest) TlsCertificateAuthorityResponse(org.apache.nifi.toolkit.tls.service.dto.TlsCertificateAuthorityResponse) ArrayList(java.util.ArrayList) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) HttpHost(org.apache.http.HttpHost) BoundedInputStream(org.apache.commons.io.input.BoundedInputStream) TlsCertificateAuthorityRequest(org.apache.nifi.toolkit.tls.service.dto.TlsCertificateAuthorityRequest) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) StringReader(java.io.StringReader) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy)

Aggregations

HttpHost (org.apache.http.HttpHost)598 IOException (java.io.IOException)111 CredentialsProvider (org.apache.http.client.CredentialsProvider)105 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)102 HttpResponse (org.apache.http.HttpResponse)101 AuthScope (org.apache.http.auth.AuthScope)101 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)99 Test (org.junit.Test)86 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)84 URI (java.net.URI)68 HttpGet (org.apache.http.client.methods.HttpGet)66 HttpRequest (org.apache.http.HttpRequest)60 Header (org.apache.http.Header)56 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)56 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)48 HttpEntity (org.apache.http.HttpEntity)47 RequestConfig (org.apache.http.client.config.RequestConfig)45 BasicScheme (org.apache.http.impl.auth.BasicScheme)45 URISyntaxException (java.net.URISyntaxException)44 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)43