Basic Authentication with Resteasy client

Consider the solution from Adam Bien:

You can attach an ClientRequestFilter to the RESTEasy Client, which adds the Authorization header to the request:

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);
        }
    }
}

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

One can use org.jboss.resteasy.client.jaxrs.BasicAuthentication which is packaged with resteasy-client 3.x and is meant specifically for basic authentication.

Client client = ClientBuilder.newClient();    
ResteasyWebTarget resteasyWebTarget = (ResteasyWebTarget)client.target("http://mywebservice/rest/api");
resteasyWebTarget.register(new BasicAuthentication("username", "passwd"));

You can add a raw authorization header to your REST client by invoking .header(HttpHeaders.AUTHORIZATION, authHeader) in your client configuration. The credentials must be packed in authorization header in the format of "user:pass", encoded as base64 byte array and then appended to the string "Basic " which identifies basic auth.

This is the whole snippet (inspired by this post on baeldung)

    String auth = userName + ":" + password;
    byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1")));
    String authHeader = "Basic " + new String(encodedAuth);

    authToken = restClient.target(restApiUrl + loginPath)
            .request()
            .accept(MediaType.TEXT_PLAIN)
            .header(HttpHeaders.AUTHORIZATION, authHeader)
            .get(String.class);

This worked for me in a Resteasy client. For information, when testing this with wget I had to use the --auth-no-challenge flag.