Passing basic auth credentials with every request with HtmlUnit WebClient

Jens Schauder picture Jens Schauder · Dec 5, 2011 · Viewed 11.3k times · Source

I'm trying to write a simple smoke test for a web application.

The application normally uses form based authentication, but accepts basic auth as well, but since the default is form based authentication, it never sends an authentication required, but instead just sends the login form.

In the test I try to send the basic auth header using

WebClient webClient = new WebClient();

DefaultCredentialsProvider creds = new DefaultCredentialsProvider();

// Set some example credentials
creds.addCredentials("usr", "pwd");

// And now add the provider to the webClient instance
webClient.setCredentialsProvider(creds);

webClient.getPage("<some url>")

I also tried stuffing the credentials in a WebRequest object and passing that to the webClient.getPage method.

But on the server I don't get an authentication header. I suspect the WebClient only sends the authentication header if it get explicitly asked for it by the server, which never happens.

So the question is how can I make the WebClient send the Authentication header on every request, including the first one?

Answer

Mosty Mostacho picture Mosty Mostacho · Dec 10, 2011

This might help:

WebClient.addRequestHeader(String name, String value)

More specific one can create an authentication header like this

 private static void setCredentials(WebClient webClient)
  {
    String username = "user";
    String password = "password";
    String base64encodedUsernameAndPassword = base64Encode(username + ":" + password);
    webClient.addRequestHeader("Authorization", "Basic " + base64encodedUsernameAndPassword);
  }

  private static String base64Encode(String stringToEncode)
  {
    return DatatypeConverter.printBase64Binary(stringToEncode.getBytes());
  }