CSRF Protection in AJAX Requests using MVC2

前端 未结 1 1596
有刺的猬
有刺的猬 2021-02-03 13:42

The page I\'m building depends heavily on AJAX. Basically, there is just one \"page\" and every data transfer is handled via AJAX. Since overoptimistic caching on the browser si

相关标签:
1条回答
  • 2021-02-03 14:18

    You could use the conventional Html.AntiForgeryToken() helper to generate a hidden field somewhere on the page (not necessarily inside a form) and include it along the ajax request:

    var token = $('input[name=__RequestVerificationToken]').val();
    $.post(
        '/SomeAction', { '__RequestVerificationToken': token }, 
        function() {
            alert('Account Deleted.');
        }
    );
    

    To verify it on the server side:

    [AcceptVerbs(HttpVerbs.Post)]
    [ValidateAntiForgeryToken]
    public ActionResult SomeAction() 
    {
        return View();
    }
    

    If you have multiple tokens on your page you might need to specify which one to include. As the existing helper generates the hidden fields with the same names it is difficult to make a good selector so you could place them inside spans:

    <span id="t1"><%= Html.AntiForgeryToken() %></span>
    <span id="t2"><%= Html.AntiForgeryToken() %></span>
    

    and then select the corresponding token:

    var token = $('#t1 input[name=__RequestVerificationToken]').val();
    
    0 讨论(0)
提交回复
热议问题