简体   繁体   中英

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.

eg

$.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?

您可以在每个ajax调用中使用$.ajaxSetup设置CSRF令牌: https : $.ajaxSetup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM