如何使用Mustache使用Spring Security?

Rob*_*sen 5 java spring-mvc spring-security mustache

我正在关注Spring Security参考,并且我已经重定向到自定义登录页面,如3.3节所述.但是,我不确定如何在Mustache中获取CSRF令牌(所有示例都使用JSP).我尝试过这样一些天真的事......

{{#_csrf}}
    <input type="hidden" name="{{parameterName}}" value="{{token}}"/>
{{/_csrf}}
Run Code Online (Sandbox Code Playgroud)

...还有这个...

{{#CsrfToken}}
    <input type="hidden" name="{{parameterName}}" value="{{token}}"/>
{{/CsrfToken}}
Run Code Online (Sandbox Code Playgroud)

......但它们不起作用(我并没有真正期待它们).如何在Mustache中获取CSRF令牌?

我也想知道:我在哪里可以在我的代码中设置断点,以查看Spring Security将模型作为模型发送到我的自定义登录视图?)

bur*_*oey 0

我不确定从哪个版本可以使用此功能,但您只需CsrfToken在控制器方法上添加一个参数即可将令牌传递到模型中,如下所示:

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

你不必使用HttpServletRequest. 现在您可以使用您的第一个模板。


如果对每个控制器方法执行上述操作太繁琐,我们可以注册一个拦截器。

拦截器:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

豆角,扁豆:

@Configuration
public class Config {
    @Bean
    public CsrfTokenInterceptor csrfTokenInterceptor() {
        return new CsrfTokenInterceptor();
    }
}
Run Code Online (Sandbox Code Playgroud)

在WebMvcConfigurer中添加拦截器:

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

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(csrfTokenInterceptor);
    }
}
Run Code Online (Sandbox Code Playgroud)