3

I have been trying to implement Spring Security for a few days and have been struggling with the csrf tokens.

I've debugged down into CsrfRequestDataValueProcessor and found that the following line is returning null.

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

Using Thymeleaf I have the following form:

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

It doesn't render and throws the following exception:

Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "_csrf.parameterName" (loginsample:19)] with root cause org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): Property or field 'parameterName' cannot be found on null

Why this might be?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Jonas Vachal
  • 53
  • 2
  • 7

1 Answers1

1

Are you using Java or XML config? If XML, make sure you enable the csrf token:

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

You might also need to import the JSP taglib: Import the security tags:

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

then add this in the head as well:

<sec:csrfMetaTags /> 

You might need to import the taglib dependency.

Ajdin
  • 94
  • 4