【问题标题】:Expected CSRF token not found. Has your session expired? + Spring security + CSRF未找到预期的 CSRF 令牌。你的会话过期了吗? + 弹簧安全 + CSRF
【发布时间】:2015-12-10 15:10:49
【问题描述】:

我正在尝试通过 Spring Security 实现 CSRF。

但是,在点击登录按钮(来自 home.jsp)后,在浏览器中遇到 以下错误

“未找到预期的 CSRF 令牌。您的会话是否已过期?”

我有以下配置

spring-security-config.xml:

<http auto-config="false">
<csrf/>
</http>

home.jsp:

<form action="j_spring_security_check" id="LoginForm" method="post">       
    <input type="text" title="Username" name="j_username" id="j_username" 
           class="inset-shadow defaultText" placeholder="Username" />
    <input type="password" title="Password" name="j_password" 
           id="j_password" class="inset-shadow defaultText" placeholder="Password" />
    <input type="submit" class="submit" title="LOGIN" 
           onsubmit="javascript:{loginSubmit();}"/>
    <input type="hidden" name="_csrf" value="dc7ce2be-f73b-4086-8f90-8ef00b8f81d5"/>    
</form>

来自 jboss server.log 的错误:

2015-09-14 19:56:10,221 错误 [org.apache.catalina.core.ContainerBase.[jboss.web].[localhost].[/].[jsp]] (http-127.0.0.1-8190-2 ) servlet jsp 的 Servlet.service() 抛出异常:java.lang.IllegalStateException: getAttribute: Session has been invalidated 在 org.apache.catalina.session.StandardSession.getAttribute(StandardSession.java:1024) [:6.1.0.Final] 在 org.apache.catalina.session.StandardSessionFacade.getAttribute(StandardSessionFacade.java:110) [:6.1.0.Final] 在 org.apache.jsp.WEB_002dINF.jsp.home_jsp._jspService(home_jsp.java:99)

注意:不确定 server.log 中的错误是否与 CSRF 相关

非常感谢您对此问题的任何帮助?

【问题讨论】:

  • 我看到有人在没有解释的情况下对这个问题表示反对。我竖起大拇指,直到我得到解释。

标签: spring-security csrf-protection


【解决方案1】:

我有同样的错误。

我的情况是,包含表单的 html 页面有一个链接标签,指向我的 web 应用程序中的 css 文件。 这个指向 css 文件的链接也受到 Spring Security 的保护,因此,我遇到了您的错误。

当我取消保护指向 css 文件的链接时,不会发生错误。

这是一个如何在 Spring Security 中使用 Java Config 取消保护文件的示例

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/css/**");
}

【讨论】:

    【解决方案2】:

    而不是

    <input type="hidden" name="_csrf" value="dc7ce2be-f73b-4086-8f90-8ef00b8f81d5"/>
    

    你试过了吗

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

    根据文档,csrf 和令牌将由 Spring 计算并作为请求参数附加,名称为 ${_csrf.parameterName},值为 ${_csrf.token}

    【讨论】:

    • 我已经这样做了,我完全按照您的建议使用,“_csrf”只不过是对 ${_csrf.parameterName} 的解释,而 dc7ce2be-f73b-4086-8f90-8ef00b8f81d5 是对 ${ 的解释_csrf.token}
    猜你喜欢
    • 2016-03-13
    • 2016-03-21
    • 2015-03-24
    • 2019-12-17
    • 2017-05-02
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    相关资源
    最近更新 更多