使用 Spring Boot + Thymeleaf + Spring Security 可以解决这个问题:
security.enable-csrf=true
更新 30/03/2017:
其中一件重要的事情是:在表单中使用 th:action,这将告诉 Spring Security 在表单中注入 CSRF,而不需要手动插入。
对于手动插入:
<input type="hidden"
th:name="${_csrf.parameterName}"
th:value="${_csrf.token}" />
更新25/01/2017:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
据
Thymeleaf
开发人员称,Thymeleaf使用RequestDataValueProcessor
接口来查找额外的隐藏字段,这些字段会自动添加到表单回发中。
org/thymeleaf/spring3/processor/attr/SpringActionAttrProcessor.java
中的以下代码显示了这一点。
final Map<String,String> extraHiddenFields =
RequestDataValueProcessorUtils.getExtraHiddenFields(arguments.getConfiguration(), arguments);
对问题进行排序,并自动添加CSRF Token;在您的应用程序中创建一个自定义请求数据值处理器并将其注册到 spring。为此,您可以阅读下面的教程。
我还建议你在没有Spring Boot的情况下检查你之前的Spring MVC代码,以确认项目的配置XML是否有定制的
RequestDataValueProcessor
。
你必须做两件事。声明一个 bean
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
... other beans ...
@Bean
public RequestDataValueProcessor requestDataValueProcessor() {
return new CsrfRequestDataValueProcessor();
}
}
确保 themeleaf 模板中的 html 表单使用“th:action”
<form th:action="@{/youractionurl}">
... input tags
</form>
这会自动插入 _csrf 令牌,如下所示
<input type="hidden" name="_csrf" value="4568ad84-b300-48c4-9532-a9dcb58366f3" />