Basic Authentication with Resteasy client

Moritz Hübner picture Moritz Hübner · Feb 28, 2014 · Viewed 19.6k times · Source

I'm trying to perform an basic auth to the login-module which runs on my jboss using REST. I already found an StackOverflow topic which explains how to authenticate with credentials.

RESTEasy client framework authentication credentials

This does not work. Analysing the established connection with Wireshark I was not able to see an HTTP package with Authorization: Basic. After more research I found this article, http://docs.jboss.org/resteasy/docs/2.3.3.Final/userguide/html/RESTEasy_Client_Framework.html which describes how to append basic auth to ApacheHttpClient4Executor from resteasy.

// Configure HttpClient to authenticate preemptively
// by prepopulating the authentication data cache.

// 1. Create AuthCache instance
AuthCache authCache = new BasicAuthCache();

// 2. Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put("com.bluemonkeydiamond.sippycups", basicAuth);

// 3. Add AuthCache to the execution context
BasicHttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

// 4. Create client executor and proxy
httpClient = new DefaultHttpClient();
ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient, localContext);
client = ProxyFactory.create(BookStoreService.class, url, executor);

But this does not work either. There is no description how to append username and passwort for basic auth to the construct. Why is that information not associated with any class from httpcomponent?

Answer

Ali Cheaito picture Ali Cheaito · Feb 15, 2016

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