Working on my latest project the past couple days I was trying to figure out a way to enforce authentication for some requests but not others. I first wrote a Filter but when I started mapping the filter to my specific URLs I realized how tedious this could become. I then remembered that Spring allowed for interceptors in its web framework and after a quick glance through their documentation I found the section I was looking for. Unfortunately this still wasn’t exactly what I needed as Spring applies your interceptors to all requests configured in your handler mapping. Looking at the HandlerInterceptor API I found I had access to the handler that was being processed and I just needed to decorate my handlers that needed authentication and adjust my interceptor to first check the handler. I decided to create an empty Interface named AuthenticatedController which my controllers could implement to indicate they needed to be protected from unauthenticated access. You could also do this using annotations, but here’s my code:
AuthenticatedController.java
123
publicinterfaceAuthenticatedController{// This is empty on purpose.}
importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;importorg.springframework.web.servlet.handler.HandlerInterceptorAdapter;publicclassAuthenticationInterceptorextendsHandlerInterceptorAdapter{publicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler)throwsException{if(!(handlerinstanceofAuthenticatedController)){// Authentication not needed, allow request to continue.returntrue;}booleanisAuthenticated=checkAuthentication(...);if(!isAuthenticated){// User is not authenticated, handle response as needed, and halt processing.response.setStatus(HttpServletResponse.SC_FORBIDDEN);returnfalse;}// User is authenticated, allow request to continue.returntrue;}}