How to use Spring Security with a mustache?

I am following the Spring Security link and I have redirected a user login page that works as described in section 3.3 . However, I am not sure how to get the CSRF token in Mustache (all examples use JSP). I tried a few naive things like this ...

{{#_csrf}} <input type="hidden" name="{{parameterName}}" value="{{token}}"/> {{/_csrf}} 

... and this...

 {{#CsrfToken}} <input type="hidden" name="{{parameterName}}" value="{{token}}"/> {{/CsrfToken}} 

... but they do not work (and I really did not expect them). How can I get a CSRF token in Mustache?

I am also wondering: where can I set a breakpoint in my code to see what Spring Security sends as a model to my custom login window?)

+5
source share
1 answer

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); // render page } 

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); } } 
0
source

Source: https://habr.com/ru/post/1204795/


All Articles