RESTEasy basic authentication example

In this tutorial we will demonstrate how to use a BASIC kind of authentication in your REST Services using RESTEasy on the backend and the DefaultHttpClient on the client side.

First of all we will define one user on the application server that belongs to a Role. If you want to rely on the "other" Security domain (default) it's enough to execute the add-user.sh /add-user.cmd script which is available in the JBOSS_HOME/bin folder.

What type of user do you wish to add?

 a) Management User (mgmt-users.properties)

 b) Application User (application-users.properties)

(a): b

 

Enter the details of the new user to add.

Using realm 'ApplicationRealm' as discovered from the existing property files.

Username : jboss

Password :

Re-enter Password :

What groups do you want this user to belong to? (Please enter a comma separated list, or leave blank for none)[  ]: Manager

About to add user 'jboss' for realm 'ApplicationRealm'

Is this correct yes/no? yes

In this example, we have created the "jboss" user that belongs to the "Manager" group.

Done with the user, we will add to our REST Web service application the Security Constraints so that all of our services will be available only to the Manager user:

<security-constraint>
	<web-resource-collection>
		<web-resource-name>HtmlAuth</web-resource-name>
		<description>application security constraints</description>
		<url-pattern>/*</url-pattern>
		<http-method>GET</http-method>
		<http-method>POST</http-method>
	</web-resource-collection>
	<auth-constraint>
		<role-name>Manager</role-name>
	</auth-constraint>
</security-constraint>
<login-config>
	<auth-method>BASIC</auth-method>
	<realm-name>UserRoles simple realm</realm-name>
</login-config>
<security-role>
	<role-name>Manager</role-name>
</security-role>

 Finally, we will specify that the web application uses the "other" Security Domain in the jboss-web.xml file:

<jboss-web>
    <security-domain>java:/jaas/other</security-domain>
</jboss-web>

 Note: This step can be skipped as the "other " Security Domain is tested if you don't provide any. However it would be needed if you are using another kind of Security Domain

That's all. Now your REST Service will request a BASIC browser authentication when invoked.

Configuring the Client side

The simplest way to write a Client aware of Basic Authentication is by means of the org.apache.http.impl.client.DefaultHttpClient which includes a CredentialsProvider interface for setting Base64 username and password.

Here is the code:

String BASE_URL = "http://localhost:8080/myapp/rest/search/125";

DefaultHttpClient client = new DefaultHttpClient();

client.getCredentialsProvider().setCredentials(
		new AuthScope("localhost", 8080),
		new UsernamePasswordCredentials("jboss", "Password1!"));

HttpGet httppost = new HttpGet(BASE_URL);

System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = null;
try {
	response = client.execute(httppost);
	BufferedReader br = new BufferedReader(new InputStreamReader(
			(response.getEntity().getContent())));

	String output;
	System.out.println("Output from Server .... \n");
	while ((output = br.readLine()) != null) {
		System.out.println(output);
	}

	client.getConnectionManager().shutdown();
} catch (ClientProtocolException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
} catch (IOException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}

Basically this code is executing an HTTP GET toward a REST Service and consuming the output as a BufferedReader Stream. As the REST Service is producing a JSON list of objects:

@GET
@Path("/search/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response updateBusta(@PathParam("id")) {
	
	// Produce JSON 
	return Response.status(200).build();

}

 Then the output of the Client application will be the JSON String returned from the Server:

[{"_id":{"date":1423039138000,"time":1423039138000,"timestamp":1423039138,"machine":296272174,"new":false,"inc":-919141096,"timeSecond":1423039138},"nome":"101","datacreazione":1423039138558,"anno":2015,"pec":"This email address is being protected from spambots. You need JavaScript enabled to view it.","oggetto":"012001","firma":false,"deposito":false,"files":["Amazon.pdf","Cartel1.pdf"],"fileTypes":["AP","SM"]}

 

Follow us on Twitter