Spring MVC - Add custom CSRF Header to all HTTP responses

微笑、不失礼 提交于 2019-12-13 03:48:18

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/52118594/spring-mvc-add-custom-csrf-header-to-all-http-responses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!