Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing basic auth credentials with every request with HtmlUnit WebClient

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?

like image 374
Jens Schauder Avatar asked Dec 05 '11 16:12

Jens Schauder


1 Answers

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());
  }
like image 187
Mosty Mostacho Avatar answered Nov 11 '22 06:11

Mosty Mostacho