MVC防止xss攻击 ——Html.AntiForgeryToken的AJAX提交

1、在Html表单里面使用了@Html.AntiForgeryToken()就可以阻止CSRF攻击。

2、相应的我们要在Controller中也要加入[ValidateAntiForgeryToken]过滤特性。该特性表示检测服务器请求是否被篡改。注意:该特性只能用于post请求,get请求无效。

3、至于JS,我们的项目中引用的是<script src="@Url.Content("~/Content/js/jqueryToken-1.4.2.js")" type="text/JavaScript"></script>

在JS时要使用: $.ajaxAntiForgery才行,
如:
 $.ajaxAntiForgery({
            type: "post",
            data: { GroupName: $("#GroupName").val(), GroupPhones: $("#GroupPhones").val() },
            dataType: "json",
            url: "/Event/Mass/AddGroup",
            success: function (data) {
                if (data) {

                    alert("添加成功 ");
                    $.unblockUI();
                }
                else {
                    alert("添加失败 ");
                }
         }
 })

注:对数据进行增删改时要防止csrf攻击!

另外一种方式

 

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(string someValue)
    {
        return Json(new { someValue = someValue });
    }
}

 

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
    @Html.AntiForgeryToken()
}

<div id="myDiv" data-url="@Url.Action("Index", "Home")">
    Click me to send an AJAX request to a controller action
    decorated with the [ValidateAntiForgeryToken] attribute
</div>

<script type="text/javascript">
    $('#myDiv').submit(function () {
        var form = $('#__AjaxAntiForgeryForm');
        var token = $('input[name="__RequestVerificationToken"]', form).val();
        $.ajax({
            url: $(this).data('url'),
            type: 'POST',
            data: { 
                __RequestVerificationToken: token, 
                someValue: 'some value' 
            },
            success: function (result) {
                alert(result.someValue);
            }
        });
        return false;
    });
</script>

 

转载于:https://www.cnblogs.com/l1pe1/p/6030841.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值