Saturday, January 25, 2014

Spring MVC Json Rest Service Authentication Example

Just a quick example of using simple username/password authentication for a Spring RestTemplate Client-> Spring MVC Rest JSON service.

The idea is:
  1. Client fires a http request using Spring's RestTemplate
  2. The request is intercepted on the client side by Spring's ClientHttpRequestInterceptor
  3. The interceptor adds authentication headers to the http request before passing it on to the server
  4. The server side has a javax.servlet.Filter which looks at the request headers
  5. If the filter finds the headers injected by the client's interceptor and the header's values are correct (username/password correct) - the filter passes the request onto the server side logic for regular processing (chain.doFilter)
  6. If the Filter does not find the http headers or they have incorrect values, the filter writes "Unauthorized" to the http response.
I run it in tomcat through eclipse. To fire the requests through the client,  I just run the client(  within the same project by right-clinking on it and 'Run As -> Java Application. Both, service and client are in the same project for convenience.