Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Client side authentication with jax-rs and cxf

We are going to switch JAX-RS implementation from Jersey to Apache CXF 3.0. I just can't figure out how basic authentication is done the Apache CXF way. All examples I found where around CXF WebClient, not the JAX-RS Client API.

This is what's working with Jersey:

Client client = ClientBuilder.newClient();
client.register(HttpAuthenticationFeature.basic(config.getUsername(),config.getPassword()));

How can this be done with Apache CXF?

like image 253
Klaus Avatar asked Nov 01 '22 19:11

Klaus


1 Answers

Create a ClientRequestFilter to perform the basic authentication:

@Provider
public class Authenticator implements ClientRequestFilter {

    private String user;
    private String password;

    public Authenticator(String user, String password) {
        this.user = user;
        this.password = password;
    }

    @Override
    public void filter(ClientRequestContext requestContext) throws IOException {
        requestContext.getHeaders().add(
            HttpHeaders.AUTHORIZATION, getBasicAuthentication());
    }

    private String getBasicAuthentication() {
        String userAndPassword = this.user + ":" + this.password;
        byte[] userAndPasswordBytes = userAndPassword.getBytes("UTF-8");
        return "Basic " + Base64.getEncoder().encodeToString(userAndPasswordBytes);
    }
}

And register it in your Client:

Client client = ClientBuilder.newClient().register(new Authenticator(user, password));

The solution above uses the Java 8 Base64.Encoder to perform the Base64 encoding.
If, for some reason, you are not using Java 8, you can use BaseEncoding from Google Guava.

like image 100
cassiomolin Avatar answered Nov 13 '22 05:11

cassiomolin