Bypassing Spring Interceptors via Decoration

by Horatiu Dan

Context

Whether they are built using the genuine Spring Framework or Spring Boot, such applications are widely developed and deployed these days. By trying to address simple or complex business challenges, products strongly rely on the used framework features in their attempt to offer elegant solutions. Elegant here means correct, clean and easy to understand and maintain.

In case of a web application, some requests are handled in a way, while others may need extra pre or post processing, or even a change in the initial request. Generally, Servlet Filters are configured and put in force, in order to accommodate such scenarios.

Spring MVC applications, on the other hand, define HandlerInterceptors which are quite similar to Servlet Filters. As per the API reference, a HandlerInterceptor “allows custom pre-processing with the option of prohibiting the execution of the handler itself and custom post-processing”. Usually, a chain of such interceptors is defined based on the HandlerMapping itself, HandlerMapping being the contract that objects defining the mapping between requests and the executors of the requests shall obey.

This article documents a simple, yet very useful way of bypassing some of the configured HandlerInterceptors depending on the requests’ mapping. An out-of-the-box Spring Framework HandlerInterceptor decorator is used – MappedInterceptor.

Set-up

  • Java 17
  • Maven 3.6.3
  • Spring Boot v. 2.7.3
  • A small web application that exposes a single HTTP Get operation in two different manners:
    • As a REST call (JSON representation)
    • As a web page (HTML representation)

Developing the POC

The application developed to showcase the solution is straight-forward. In order to accomplish the two previously mentioned scenarios, two controllers are defined.

The former is a @RestController annotated one and addresses the REST call, while the latter is a @Controller annotated one and handles the HTML part.

@RestController @Slf4j @RequiredArgsConstructor class JokesRestController { private final JokesService jokesService; @GetMapping("/api/jokes") ResponseEntity<List<Joke>> getJokes() { log.info("getJokes - Retrieve all jokes representation."); return ResponseEntity.ok(jokesService.getJokes()); } } @Controller @Slf4j @RequiredArgsConstructor class JokesController { private final JokesService jokesService; @GetMapping("/jokes") String getJokes(Model model) { log.info("getJokes - Render all jokes."); model.addAttribute("jokes", jokesService.getJokes()); return "jokes"; } } 

Both of them delegate to the same @Service component that provides the content – a few jokes – to be represented in the two aimed manners. Out of simplicity, the JokesService has the entities declared inside, as the scope of this article is focused around the web tier. In a real application, the service obviously would further delegate to a real source of data (a database repository etc.).

A Joke entity is simply described by an identifier and the joke text and represented by the record below:

public record Joke(String id, String text) { public Joke(String text) { this(UUID.randomUUID().toString(), text); } } 

The detail worth observing and essential for the purpose of this article is the slight difference between the controllers’ handler mappings – /api/jokes and /jokes respectively. Since it was decided that both ‘sections’ of this application (REST and non-REST) run in the same JVM and are deployed together, they were separated at URL level. Basically, all REST related URLs are prefixed by /api. Pros and cons around this decision may arise, but in order to sustain the facts presented in this article, this is quite handy.

If we run it, the outcome is as desired:

  • http://localhost:8080/jokes – responds with the the jokes rendered in HTML
HTTP/1.1 200 Content-Type: text/html;charset=UTF-8 Content-Language: en-US Transfer-Encoding: chunked Date: Fri, 16 Sep 2022 08:14:31 GMT Keep-Alive: timeout=60 Connection: keep-alive <!DOCTYPE HTML> <html lang="en"> <head> <title>Jokes</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> </head> <body> <div> <table> <thead> <tr> <th align="left">Jokes</th> </tr> </thead> <tbody> <tr> <td>If Chuck Norris coughs on you, you owe him 50 bucks.</td> </tr> <tr> <td>Chuck Norris can make a slinky go up the stairs.</td> </tr> <tr> <td>Ice has Chuck Norris running through its veins.</td> </tr> </tbody> </table> </div> </body> </html> 
  • http://localhost:8080/api/jokes – responds with the jokes represented as JSON
HTTP/1.1 200 Content-Type: application/json Transfer-Encoding: chunked Date: Fri, 16 Sep 2022 08:13:40 GMT Keep-Alive: timeout=60 Connection: keep-alive [ { "id": "99798159-673b-470a-9355-09246935a42c", "text": "If Chuck Norris coughs on you, you owe him 50 bucks." }, { "id": "6c073428-02c8-4a6f-a438-b4fc445adcd3", "text": "Chuck Norris can make a slinky go up the stairs." }, { "id": "c9b6fcca-d12b-482f-9197-56991e799a15", "text": "Ice has Chuck Norris running through its veins." } ] 

Adding Interceptors

Let’s consider the following requirement – log all requests fulfilled by the application and moreover the session id, where applicable.

Since these are two different concerns, two different HandlerInterceptors are wired in.

@Component @Slf4j public class AppInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { log.info("preHandle - {} {} recorded", request.getMethod(), request.getRequestURI()); return true; } } 
@Component @Slf4j public class SessionInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { log.info("preHandle - {} {}, session id is {}", request.getMethod(), request.getRequestURI(), request.getSession().getId()); return true; } } 
@EnableWebMvc @Configuration @RequiredArgsConstructor public class WebConfig implements WebMvcConfigurer { private final AppInterceptor appInterceptor; private final SessionInterceptor sessionInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(appInterceptor); registry.addInterceptor(sessionInterceptor); } } 

AppInterceptor logs each request, while SessionInterceptor logs the corresponding session identifier of each request, both in advance of the actual fulfillment – method preHandle() is overwritten.

If we run it again, the output is identical as before and in the console following are logged:

  • http://localhost:8080/jokes
c.h.m.interceptor.AppInterceptor : preHandle - GET /jokes recorded c.h.m.interceptor.SessionInterceptor : preHandle - GET /jokes, session id is 61A873D6D9697A1D1041B17A47B02285 c.h.m.controller.JokesController : getJokes - Render all jokes. 
  • http://localhost:8080/api/jokes
c.h.m.interceptor.AppInterceptor : preHandle - GET /api/jokes recorded c.h.m.interceptor.SessionInterceptor : preHandle - GET /api/jokes, session id is 61A873D6D9697A1D1041B17A47B02285 c.h.m.controller.JokesRestController : getJokes - Retrieve all jokes representation. 

For each of the requests, both HandlerInterceptors were invoked and they logged the desired information, in the order they were configured. Then, the corresponding handler method was invoked and fulfilled the request.

Analysis and Improvements

If we analyze a bit this simple implementation, we recollect that one of the characteristics of REST is its statelessness – the session state is kept entirely on the client. Thus, in case of the REST call of this implementation, the session identifier logged by the latter HandlerInterceptor is irrelevant.

Furthermore, it means that short-circuiting this interceptor for all REST calls would be an improvement. Here, SessionInterceptor calls HttpServletRequest#getSession(), which further delegates and calls HttpServletRequest#getSession(true). This is a well known call which returns the session associated with the request or creates one, if necessary. In case of REST calls, such a call is useless, pretty expensive and may affect the overall functioning of the service, if a client performs a great deal of REST calls.

Spring Framework defines the org.springframework.web.servlet.handler.MappedInterceptor, which according to its documentation “wraps a HandlerInterceptor and uses URL patterns to determine whether it applies to a given request”. This looks exactly what it is needed here, a way to bypass the SessionInterceptor in case of REST calls, in case of URLs prefixed with '/api'.

MappedInterceptor class defines a few constructors which allow including or excluding a HandlerInterceptor from being called based on URL patterns. The configuration becomes as follows:

@EnableWebMvc @Configuration @RequiredArgsConstructor public class WebConfig implements WebMvcConfigurer { private final AppInterceptor appInterceptor; private final SessionInterceptor sessionInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(appInterceptor); registry.addInterceptor(new MappedInterceptor(null, new String[] {"/api/**"}, sessionInterceptor)); } } 

Instead of directly registering the sessionInterceptor as above, it is decorated in a MappedInterceptor instance, which excludes all URLs prefixed by '/api'.

Now in the console the following are logged:

  • http://localhost:8080/jokes
c.h.m.interceptor.AppInterceptor : preHandle - GET /jokes recorded c.h.m.interceptor.SessionInterceptor : preHandle - GET /jokes, session id is 8BD55C96F2396494FF8F72CAC5F4EE67 c.h.m.controller.JokesController : getJokes - Render all jokes. 

Both interceptors are executed, before the handler method in JokesController.

  • http://localhost:8080/api/jokes
c.h.m.interceptor.AppInterceptor : preHandle - GET /api/jokes recorded c.h.m.controller.JokesRestController : getJokes - Retrieve all jokes representation. 

Only the relevant interceptor is invoked, before the handler method in JokesRestController.

Conclusion

This article documented and demonstrated via a simple use case how a HandlerInterceptor invocation may be bypassed when needed, by leveraging the out-of-the box Spring Framework’s MappedInterceptor.

In real applications, such configurations might be helpful and proactively protect product development teams from hard to depict problems, suddenly arose and apparently out of nowhere.

Resources

  • Sample project is available here.
  • Picture was taken at Barsana Monastery, Romania

Despre ZTB.ro

ZTB.ro este un agregator românesc de bloguri care colectează și afișează articole din diverse domenii, oferind vizibilitate bloggerilor și o platformă centralizată pentru cititori. Articolele sunt preluate prin feed-uri RSS/Atom și direcționează traficul către blogurile originale.

Articole recente