8

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?

Charles
  • 50,943
  • 13
  • 104
  • 142
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
  • I'm not clear what you mean by "just sends the login form" -- does this appear on a page within your app? I just dug out some old code that tests a site with browser authentication dialogs inserted by some domain security, not by the application, and I basically did exactly as you did, which it worked fine. – Rodney Gitzel Dec 05 '11 at 22:31
  • This is the way the application is implemented. The basic authentication is only for testing and other machines interfacing with the app. We don't want a user to ever see a ugly basic auth form as generated by the browser. – Jens Schauder Dec 10 '11 at 06:33

1 Answers1

17

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());
  }
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
Mosty Mostacho
  • 42,742
  • 16
  • 96
  • 123