0

I'm trying to perform a REST API get request using org.apache.http.client.HttpClient on 4.3.6 version, but receiving a 401 error. I am using Basic Authentication

Here is my example code

BasicCredentialsProvider credprov = new BasicCredentialsProvider();
credprov.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(API_USERNAME, API_PASSWORD));

HttpClientBuilder builder = HttpClientBuilder.create().setDefaultCredentialsProvider(credprov);
HttpClient client = builder.build();

HttpGet httpget = new HttpGet(API_TEST_URI);

HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();

System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
    System.out.println("Response content length: " + entity.getContentLength());
}
if (entity != null) {
    entity.consumeContent();
}

httpClient.getConnectionManager().shutdown();

This is returning a 401, even though all the details are correct. I was debugging through the HttpClient code, and found the original response is returning a 401 with the WWW-Authenticate header is just set as "Basic" with nothing else. This then ends up with a MalformedChallengeException "Authentication challenge is empty" exception.

I have tried changed the code a bit to directly set the header on the httpget variable with the basic authentication

httpget.addHeader("Authorization", "Basic " + Base64Encoder.encode ("username:password"));

and this has worked (showing that the authentication details are correct.

Can anyone find any problems with this approach and why it doesnt work?

user3206236
  • 315
  • 5
  • 14
  • did you have a look at this answer : http://stackoverflow.com/questions/3283234/http-basic-authentication-in-java-using-httpclient ? – Tom Feb 14 '17 at 14:05
  • yes, and that is why i looked at adding the header directly. but the only bit that concerned from there is where it states that this authentication may not work for cloud services – user3206236 Feb 17 '17 at 08:09

1 Answers1

0

It looks like you have added a credentials provided, but haven't added an AuthCache, which is required to pre-emptively authenticate.

There's an example of preemptive basic authentication listed on the HttpClient examples page: http://hc.apache.org/httpcomponents-client-ga/examples.html

Palmr
  • 358
  • 3
  • 7
  • I tried this at the time and it did not work. Reason was that there was not a request interceptor to add the authentication from the AuthCache. I am currently against adding this as it cannot be done through spring xml injection – user3206236 Feb 17 '17 at 08:10