Well, after several hours of fighting this and trying to decipher the documentation of the often-missing context on the topic , I understood.
So from their docs:
To provide simple protection for requests not from the browser, Play only checks requests with cookies in the header. If you are making requests with AJAX, you can put the CSRF token on the HTML page and then add it to the request using the Csrf-Token header.
And there is no code, no example. Thanks Play. Very clear. Anyway, here's how:
in your view.html.formTemplate you can write in IntelliJ:
@() <form method="post" id="myForm" action="someURL"> @helper.CSRF.formField <input type="text" id="sometext"> <button type="submit"> Submit! </button> </form>
And it will look like this when delivered to a customer:
<form method="post" id="myForm" action="someURL"> <input name="csrfToken" value="5965f0d244b7d32b334eff840...etc" type="hidden"> <input type="text" id="sometext"> <button type="submit"> Submit! </button> </form>
Ok, almost there, now we have to create our AJAX call. I have everything in a separate main.js file, but you can also put this in your view.html.formTemplate if you want.
$(document).on('submit', '#myForm', function (event) { event.preventDefault(); var data = { myTextToPass: $('#sometext').val() } // LOOK AT ME! BETWEEN HERE AND var token = $('input[name="csrfToken"]').attr('value') $.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader('Csrf-Token', token); } }); // HERE var route = jsRoutes.controllers.DashboardController.postNewProject() $.ajax({ url: route.url, type: route.type, data : JSON.stringify(data), contentType : 'application/json', success: function (data) { ... }, error: function (data) { ... } }) });
With this line: var token = $('input[name="csrfToken"]').attr('value') You retrieve the CSRF token automatically generated in the form field and capture its value in the variable that will be used in your Javascript
Another important piece of everything that is in AJAX:
$.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader('Csrf-Token', token); } });
Using $.ajaxSetup , you can set that in the header. Here is what you should do from their documentation:
add it to the request using the Csrf-Token header.
Good luck Let me know if this is clear.
Note : when using lusca, use X-CSRF-Token instead of Csrf-Token .