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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With