Thank you very much Peter. I missed the point that HttpCacheContext was 
extending HttpClientContext.

Unfortunately, httpClient5 Async (CloseableHttpAsyncClient) is not sending 
credentials at first request even with your code (the same as mine except using 
HttpCacheContext in place of HttpClientContext).

I will check with Oleg on the way to produce logs.

Regards,
Christophe

> On 10 Feb 2022, at 10:26, Naber, Peter <peter.na...@alfa.de> wrote:
> 
> Hi,
> 
> ok, than a little bit more code 😊
> 
> 
>       public CloseableHttpClient getHttpClient() throws IOException, 
> NoSuchAlgorithmException {
>               final SocketConfig socketConfig = 
> SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true).build();
>               String tlsString = System.getProperty("https.protocols");
>               if ((tlsString == null) || tlsString.isEmpty()) {
>                       tlsString = "";
>                       final String[] protocols = 
> SSLContext.getDefault().getSupportedSSLParameters().getProtocols();
>                       for (final String protocol : protocols) {
>                               if (protocol.startsWith("TLS")) {
>                                       tlsString = tlsString.length() == 0 ? 
> tlsString + protocol : tlsString + "," + protocol;
>                               }
>                       }
>               }
>               final PoolingHttpClientConnectionManager connManager = 
> PoolingHttpClientConnectionManagerBuilder.create()
>                               
> .setConnectionFactory(this.connFactory).setDnsResolver(new 
> SystemDefaultDnsResolver())
>                               
> .setSSLSocketFactory(SSLConnectionSocketFactoryBuilder.create().setSslContext(this.sslContext)
>                                               
> .setTlsVersions(tlsString.split(",")).build())
>                               
> .setDefaultSocketConfig(socketConfig).setValidateAfterInactivity(TimeValue.ofSeconds(10L)).build();
> 
>               this.defaultRequestConfig = 
> RequestConfig.custom().setCookieSpec(StandardCookieSpec.RELAXED)
>                               
> .setAuthenticationEnabled(true).setExpectContinueEnabled(false).setContentCompressionEnabled(true)
>                               
> .setConnectionRequestTimeout(Timeout.ofMilliseconds(this.getConnectionRequestTimeout()))
>                               
> .setConnectTimeout(Timeout.ofMilliseconds(this.getConnectTimeout()))
>                               
> .setResponseTimeout(Timeout.ofMilliseconds(this.getSocketTimeout()))
>                               
> .setRedirectsEnabled(this.getRedirect()).setCircularRedirectsAllowed(false)
>                               .setTargetPreferredAuthSchemes(
>                                               
> Arrays.asList(StandardAuthScheme.DIGEST, StandardAuthScheme.BASIC, 
> StandardAuthScheme.NTLM))
>                               
> .setProxyPreferredAuthSchemes(Arrays.asList(StandardAuthScheme.BASIC, 
> StandardAuthScheme.NTLM)).build();
> 
>               final RedirectStrategy redirectStrategy = new 
> DefaultRedirectStrategy();
> 
>               final CachingHttpClientBuilder cachingHttpClients = 
> CachingHttpClients.custom();
>               
> cachingHttpClients.setCacheConfig(this.getHttpCacheConfig().getCacheConfig()).setConnectionManager(connManager)
>                               
> .setRedirectStrategy(redirectStrategy).setDefaultCookieStore(this.getCookieStore())
>                               
> .setDefaultRequestConfig(this.defaultRequestConfig);
>               if (this.getHttpCacheConfig().getCacheFileName() != null) {
>                       cachingHttpClients.setCacheDir(new 
> File(this.getHttpCacheConfig().getCacheFileName()));
>               }
> 
>               final HttpClientBuilder httpBuild = cachingHttpClients;
>               httpBuild.addExecInterceptorBefore("test", "compress", new 
> ContentCompressionExec());
>               if (this.getHttpProxy() != null) {
>                       final HttpProxy hproxy = this.getHttpProxy();
>                       this.proxy = new HttpHost(hproxy.getHost(), 
> hproxy.getPort());
>                       httpBuild.setProxy(this.proxy);
>                       httpBuild.setRoutePlanner(new 
> DefaultProxyRoutePlanner(this.proxy) {
>                               @Override
>                               protected HttpHost determineProxy(final 
> HttpHost target, final HttpContext context)
>                                               throws HttpException {
> 
>                                       if (ExecuteHttp.this.httpProxy == null) 
> {
>                                               return null;
>                                       }
>                                       if 
> (ExecuteHttp.this.httpProxy.getProxyNonHosts() != null) {
>                                               for (final String proxy1 : 
> ExecuteHttp.this.httpProxy.getProxyNonHosts()) {
>                                                       try {
>                                                               if 
> (target.getHostName().matches(proxy1)) {
>                                                                       return 
> null;
>                                                               }
>                                                       } catch (final 
> Exception e) {
>                                                               
> e.printStackTrace();
>                                                       }
>                                               }
>                                       }
>                                       return super.determineProxy(target, 
> context);
>                               }
>                       });
>               }
>               final CloseableHttpClient httpClient = httpBuild.build();
> 
>               return httpClient;
>       }
> 
> 
>       private void basicRequest(final String basicCommand, final String 
> urls1) throws Exception {
>               int status = 0;
>               String returnString = "";
>               try (CloseableHttpClient httpClient = this.getHttpClient()) {
>                       for (final String url : 
> this.getURL(this.replace(urls1))) {
>                               final HttpUriRequestBase basicRequest = new 
> HttpUriRequestBase(basicCommand, new URI(url));
>                               final URL aURL = new URL(url);
> 
>                               this.setHeaders(basicRequest);
>                               final HttpCacheContext context = 
> this.getHttpCacheContext(aURL);
>                               this.log.info("[basicRequest]  " + 
> basicRequest.getRequestUri());
>                               final CloseableHttpResponse response = 
> httpClient.execute(basicRequest, context);
> 
>                               try {
>                                       status = response.getCode();
>                                       ...
> 
> Regards,
> 
> Peter
> 
> -----Ursprüngliche Nachricht-----
> Von: Christophe Darville <c...@internetvista.com> 
> Gesendet: Donnerstag, 10. Februar 2022 08:42
> An: HttpClient User Discussion <httpclient-users@hc.apache.org>
> Betreff: Re: Preemptive authentication in Http Client 5 Async
> 
> Hi Peter,
> 
> Thank you for your answer. Once you get an HttpCacheContext instance, how do 
> you link it with the request ? I see no setter on the HttpClient nor on the 
> RequestConfig.
> 
> Regards,
> Christophe
> 
>> On 9 Feb 2022, at 17:15, Naber, Peter <peter.na...@alfa.de> wrote:
>> 
>> Hi,
>> 
>> I use the HttpCacheContext but I think with the httpclient5 the preemtive 
>> authentication is implemented the same way.
>> 
>> 
>>      public HttpCacheContext getHttpCacheContext(final URL aURL) throws 
>> Exception {
>>              final HttpHost targetHost = new HttpHost(aURL.getProtocol(), 
>> aURL.getHost(), aURL.getPort()==-1?aURL.getDefaultPort():aURL.getPort());
>>              final HttpCacheContext context = HttpCacheContext.create();
>>              final AuthCache authCache = new BasicAuthCache();
>>              if (this.getPreAuth() && this.getUser()!= null && 
>> this.getPassword()!=null ) {
>>                      if (this.getAuthScheme() == AuthScheme.BASIC) {
>>                              final BasicScheme basicAuth = new BasicScheme();
>>                              basicAuth.initPreemptive(
>>                                              new 
>> UsernamePasswordCredentials(this.getUser(), 
>> this.getPassword().toCharArray()));
>>                              authCache.put(targetHost, basicAuth);
>>                      } else if (this.getAuthScheme() == AuthScheme.DIGEST) {
>>                              final DigestScheme digestScheme = new 
>> DigestScheme();
>>                              final UsernamePasswordCredentials creds = new 
>> UsernamePasswordCredentials(this.replace(this.getUser()),
>>                                              
>> this.replace(this.getPassword()).toCharArray());
>>                              digestScheme.initPreemptive(creds, 
>> UUID.randomUUID().toString().replaceAll("-", ""), "vectorius");
>>                              authCache.put(targetHost, digestScheme);
>>                      }
>>                      context.setAuthCache(authCache);
>>              }
>>              
>> context.setCredentialsProvider(this.getCredentialsProvider(aURL));
>>              return context;
>>      }
>> 
>> regards,
>> 
>> Peter
>> 
>> -----Ursprüngliche Nachricht-----
>> Von: Christophe Darville <c...@internetvista.com> 
>> Gesendet: Mittwoch, 9. Februar 2022 17:00
>> An: HttpClient User Discussion <httpclient-users@hc.apache.org>
>> Betreff: Preemptive authentication in Http Client 5 Async
>> 
>> Hi,
>> 
>> I am trying to make preemptive authentication in HttpClient 5 Async mode 
>> using the following code, but I does not work, first request is still 
>> without authentication and the authentication is done on the second request 
>> : 
>> 
>>      HttpClientContext httpContext = HttpClientContext.create();
>>      CredentialsProvider credentialsProvider = getCredentialsProvider();
>>      if (preemptive) {
>>              URI uri = URI.create(url);
>>              HttpHost targetHost = new HttpHost(uri.getScheme(), 
>> uri.getHost(), uri.getPort());
>>              AuthCache authCache = new BasicAuthCache();
>>              BasicScheme basicAuth = new BasicScheme();
>>              authCache.put(targetHost, basicAuth);
>>              httpContext.setAuthCache(authCache);
>>      }
>>      httpContext.setCredentialsProvider(credentialsProvider);
>> 
>> This code was working in httpClient 4. Any suggestion on how to make 
>> preemptive authentication work in HttpClient5 Async ?
>> 
>> Thank you,
>> Christophe
>> 
>> 
>> 
>> 
>> ---------------------------------------------------------------------
>> To unsubscribe, e-mail: httpclient-users-unsubscr...@hc.apache.org
>> For additional commands, e-mail: httpclient-users-h...@hc.apache.org
>> 
> 
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: httpclient-users-unsubscr...@hc.apache.org
> For additional commands, e-mail: httpclient-users-h...@hc.apache.org
> 
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: httpclient-users-unsubscr...@hc.apache.org
> For additional commands, e-mail: httpclient-users-h...@hc.apache.org
> 


---------------------------------------------------------------------
To unsubscribe, e-mail: httpclient-users-unsubscr...@hc.apache.org
For additional commands, e-mail: httpclient-users-h...@hc.apache.org

Reply via email to