Spring MVC-将自定义CSRF标头添加到所有HTTP响应 [英] Spring MVC - Add custom CSRF Header to all HTTP responses
问题描述
在我的Spring MVC应用程序中,我想在带注释的控制器方法上实现一种CSRF标头。
In my Spring MVC application, I want to implement a sort of CSRF header on annotated controllers methods.
我已经在其上实现了100%正常工作的客户端CSRF标头解析器 HandlerInterceptorAdapter.preHandle
方法,我曾经尝试在同一处理程序中在 afterCompletion
,因为这似乎是最适合我的地方:
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);
}
在此线程有人告诉我,我不能使用该方法,而使用Filter最好,但我注意到在 doFilter
...
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
...
- 无法设置标题响应(或者至少我找不到方法)
- 在控制器执行之前调用方法
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)
我真的很想深入了解如何处理这些拦截器,所以有人可以向我解释一下举个例子,最好的地方是我可以操纵 HttpServletResponse
以实现自己的目标吗?
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?
推荐答案
在我的其他线程上找到了解决方案在这里为了实现我的目标,所有使用 ResponseBodyAdvice
都是如此。
Found a solution on my other thread here it was all abount using ResponseBodyAdvice
in order to achieve my goal.
这篇关于Spring MVC-将自定义CSRF标头添加到所有HTTP响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!