CXF RESTful Client - How to do basic http authentication without Spring?

sdoca picture sdoca · Oct 24, 2011 · Viewed 9.1k times · Source

I am familiar with using Jersey to create RESTful webservice servers and clients, but due to class loading issues, I am trying to convert a Jersey client into CXF. I believe I want to use an HTTP-centric client but we don't use Spring. We need to use basic HTTP authentication. The user guide has this example:

WebClient client = WebClient.create("http:books", "username", "password", "classpath:/config/https.xml");

The first parameter isn't a URI string. Is it a format used by Spring? Can this method only be used to create WebClients using Spring?

The other way of doing authentication shown is to add a header string:

String authorizationHeader = "Basic " + org.apache.cxf.common.util.Base64Utility.encode("user:password".getBytes());
webClient.header("Authorization", authorizationHeader);

I am guessing that "user:password" should be substituted with the real values, but would appreciate confirmation.

Answer

sdoca picture sdoca · Oct 27, 2011

This answer came from the CXF users mailing list.

The first example referenced above had a typo in it. It has been updated to:

WebClient client = WebClient.create("http://books", "username", "password", "classpath:/config/https.xml");

The fourth argument can be null if a Spring config file is (and therefore Spring) is not being used.

So, this worked for me:

private WebClient webClient;

public RESTfulClient(String url, String username, String password)
        throws IllegalArgumentException
{
    this.username = username;
    this.password = password;
    this.serviceURL = url;

    if (username == null || password == null || serviceURL == null)
    {
        String msg = "username, password and serviceURL MUST be defined.";
        log.error(msg);
        throw new IllegalArgumentException(msg);
    }

    webClient = WebClient.create(this.serviceURL,
            this.username,
            this.password,
            null); // Spring config file - we don't use this
}