【问题标题】:Spring Security 4 JTwig put CSRF token in formsSpring Security 4 JTwig 将 CSRF 令牌放入表单中
【发布时间】:2017-06-16 11:55:46
【问题描述】:

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

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

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

【问题讨论】:

  • 扩展应该可以正常工作。你能在这里留下一个不起作用的示例模板吗?
  • 从 JTwig 移至 FreeMarker。没有更多的悲伤。

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


【解决方案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>

【讨论】:

    猜你喜欢
    • 2016-05-07
    • 2017-09-07
    • 1970-01-01
    • 2012-03-06
    • 2014-12-06
    • 2019-07-20
    • 2017-04-06
    • 2015-08-25
    • 2013-08-28
    相关资源
    最近更新 更多