Question

I'm trying to submit a form using jquery in symfony 1.4, but CSRF attack detected error pops up each time. This is the code i use to submit the form data:

$.ajax({
      type: 'post',
      cache: false,
      url: $('#assign-form form').attr('action'),
      data: (
        'activity[id]=' + $('#activity_id').val() +
        '&activity[_csrf_token]=' + $('#activity__csrf_token').val() +
        '&activity[assigned_to_user_id]=' + $('#activity_assigned_to_user_id').val() +
        '&activity[assigned_to_group_id]=' + $('#activity_assigned_to_group_id').val()
      )
});

Am i missing something?

Thanks, Radu.

Was it helpful?

Solution

One thing to look at is whether the Form object that is validating the input is the exact same class as the the one that generated the token. By default, the class is used in the generation of the CSRF token.

If, for example, you had an instance of a subclass of a form used to generate the form html and then you posted to an action that used the ancestor form class, the validation would most likely fail by default.

It's possible to override the token creation if it turns out this is your issue.

Also, have you verified that the value of the token field actually includes a token? A console.log() may help you discover this.

Um...as I look closer at your code, another thing to look at is that you're building a query string to pass in 'data'. Have you tried passing an actual JSON-style object instead?

OTHER TIPS

Usual cause is that the browser is not accepting cookies - have you checked that the cookies are being returned as expected (e.g. iehttpheaders, wireshark, tamperdata)?

Did you configure the secret in settings.yml?

C.

This little issue has driven me mad in the past.

If it's acceptable to you to disable CSRF protection for this particular form (which it often can be), you can add the following to your Form class in /lib/form/... folder:

public function configure ()

  $this->disableLocalCSRFProtection();

I believe it's possible to disable CSRF for a particular instance of the form as well if you don't always wish to have it disabled, but I haven't tried this / don't have the code at hand.

Does the session cookie really received it with ajax query ? your session cookie as returned by server should be exactly the same with a plain HTTP request (for instance the first request initiating session management) and with XMLHttpRequest, otherwise you'll get trouble with CSRF.

$('#activity__csrf_token').val()

Did you mean to have a double underscore in that element id?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top