user2975535 user2975535 - 2 months ago 21
Scala Question

Play Framework 2.5 CSRF check failed ajax

I don't want to enable CSRF filter for all my requests.
But want to use it in my form.
So I use CSRFAddToken and CSRFCheck like this in controller:

def change(lng: String) = checkToken {
Action { implicit request =>
{ formWithErrors =>
Ok(Json.toJson(JsObject(Map("status" -> JsString("error"), "message" -> JsString(messagesApi.translate("register.all_fields_required", Seq()).get)))))
value =>
[Code was cutted]

def getCurrent(lng: String) = addToken {
Action { implicit request =>

In view I just use


to add CSRF to form
Then I get getCurrent action using Ajax and getting html for form and on save I post it using Ajax to change action. The problem is I'm getting

CSRF token check failed

error on submit. Even so I see CSRF hidden field in the form. What I'm doing wrong?


Maybe your JavaScript library isn't picking up csrfToken field correctly? For example you could have issue when using jQuery's text() instead of val()...

Depending on your config settings, you could be missing Csrf-Token value. Play wants the CSRF token in headers(session) AND (in form OR query string). More info here.