How to use Spring Security with Mustache?

时光毁灭记忆、已成空白 提交于 2019-12-10 14:39:30

问题


I'm following the Spring Security reference, and I've got redirection to a custom login page working as described in section 3.3. However, I'm not sure how to get the CSRF token in Mustache (all the examples use JSP). I've tried a few naïve 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 don't work (and I didn't really expect them to). How can I get the CSRF token in Mustache?

I'm also wondering: Where could I set a breakpoint in my code to see what Spring Security is sending as the model to my custom login view?)


回答1:


I am not sure from which version this is available, but you can just add a parameter for CsrfToken on your controller method to get the token to be passed into the model, like so:

@GetMapping("/dashboard")
public String dashboard(CsrfToken csrfToken, Model model) {
    model.addAttribute("_csrf", csrfToken);
    // render page
}

You don't have to use HttpServletRequest. Now you can use your first template.


If the above is too tedious to do for each controller methods, we can register an interceptor instead.

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 interceptor in WebMvcConfigurer:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Autowired
    CsrfTokenInterceptor csrfTokenInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(csrfTokenInterceptor);
    }
}



回答2:


Add this to yourapplication.properties:

spring.mustache.expose-request-attributes=true

Then you have access to the _csrf request attribute in your template.



来源:https://stackoverflow.com/questions/26397168/how-to-use-spring-security-with-mustache

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