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

时间:2017-01-31 06:21:23

标签: java spring-mvc spring-security csrf jtwig

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

我尝试了this扩展,但它不起作用(显示有关{% csrf %}的错误没有结束块)。此外,我尝试将HttpServletRequest对象放入模型中,然后使用this代码段获取令牌,但它根本没有效果。

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

1 个答案:

答案 0 :(得分:1)

以下代码对我有用:

我创建了一个名为 ControllerSetup 的类(或者您可以随意命名),并将其放置在与Application类相同的文件夹中(使用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>