jQuery Ajax calls and the Html.AntiForgeryToken()

前端 未结 20 2634
鱼传尺愫
鱼传尺愫 2020-11-22 16:34

I have implemented in my app the mitigation to CSRF attacks following the informations that I have read on some blog post around the internet. In particular these post have

20条回答
  •  我在风中等你
    2020-11-22 17:16

    I'm using a ajax post to run a delete method (happens to be from a visjs timeline but that's not relelvant). This is what I sis:

    This is my Index.cshtml

    @Scripts.Render("~/bundles/schedule")
    @Styles.Render("~/bundles/visjs")
    @Html.AntiForgeryToken()
    
    
    

    All I added here was @Html.AntiForgeryToken() to make the token appear in the page

    Then in my ajax post I used:

    $.ajax(
        {
            type: 'POST',
            url: '/ScheduleWorks/Delete/' + item.id,
            data: {
                '__RequestVerificationToken': 
                $("input[name='__RequestVerificationToken']").val()
                  }
         }
    );
    

    Which adds the token value, scraped off the page, to the fields posted

    Before this I tried putting the value in the headers but I got the same error

    Feel free to post improvements. This certainly seems to be a simple approach that I can understand

提交回复
热议问题