在 Thymeleaf 中禁用 CSRF 隐藏输入

Posted

技术标签:

【中文标题】在 Thymeleaf 中禁用 CSRF 隐藏输入【英文标题】:Disable CSRF hidden input in Thymeleaf 【发布时间】:2017-05-30 03:34:41 【问题描述】:

我有一个简单的搜索输入:

<form>
  <input name="search" />
</form>

只要我添加了th:action,Thymeleaf 就会添加一个隐藏的 CSRF 输入字段,尽管我在这里不需要它。

有没有办法为这个给定的表单禁用这种行为?

【问题讨论】:

【参考方案1】:

你可以添加

<csrf disabled="true"/> 

到你的 spring-security.xml 文件,因为 csrf 保护是默认启用的。

所以你的配置文件可能是这样的:

<http auto-config="true" use-expressions="false">
    <form-login
            login-page="/login"
            default-target-url="/index"
            login-processing-url="/login"
            password-parameter="password"
            username-parameter="username"
            authentication-failure-handler-ref="authenticationFailureHandler"
    <intercept-url pattern="/login" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
    <intercept-url pattern="/logout" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
    <csrf disabled="true"/>
</http>

【讨论】:

但据我了解,这会改变整个应用程序的行为。有没有办法只改变表格? 您应该实现 RequestDataValueProcessor(Spring Security 使用 CsrfRequestDataValueProcessor 作为默认实现)和 processAction 方法。在该方法中,您可以决定要自动添加 csrf 令牌的操作,执行此操作后您应该还扩展了 OncePerRequestFilter,因为 CsrfFilter 会拦截您的请求。

以上是关于在 Thymeleaf 中禁用 CSRF 隐藏输入的主要内容,如果未能解决你的问题,请参考以下文章