[Spring] [Thymeleaf] Insert CSRF token

When customizing the form and button, the transition could not be made because the destination and CSRF token were not entered.

Using thymeleaf

<form th:action="@{url}" method="post">

If you write the action attribute using @ {} like, the CSRF token will be automatically entered as hidden.

In other words

<form action="url" method="post">

Then, the CSRF token is not included. So even if I submitted in this state, I couldn't make a transition.

CSRF token does not enter if the method of changing the destination for each button

<form th:action="url" method="post">
<button type="button" onClick="submit();" th:formaction="@{url2}">
</form>

If you use jQuery's submit function like this, it seems to be submitted to the url destination of the action attribute of the form tag.

In other words, if you set `th: formaction =" @ {url2}', you wouldn't be able to get a token.

Countermeasures

<form th:action="url" method="post">
//↓ If you add this, tokens will be entered. In other words, insert the token manually
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
<button type="button" onClick="submit();" th:formaction="@{url2}">
</form>

I tried various things to write a script and try to write it somehow, but it didn't work, so I feel that there is no problem even if I increase the number of buttons if I put it in manually for the time being.

However, th: form action does not work, and the action attribute of form becomes the submit destination.

Change submit () to change submit destination


<button type="button" onClick="setAction("Favorite URL");">

<script type="text/javascript">
function setAction(url){
  $('form').attr('action', url); //Set the url of the argument to the action attribute
  $('form').submit(); //Execute submit (Since the action attribute was changed above, that is the submit destination!)
}
</script>

With this, it seems possible to increase the number of buttons and prepare multiple submit destinations.

I would like to know if there is a better way m (_ _) m

Recommended Posts

[Spring] [Thymeleaf] Insert CSRF token
Spring Security usage memo CSRF
[Java] Thymeleaf Basic (Spring Boot)
Until INSERT and SELECT to Postgres with Spring boot and thymeleaf
Authentication / authorization with Spring Security & Thymeleaf
Thymeleaf usage notes in Spring Boot