问题描述
我们使用spring框架的应用程序需要实现基于请求的CSRF令牌,以满足安全性要求。当前,我们有HttpSessionCsrftokenRepository作为Spring默认提供的基于会话的CSRF令牌。根据我发现的说明,通过像这样配置xml
<security:csrf token-repository-ref="customrequestCsrftokenRepository"/>
<bean id="customrequestCsrftokenRepository" class="com.dev.common_web.security.configuration.CustomCsrftokenRepository"/>
将加载实现CsrftokenRepository接口的自定义令牌存储库以处理令牌请求。
但是,当应用程序启动并以调试模式运行时,我可以看到它是Spring默认的HttpSessionCsrftokenRepository,用于处理令牌的加载和生成。我也尝试过在像
这样的xml配置中使用spring CookieCsrftokenRepository<security:csrf token-repository-ref="cookieCsrftokenRepository"/>
<bean id="cookieCsrftokenRepository" class="org.springframework.security.web.csrf.CookieCsrftokenRepository"/>
当应用程序运行时,再次加载HttpSessionCsrftokenRepository来处理令牌请求。似乎在xml中配置为“ token-repository-ref”的值无关紧要,始终使用HttpSessionCsrftokenRepository。
如何配置spring以使用其他csrf令牌存储库而不是默认的HttpSessionCsrftokenRepository?我们正在使用Spring 5.2。
解决方法
我设法弄清楚了:-)。
在应用程序的security.xml中,我们还定义了自定义的csrf请求匹配器,以禁用某些页面的csrf检查。现在添加自定义的csrf令牌存储库时,必须在
<security:csrf token-repository-ref="customRequestCsrfTokenRepository"/>
<security:csrf request-matcher-ref="customCsrfRequestMatcher"/>
必须是这样
<security:csrf token-repository-ref="customRequestCsrfTokenRepository" request-matcher-ref="customCsrfRequestMatcher" />