spring security 3.2.0 csrf 令牌在 freemarker 模板中不起作用

2024-01-12

升级到 Spring Security 3.2.0 并配置 xml 后,_csrf 令牌不起作用。

基本原理:

  • 春季4.0.1
  • 春季安全3.2.0。
  • Freemarker 模板语言

步骤1 - spring security xml配置:

<!-- enable csrf protection via csrf-element -->
<sec:http>
    <!-- -->
    <sec:csrf token-repository-ref="csrfTokenRepository" />
</sec:http>

<!-- rewrite headerName -->
<bean id="csrfTokenRepository" class="org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository">
    <property name="headerName" value="X-SECURITY" />
</bean>

第 2 步 - freemarker 模板:

<form accept-charset="UTF-8" action="/portal" method="POST" name="formAddItemToCart">
    <!-- ... -->

    <!-- inlcude csrf token -->
    <input type="hidden"
           name="${_csrf.parameterName}"
           value="${_csrf.token}"/>
</form>

第 3 步 - 渲染输出:

<form accept-charset="UTF-8" action="/portal" method="POST" name="formAddItemToCart">
    <!-- ... -->

    <input type="hidden" name="" value=""/>
</form>

第 4 步 - freemarker 模板错误:

FreeMarker template error:
The following has evaluated to null or missing:
==> _csrf  [in template "cart.ftl" at line 28, column 21]

参考:http://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/reference/htmlsingle/#csrf http://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/reference/htmlsingle/#csrf

目前我正在调试整个应用程序。

我不知道问题到底出在哪里 - 但似乎 csrf 不能与 freemarker 一起使用。通常可以将 csrf 令牌包含在 freemarker 模板中吗?您有什么建议或解决方案吗?


UPDATE:

xml配置没有正确进行。 我发现这个解决方案对我有很大帮助。https://github.com/spring-projects/spring-mvc-showcase/commit/361adc124c05a8187b84f25e8a57550bb7d9f8e4 https://github.com/spring-projects/spring-mvc-showcase/commit/361adc124c05a8187b84f25e8a57550bb7d9f8e4

现在我的文件如下所示:

安全性.xml

    <sec:http>
        <!-- ... -->
        <sec:csrf />
</sec:http>

<bean id="requestDataValueProcessor" class="org.springframework.security.web.servlet.support.csrf.CsrfRequestDataValueProcessor"/>

<bean id="csrfFilter" class="org.springframework.security.web.csrf.CsrfFilter">
    <constructor-arg>
        <bean class="org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository">
            <property name="headerName" value="X-SECURITY" />
        </bean>
    </constructor-arg>
</bean>

web.xml

 <filter>
    <filter-name>csrfFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <async-supported>true</async-supported>
</filter>

<filter-mapping>
    <filter-name>csrfFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

spring security 3.2.0 csrf 令牌在 freemarker 模板中不起作用 的相关文章

随机推荐