Search code examples
javaspringspring-mvccsrf-protection

Spring MVC - Add custom CSRF Header to all HTTP responses


In my Spring MVC application, I want to implement a sort of CSRF header on annotated controllers methods.

I already have 100% working client's CSRF header parser implemented on the HandlerInterceptorAdapter.preHandle method and I used to try, in the same handler, the header generation for responses inside the on afterCompletion because that seemed to be the most suitable place for me:

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
        throws Exception {
    if (handler instanceof HandlerMethod) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;

        boolean requestCheck = handlerMethod.getMethodAnnotation(CSRF.class) != null;

        if (requestCheck && handlerMethod.getMethodAnnotation(CSRF.class).response()) {
            response.addHeader(payloadEncryptedHeaderName, SecureUtil.buildCsrfHeader(salt, response));
        }
    }

    super.afterCompletion(request, response, handler, ex);
}

In this thread somebody told me that I could not use that method and using a Filter would have been the best but I noticed that in doFilter...

  1. Cannot set headers to the response (or at least I could not find a way)
  2. The method doFilter is invocated before the controller execution (and not after)

I really want to deeply understand how to deal with these interceptors so could someone explain me with an example the best place where I can manipulate the HttpServletResponse in order to accomplish my goal?


Solution

  • Found a solution on my other thread here it was all abount using ResponseBodyAdvice in order to achieve my goal.