spring security 3.2.0 csrf token not working in freemarker template

假如想象 提交于 2019-12-21 18:34:46

问题


After uprading to Spring Security 3.2.0 and configuring the xml, the _csrf token is not working.

Fundamentals:

  • Spring 4.0.1
  • Spring Security 3.2.0.
  • Freemarker Template Language

Step 1 - the spring security xml configuration:

<!-- 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>

Step 2 - the freemarker template:

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

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

Step 3 - the rendered output:

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

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

Step 4 - the freemarker template error:

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

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

Currently i'm debugging the whole application.

I don't know where exactly the problem is - but it seems that csrf isn't working with freemarker. Is this generally possible to include the csrf token in the freemarker template? Do you have any suggestions or solutions?


回答1:


UPDATE:

xml configuration was not made properly. I've found this solution which helps me lot. https://github.com/spring-projects/spring-mvc-showcase/commit/361adc124c05a8187b84f25e8a57550bb7d9f8e4

Now my files look like these:

security.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>


来源:https://stackoverflow.com/questions/21757222/spring-security-3-2-0-csrf-token-not-working-in-freemarker-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!