Spring Boot + Security + Thymeleaf 和 CSRF 令牌不会自动注入

问题描述 投票:0回答:4
spring-security spring-boot csrf thymeleaf
4个回答
25
投票

我也有类似的问题。经过一番调查后,我发现只有使用“th:action”属性(而不是普通的“action”)的表单才会注入 csrf 令牌。
对于登录表单,似乎您需要手动注入 csrf(link)。
在 Spring 官方文档(link)中,建议在提交登录表单之前检索 csrf 令牌,以防止会话超时。在这种情况下,表单上的隐藏输入中不会有 csrf 令牌。


7
投票

使用 Spring Boot + Thymeleaf + Spring Security 可以解决这个问题:

应用程序属性

security.enable-csrf=true

更新 30/03/2017:

其中一件重要的事情是:在表单中使用 th:action,这将告诉 Spring Security 在表单中注入 CSRF,而不需要手动插入。

对于手动插入:

html 模板

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

更新25/01/2017

pom.xml

    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        <version>2.1.2.RELEASE</version>
    </dependency>

4
投票

Thymeleaf
开发人员称,Thymeleaf使用
RequestDataValueProcessor
接口来查找额外的隐藏字段,这些字段会自动添加到表单回发中。

org/thymeleaf/spring3/processor/attr/SpringActionAttrProcessor.java
中的以下代码显示了这一点。

 final Map<String,String> extraHiddenFields =
                    RequestDataValueProcessorUtils.getExtraHiddenFields(arguments.getConfiguration(), arguments);

对问题进行排序,并自动添加CSRF Token;在您的应用程序中创建一个自定义请求数据值处理器并将其注册到 spring。为此,您可以阅读下面的教程。

Spring-MVC 中的 Csrf 防御

我还建议你在没有Spring Boot的情况下检查你之前的Spring MVC代码,以确认项目的配置XML是否有定制的

RequestDataValueProcessor


4
投票

你必须做两件事。声明一个 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" />
© www.soinside.com 2019 - 2024. All rights reserved.