ASP.net MVC AntiForgeryToken over AJAX

前端 未结 6 1910
清酒与你
清酒与你 2020-12-10 16:08

I am currently developing an MVC application in ASP.net. I am using AJAX.ActionLink to provide a delete link in a list of records, however this is very insecure. I have put

6条回答
  •  被撕碎了的回忆
    2020-12-10 16:35

    You can use AntiForgeryToken with Ajax.ActionLink but you need to manually insert the AntiForgeryToken into the header of your request like so:

    function GetAntiForgeryToken(){
       var tokenWindow = window;
       var tokenName = "__RequestVerificationToken";
       var tokenField = $(tokenWindow.document).find("input[type='hidden'][name='" +     tokenName +   "']");
       if (tokenField.length == 0) {return null;}
       else {
          return {
             name: tokenName,
             value: tokenField.val()
          };
       }
    };
    

    Then, we can use $.ajaxPrefilter to insert it into the header:

    $.ajaxPrefilter(
       function (options, localOptions, jqXHR) {
          var token = GetAntiForgeryToken();
          jqXHR.setRequestHeader(token.name, token.value);
       }
    );
    

    I wrote a post about it here. Hope this helps!

提交回复
热议问题