Apache CXF - Basic Authentication Example

Basic Authentication (BA) is a method for a HTTP client to provide a user name and password when making a request. There is no confidentiality protection for the transmitted credentials. therefore it is strongly advised to use it in conjunction with HTTPS.

The credentials are provided as an HTTP header field called 'Authorization' which is constructed as follows:

The authorization method and a space ("Basic ") are then put before the encoded string.

Basic Y29kZW5vdGZvdW5kOnA0NTV3MHJk

Instead of writing custom code to create and check the HTTP authorization header we will configure Apache CXF and Spring Boot to do the work for us. The below example illustrates how a client and server can be configured to apply basic access authentication using Apache CXF, Spring Boot, and Maven.

In order for this example to work we need to add one additional dependency to the Maven POM file which is the spring-boot-starter-securitySpring Boot starter dependency that will be used for the server setup.

CXF Basic Authentication Client

The CXF framework ships with an AuthorizationPolicy class that can be set on the HTTPConduit which handles the HTTP(S) transport protocols.

We update the ClientConfig by adding a 'basicAuthorization'Bean on which we set the username and password that are both retrieved from the application.yml properties file shown below. As a basic authentication HTTP header needs to be added we set the type to 'Basic'.

The default user that will be configured has as name 'user'. The password is randomly generated at startup (it is displayed in the startup logs).

Typically you will want to configure a custom value for the user and password, in order to do this you need to set the Spring Boot security properties in the application properties file. In this example we set the 'user' to "codenotfound" and the 'password' to "p455w0rd" in application.yml using the YAML variant as shown below.

security:user:name:codenotfoundpassword:p455w0rd

Testing the Basic Authentication Configuration

In order to test above configuration, we just run the SpringWsApplicationTests unit test case by executing the following Maven command.

mvn test

The test case will run successfully as basic authentication is correctly configured on both sides. The TicketAgentImpl was annotated with the LoggingFeature and the 'org.apache.cxf.services' log level was set to 'INFO' so that the HTTP headers are logged including the authorization header as shown below.