Client-Side HTTP Basic Access Authentication With JAX-RS 2.0 📎
Basic Access Authentication is easy to implement with JAX-RS 2.0 and a
ClientRequestFilter
realization:
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.MultivaluedMap;
import javax.xml.bind.DatatypeConverter;
public class Authenticator implements ClientRequestFilter {
private final String user;
private final String password;
public Authenticator(String user, String password) {
this.user = user;
this.password = password;
}
public void filter(ClientRequestContext requestContext) throws IOException {
MultivaluedMap<String, Object> headers = requestContext.getHeaders();
final String basicAuthentication = getBasicAuthentication();
headers.add("Authorization", basicAuthentication);
}
private String getBasicAuthentication() {
String token = this.user + ":" + this.password;
try {
return "BASIC " + DatatypeConverter.printBase64Binary(token.getBytes("UTF-8"));
} catch (UnsupportedEncodingException ex) {
throw new IllegalStateException("Cannot encode with UTF-8", ex);
}
}
}
A filter instance can be registered during the creation of the client:
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
Client client = ClientBuilder.newClient().register(new Authenticator(user, password));
... = this.client.target(uri);
…and the authentication becomes transparent…
The code above was borrowed from the https://github.com/AdamBien/e2ftp project.
See you at Java EE Workshops at MUC Airport!