Asp.Net MVC和webapi CSRF防攻击ajax使用方法

一、MVC提交

视图

@using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        <p>
            <strong><em>*</em>姓名:</strong><input type="text" id="name" name="name" />
        </p>
        <p>
            <strong><em>*</em>年龄:</strong><input type="text" id="age" name="age" />
        </p>
        <p>
            <input type="submit" value="提交" />
        </p>
    }

 

控制器

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult PostAdd(FormCollection FromValue)
        {
        //
        }        

 

二、ajax+mvc提交

js

$("form").submit(function () {
                //var token = $("input[name='__RequestVerificationToken']").val();
                var token = $('@Html.AntiForgeryToken()').val();
                var postData = { id: 123, name: "张三", __RequestVerificationToken: token };
                $.ajax({
                    url: '/api/Test/PostData/666',
                    type: "post",
                    data: postData,
                    success: function (res) {
                        console.log(res)
                    },
                    error: function () {
                        console.log("错误")
                    }
                })
                return false;
            })

 

控制台

[ValidateAntiForgeryToken]
        public string PostData(string id,string name)
        {
            string res = "id==" + id + ",name==" + name;
            return res;
        }

 

三、ajax+webapi

js

$("form").submit(function () {
                var postData = { id: 123, name: "李四"};
                $.ajax({
                    url: '/api/Test/PostData/666',
                    headers: {'RequestVerificationToken': '@ApiValidateAntiForgeryToken.GenerateAntiForgeryTokenForHeader()'},
                    type: "post",
                    contentType: 'application/json',
                    data: JSON.stringify(postData),
                    success: function (res) {
                        console.log(res)
                    },
                    error: function () {
                        console.log("错误")
                    }
                })
                return false;
            })

 

webapi

[HttpPost]
        [ApiValidateAntiForgeryToken]
        public string PostData(dynamic obj)
        {
            string res = "id===" + obj.id + ",name===" + obj.name+",ref="+Request.Headers.Referrer.Host;
            return res;
        }
//ApiValidateAntiForgeryToken是自定义过滤器
posted @ 2021-10-09 09:48  WebApi  阅读(269)  评论(0编辑  收藏  举报
CopyRight © 博客园 WebAPI