'Grails 3 CSRF protection

Is it possible to configure CSRF protection in grails3 app using spring-security plugin, I can't find anything except useToken attribute for grails form and then call withForm inside controller. But this is actually not a very flexible solution. I like approach with filter like here



Solution 1:[1]

You can implement it with <g:form> tag:

Example:

<g:form useToken="true" uri="/logout">

Documentation: http://grails.github.io/grails-doc/latest/guide/single.html#formtokens

In my case, I'm using Spring code, so, additionally, I should add manually a _csrf hidden field in the form.

<g:form useToken="true" uri="/logout">
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
    <input type="submit">Logout</input>
</g:form>

Result:

<form action="/nacho/logout" method="post" >

    <!-- this two lines are added automatically by Grails -->
    <input type="hidden" name="SYNCHRONIZER_TOKEN" value="883a1037-a2c9-4997-8254-e59da6303494" id="SYNCHRONIZER_TOKEN" />
    <input type="hidden" name="SYNCHRONIZER_URI" value="/nacho/userInfo" id="SYNCHRONIZER_URI" />

    <!-- this line was added by myself, but, using the ${_csrf} variable -->
    <input type="hidden" name="_csrf" value="0928f13c-02aa-4122-8ebe-a1239855a85b"/>

    <input type="submit">Logout</input>
</form>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ignacio Ocampo