Spring Boot + Security + Thymeleaf and CSRF token not injected automatically

三世轮回 提交于 2019-11-30 07:19:52

According to the Thymeleaf developers, RequestDataValueProcessor interface is used by Thymeleaf to find the extra hidden fields which is automatically added to the form post back.

The below code in org/thymeleaf/spring3/processor/attr/SpringActionAttrProcessor.java shows this.

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

To sort the issue, and automatically add the CSRF Token; In your application create a custom request data value processor and register it with spring. To do this, you may go through the tutorial below.

Csrf Defense in Spring-MVC

I also suggest you to check your previous spring MVC code without the spring boot, to confirm that project's configuration XML has a custom made RequestDataValueProcessor or not.

I had a similar issue. After some investigation I've found out that only forms that were using 'th:action' attribute (not plain 'action') had the csrf token injected.
For login forms it seems that you need to inject the csrf manually (link).
In the official spring docs (link) there is a suggestion to retrieve the csrf token just before login form submission to prevent session timeouts. In this scenario there would be no csrf token in hidden input on the form.

You'll have to do 2 things. Declare a bean

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

 ... other beans ...

    @Bean
    public RequestDataValueProcessor requestDataValueProcessor() {
        return new CsrfRequestDataValueProcessor();
    }
}

Make sure the html form in your themeleaf template uses "th:action"

<form th:action="@{/youractionurl}"> 
 ... input tags
</form>

This automatically inserts _csrf token like this

<input type="hidden" name="_csrf" value="4568ad84-b300-48c4-9532-a9dcb58366f3" />

Using Spring Boot + Thymeleaf + Spring Security it worked with this:

Application Properties

security.enable-csrf=true

Update 30/03/2017:

One important thing is: use th:action inside your form, this will tell the Spring Security to inject CSRF inside the form without the need of manual insertion.

For manual insertion:

html template

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

Update 25/01/2017:

pom.xml

    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        <version>2.1.2.RELEASE</version>
    </dependency>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!