-1

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?

Sumesh TG
  • 2,557
  • 2
  • 15
  • 29
Andrea Grimandi
  • 631
  • 2
  • 8
  • 32
  • can this help? https://github.com/aditzel/spring-security-csrf-filter/blob/master/src/main/java/com/allanditzel/springframework/security/web/csrf/CsrfTokenResponseHeaderBindingFilter.java – fantaghirocco Aug 31 '18 at 15:41
  • Hi fantaghirocco thanks for the answer! Unfortunately the OncePerRequestFilter has the same behaviour of a Filter. I am seeking something that is triggered after the controller return in order to catch the return value and perform some operations on response headers. – Andrea Grimandi Sep 03 '18 at 06:52
  • 1. the same as in the interceptor. Everything before the call to `doFilter` is invoked before the controller, everything after the `doFilter` is invoked after the controller. Method calls passes through so you can do both. – M. Deinum Sep 03 '18 at 11:19

1 Answers1

0

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

Andrea Grimandi
  • 631
  • 2
  • 8
  • 32