Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...