I'm trying to send a REST-request over HTTPS that includes basic authentication in the HTTP header, the problem seem to be that the authentication does not get inserted into the header.
HttpAuthenticationFeature feature = HttpAuthenticationFeature
.basicBuilder().build();
Client client = ClientBuilder.newBuilder().sslContext(getSSLContext())
.hostnameVerifier(getHostNameVerifier()).build();
client.register(feature);
client.register(new LoggingFilter());
try
{
String entity = client
.target(url)
.request(MediaType.APPLICATION_XML)
.property(
HttpAuthenticationFeature.HTTP_AUTHENTICATION_BASIC_USERNAME,
"username")
.property(
HttpAuthenticationFeature.HTTP_AUTHENTICATION_BASIC_PASSWORD,
"password").get(String.class);
System.out.println(entity);
} catch (WebApplicationException e)
{
ByteArrayInputStream in = (ByteArrayInputStream) e.getResponse()
.getEntity();
int n = in.available();
byte[] bytes = new byte[n];
in.read(bytes, 0, n);
String entity = new String(bytes, StandardCharsets.UTF_8);
System.out.println(entity);
}
What the log says:
Jun 16, 2015 2:06:53 PM org.glassfish.jersey.filter.LoggingFilter log
INFO: 1 * Sending client request on thread JavaFX Application Thread
1 > GET https://url
1 > Accept: application/xml
Jun 16, 2015 2:06:53 PM org.glassfish.jersey.filter.LoggingFilter log
INFO: 2 * Client response received on thread JavaFX Application Thread
2 < 403
2 < Connection: Keep-Alive
2 < Content-Length: 240
2 < Content-Type: text/html; charset=iso-8859-1
2 < Date: Tue, 16 Jun 2015 12:06:53 GMT
2 < Keep-Alive: timeout=15, max=100
And the result code is just 403 Forbidden.
If I remove the line client.register(feature);
the line 2 < WWW-authenticate: basic realm="/"
gets added to the end of the log and the result code is 401 Authorization Requried instead of 403.
The REST-request works fine when using HTTP Requester in FireFox.
I guess I'm just missing something somewhere?
If you are required to use Pre-Jersey 2.X this is quite difficult, as is apparent. If you need to do HTTPS (SSL) Basic Authentication then it gets ridiculously easy with Jersey 2.X onwards.
These instructions are using Jersey 2.25.1:
Sample code for building WebTarget and Client with SSLContext: