3

几天来,我一直在尝试实施 Spring Security,并且一直在努力解决csrf tokens.

我已经调试CsrfRequestDataValueProcessor并发现以下行返回null。

CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());

使用 Thymeleaf 我有以下形式:

<form th:action="@{/j_spring_security_check}" method="post">
  <label for="j_username">Username</label>:
  <input type="text" id="j_username" name="j_username" /> <br />
  <label for="j_password">Password</label>:
  <input type="password" id="j_password" name="j_password" /> <br />
  <input type="submit" value="Log in" />
  <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
</form>

它不渲染并引发以下异常:

请求处理失败;嵌套异常是 org.thymeleaf.exceptions.TemplateProcessingException:异常评估 SpringEL 表达式:“_csrf.parameterName”(loginsample:19)] 根本原因 org.springframework.expression.spel.SpelEvaluationException:EL1007E:(pos 0):属性或字段在 null 上找不到“参数名称”

为什么会这样?

4

1 回答 1

1

您使用的是 Java 还是 XML 配置?如果是 XML,请确保启用 csrf 令牌:

<http> ... <csrf /> </http>

您可能还需要导入 JSP 标记库: 导入安全标记:

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

然后将其也添加到头部:

<sec:csrfMetaTags /> 

您可能需要导入 taglib 依赖项。

于 2015-06-16T02:29:52.480 回答