I turned on Spring Security and my POSTs don’t work anymore

^ that’s what I googled, so that’s the title of the blog post that solves it.

When I added spring-boot-starter-security to my dependencies, I expected my whole app to suddenly be behind a login screen. But I expected it to work after logging in. Instead, it failed at the first form submission. And it failed without any indication of why.

To find out why, I had to turn on ALL THE LOGGING and look through it carefully. Finally I found this line:

 o.s.security.web.csrf.CsrfFilter         : Invalid CSRF token found for http://localhost:8080/cat/new
Invalid CSRF token found

This gave me the clue to Google for “Spring security CSRF” and then I found the spell.

Inside all your forms, you need to include the special field that means “no really, I am a form that came from your site just now, not someone else sending a sneaky POST with cookies that the browser helpfully supplies.” If you’re using the default Thymeleaf templates, add this input to each form:

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

The th:if part makes it skip this if you’ve temporarily turned off CSRF entirely, so your template will render either way. The rest adds the supplied random token of authenticity to the form submission.

You might also enjoy seeing the failure in the log when it does happen. I put this in my application.properties: