0

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 =>
          registerForm.bindFromRequest.fold(
            { 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 =>
        Ok(views.html.profile_edit_popup())
    }
  }

In view I just use

@CSRF.formField

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?

sergeda
  • 2,061
  • 3
  • 20
  • 43
  • Maybe your jQuery or whatever isn't picking up `csrfToken` field correctly? – insan-e Aug 19 '16 at 08:04
  • You also need to set the `Csrf-Token` header! See [this example](https://github.com/mohiva/play-silhouette-angular-seed/blob/9008dd9a93ff7fcfcfba8c182903b0a997beb034/ui/app/scripts/app.js#L62). Note that there CSRF token is sent as custom Cookie(see app.conf). – insan-e Aug 19 '16 at 08:10
  • @insan-e you were right. Can you make it answer? – sergeda Aug 19 '16 at 17:26
  • Yup, thanks! Glad I could help. :) – insan-e Aug 19 '16 at 17:54

1 Answers1

3

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.

Community
  • 1
  • 1
insan-e
  • 3,883
  • 3
  • 18
  • 43