I'm not sure which version it is available for, but you can simply add a parameter for CsrfToken to your controller method to get the token that will be passed to the model, for example:
@GetMapping("/dashboard") public String dashboard(CsrfToken csrfToken, Model model) { model.addAttribute("_csrf", csrfToken);
You do not need to use HttpServletRequest . Now you can use your first template.
If the above is too tedious for each controller method, we can register an interceptor.
interceptor:
public class CsrfTokenInterceptor implements HandlerInterceptor { @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { CsrfToken csrfToken = (CsrfToken) request.getAttribute("_csrf"); if (modelAndView != null) { modelAndView.addObject("_csrf", csrfToken); } } }
Bean:
@Configuration public class Config { @Bean public CsrfTokenInterceptor csrfTokenInterceptor() { return new CsrfTokenInterceptor(); } }
Add an interceptor to WebMvcConfigurer:
@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Autowired CsrfTokenInterceptor csrfTokenInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(csrfTokenInterceptor); } }
source share