Monthly Archives: October 2013

REST with Java in practice

RESTful web services are generally hyped these days – and for many good reasons: among others, the fact that they are easily consumed by almost any kind of client – browsers, mobile apps, desktop apps etc.

One technology stack for building restful services in a Java environment could comprise Jersey, Gson and Guice (nice alliteration, by the way…). Without prior knowledge to any of these technologies, me and my team managed to successfully establish a RESTful web service consumed by for example this website.

I will briefly introduce these 3 frameworks:

Jersey and JAX-RS

Jersey­ is one of several implementations of the JAX-RS interface – the Java API for RESTful web services.

Jersey provides a servlet that analyses an incoming HTTP request by scanning underlying classes for RESTful resources, and selecting the correct class and method to respond to this request. The RESTful resources are defined by decorating classes and methods with the appropriate JAX-RS annotations.

If you for example have a UserService class that you want to expose through a RESTful API, you can wrap it in a UserWebService class and decorate this class and its methods with JAX-RS annotations:

The @Path annotation specifies on which (relative) URL path this method will be invoked. The @Get annotation specifies that the http method GET has to be used and the @Produces annotation declares the format of the response.

So, the following http-request:

GET http://localhost:8080/myservice/api/user/list

will invoke the GetUserList() method, which basically is a pass-through to the UserService.getAll() method, and return a response with a list of users in JSON format.

JSON support using Gson

One of the decisions you have to make when establishing a RESTful service is which representation formats (media types) to support. Very often JSON will be the obvious choice – especially if the services are to be consumed by browser-based clients which typically use JavaScript.

In order to produce and consume JSON you need a serialization mechanism that turns a Java object into a JSON document and vice versa (under-the-hood the representation bodies will very often be POJO objects). Our choice was to use Google Gson for this purpose.

You simply need to implement the two interfaces and, and decorate the implementing classes with the JAX-RS @Provider annotation. Here is the writer:

And here is the reader:

Guice as DI container

In a previous post I showed how to use Guice as a DI container in a Jersey application. So, what is left now is to bind the Gson writer and reader – ass well as other types, such as the RESTful resource classes – in the Guice injector:

To summarize, a well-proven technology stack for implementing a RESTful web service in Java comprises Jersey­ as the REST framework, Google Guice as the DI container to support dependency Injection and Google Gson for JSON serialization and de-serialization of the representation body objects. The service can be deployed on for example a Glassfish server.

Implementing Role-Based Authorization using Guice

Besides magically composing the entire object graph for your application, one of the main advantages of introducing a DI container is its ability to perform runtime interception. Because you are delegating the responsibility of composing objects to a 3rd party component (the DI container) you also give this container the possibility to intercept a call from the consumer to a service and execute some additional code before passing the call on to the service itself.

This is a perfect way to implement cross-cutting concerns (aspects) such as logging, validation, authorization etc. so that the underlying services don’t have to care about this and can easily follow the Single Responsibility Principle.

In this post, I will show you an example of how to implement role-based authorization using aspect oriented programming (AOP) in Guice.

The example is a RESTful web service built using Jersey­. The web service is ­using the basic authentication scheme which forces the client to authenticate itself with a user ID and a password for each request. The client must compute a Base64 encoding of <user>:<Password> and include the value in an Authorization header in the request.

The web service operates with 4 different roles: Guest, User, Editor and Admin.

The roles are meant to be hierarchical in the sense that e.g. an editor inherits all the privileges of a guest and a user. This is done by defining a RoleSet enum with an abstract method called getRoles(), which each enum has to override.

So each user does not have a role, but a role set. Through the hasRole() method it can be queried whether a user has the privileges of a particular role:

Now, to setup the role-based authorization, you need to do the following:

  1. Create a new annotation
  2. Implement the method interceptor
  3. Decorate the methods that must be protected with the new annotation
  4. Register the interceptor

Creating the annotation

First, you need to define an annotation that can be used to decorate the methods that you want protected by role-based authorization:

Implementing the interceptor

The interceptor itself is made by implementing the org.aopalliance.intercept.MethodInterceptor interface:

Through the methodInvocation variable, the interceptor has the opportunity to inspect the call: the method, its arguments, and the receiving instance. In this case, you will inspect the httpHeaders argument to get and parse the Authorization header of the http request. The Authorization header includes a Base64 encoding of <user>:<Password>, so you can decode this string and extract the username and password of the caller. The required role is extracted from the @Authorize annotation. If the calling user does not have the required role, or if the provided password is wrong, an appropriate exception is raised. Otherwise, the intercepted method is allowed to proceed.

Decorating the methods

The usage of the @Authorize annotation is straight-forward, simply decorate the method and declare the required role in the annotation parameter.

Register the interceptor

Finally, the interceptor needs to be registered. You need to create matchers for the classes and methods to be intercepted. In this case you must match any class – but only the methods decorated with the @Authorize annotation. Because you need to inject dependencies into the interceptor, use requestInjection() alongside the standard bindInterceptor() call.

As for all other calls to Guice methods, this code must reside in the bootstrapper component of the application where the whole object graphs is wired up.

Now, if a method decorated with the @Authorize annotation is called, the autorizationInterceptor will be executed before the method itself. This is Guice and AOP in action.