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
...
- Cannot set headers to the response (or at least I could not find a way)
- 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?
doFilter
is invoked before the controller, everything after thedoFilter
is invoked after the controller. Method calls passes through so you can do both. – Goerke