Implementing Basic Authentication with CXF

September 7th 2018 Apache CXF Java

Generating the proxy client classes for a web service is only the first step. While the official documentation includes a basic sample for invoking a method on the web service, I had a hard time finding any guidance on how to pass in the credentials for basic authentication.

The way basic authentication support is implemented in CXF isn't very discoverable either. You need to set the username and password on the request context. However, in order to access it, you first need to cast your client proxy class to the BindingProvider interface:

BookService_Service service = new BookService_Service();
BookService proxy = service.getBookServiceSOAP();
Map<String, Object> requestContext = ((BindingProvider)proxy).getRequestContext();

The keys for username and password are exposed on the BindingProvider interface:

requestContext.put(BindingProvider.USERNAME_PROPERTY, SERVICE_USERNAME);
requestContext.put(BindingProvider.PASSWORD_PROPERTY, SERVICE_PASSWORD);

You'll often also need to change the endpoint URL for a web service because the one in the WSDL file is incorrect or when you want to access a different environment. Although there's a constructor on the service class with a URL parameter, that one will change the WSDL file URL, not the endpoint URL. To change the latter, you'll need to use the request context:

requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, SERVICE_URL);
Creative Commons License