Monday, October 19, 2015

CDI interceptor of HTTP Request and Header params - simple example #javaee7 #cdi #jaxrs

While developing and evolving a REST API, using Java EE , there are some cases where you would like to have 'a look' on the incoming HTTP request, specifically the header params, in a more fine grained  (per case) way, rather than a Servlet Filter or the more specific ContainerRequestFilters

One potential way, which I find in some cases very convenient is the addition of CDI interceptors along my JAXRS Resource implementation, that eventually have access to the incoming HTTP request and perform some 'custom' logic. As a developer I can fully control -  where  (in which paths) to intercept the request, by just adding or removing the custom annotation.With the introduction of Java EE 7, it is easier to mix 'concerns' , so you can easily inject  the HTTP Request to plain CDI interceptors.

Below I am just documenting a very simple example, where I use a custom interceptor, to 'intercept' HTTP requests on a business REST API, in order to do some very specific custom Authentication logic. I am checking if the 'user' initiating the request in my REST API is in some specific custom role, that my system defines. Of course the overall example is just an example, but you get the idea.

In order to introduce such a component you need 2 things :
  • introduce a custom annotation, that will be used for activating the interceptor, when it is defined
  • implement the CDI interceptor.
  • apply the annotation, on the paths/ resources of your rest api

The annotation interface.
Nothing fancy here, just a custom run-time annotation, so we can use in order to 'mark' specific methods of our JAXRS API.


The implementation of the interceptor

Noteworthy points
  • the interceptor is 'marked' with our custom annotation  - simple
  • we @Inject the HttpServletReqest 
  • We apply some custom logic, based on the annotation details (I read any params on the definition)
  • From the request I read the header and based on the annotation params - i do some basic logic

Applying the interceptor / annotation

Eventually, you can just annotate your @Path JAXRS resources and methods in order to 'kick' in your custom logic


You can find all the files in this very simple sample project on github.

3 comments:

  1. First of all, thanks for this post.
    However throw NotAuthorizedException("msg") will be better than NotAllowedException, I think.
    Because of 401 Http Error means Unauthorized, but 405 - Method Not Allowed.

    ReplyDelete
  2. First of all, thanks for this post.
    However throw new NotAuthorizedException("msg"), because of http code 401 means unauthorized would be better than NotAllowedException http code 405 Method Not Allowed.
    Because of http code 401 means unauthorized except

    ReplyDelete