Testing an authenticated REST-api with HtmlUnit seems simple enough. Yet, I can't seem to get it to work.
I have the following code:
@Test
public void testApi() throws IOException {
WebClient webClient = new WebClient();
webClient.addRequestHeader("ACCEPT", "application/json");
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
// Incorrect authentication data
DefaultCredentialsProvider userCredentials = new DefaultCredentialsProvider();
userCredentials.addCredentials("someuser", "wrongpass");
webClient.setCredentialsProvider(userCredentials);
page = webClient.getPage("http://localhost:8081/apiv/");
assertEquals(401, page.getWebResponse().getStatusCode());
userCredentials.clear();
// Correct authentication data
userCredentials.addCredentials("someuser", "correctpass");
webClient.setCredentialsProvider(userCredentials);
page = webClient.getPage("http://localhost:8081/apiv/");
assertEquals(200, page.getWebResponse().getStatusCode());
}
When inspecting with a packet-sniffer, no authentication headers are sent. Neither for the 'Incorrect authentication data', nor for the 'Correct authentication data'.