Reputation: 83
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?
Upvotes: 8
Views: 4799
Reputation: 130917
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.
Upvotes: 5
Reputation: 1397
I've opened an improvement in CXF Jira for this: https://issues.apache.org/jira/browse/CXF-6817
Upvotes: 0