Robin Carlo Catacutan
Robin Carlo Catacutan

Reputation: 13679

Anti forgery token as header field or as Post value on AJAX?

I'm working now on Ring Anti Forgery to prevent the site from CSRF attacks. Now I'm in doubt if I should pass the token as a header field or as a post value on AJAX request as they both seem to work.

On the doc it says:

The middleware also looks for the token in the X-CSRF-Token and X-XSRF-Token header fields, which are commonly used in AJAX requests.

The downside of setting it to a header field on my side is that I have to change every Jquery $.post to a simple $.ajax so I can set the headers.

e.g.

$.ajax({
  url: "url",
  type: "post",
  data: {
    username: username, 
    sender: sender
  },
  headers: {
    "X-CSRF-Token": X_CSRF_Token,   
  }
});

vs.

$.post( "url", { username: username, sender: sender, '__anti-forgery-token': X_CSRF_Token})
  .done(function( data ) {
  // done
});

Is there a need for me to change every jQuery $.post to a $.ajax so I can set the anti forgery token as a header field?

Upvotes: 2

Views: 665

Answers (1)

oliverpool
oliverpool

Reputation: 1671

You can use $.ajaxSetup to set the CSRF token at every ajax call: https://gist.github.com/alanhamlett/6316427

Upvotes: 4

Related Questions