Spring MVC - Add custom CSRF Header to all HTTP responses
Asked Answered
D

1

-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?

Dumfound answered 31/8, 2018 at 15:26 Comment(3)
can this help? github.com/aditzel/spring-security-csrf-filter/blob/master/src/…Invade
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.Dumfound
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.Goerke
D
0

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

Dumfound answered 3/9, 2018 at 10:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.