Spring Security 4 JTwig 将 CSRF 令牌放入表单中

Spring Security 4 JTwig put CSRF token in forms

如何使用 JTwig 将 CSRF 令牌放入表单中?

我尝试了 this extension but it doesn't work (showing error about {% csrf %} has no endblock). Also i tried putting HttpServletRequest object in model and then get token using this 片段,但完全没有效果。

即使没有模板引擎,是否有一些通用的方法来实现 csrf-token?

以下代码对我有用:

我创建了一个名为 ControllerSetup 的 class(或者您可以随意命名)并将其放在与我的应用程序相同的文件夹中 class(使用 public static void main() 方法的那个)。代码如下:

package some.pkg.of.myapp;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;

@ControllerAdvice
public class ControllerSetup {

    @ModelAttribute
    public void initModel(HttpServletRequest request, Model model) {
        model.addAttribute("_csrf", request.getAttribute("_csrf"));
    }

}

现在,我的任何控制器中的任何模型都会自动具有一个名为 _csrf 的属性。我会在我的 JTwig 表单中使用它,如下所示:

<form method="post" action="/some/action/url">
    <!-- My fields and buttons here -->

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