ASP.NET如何防止跨站点请求伪造

环境:ASP.NET、MVC5、EntityFramework
对于任何BS程序来说,安全始终是最为重要的一个话题,而跨站点请求伪造是最容易发起的,只需要下个工具(如fiddler)即可轻易实现。我们可以通过对Controller类采取下列措施防止该类黑客行为的发生:
1、在提交数据处理的页面上,加上@Html.AntiForgeryToken()语句。
2、在接收并处理提交的数据的方法上加上[ValidateAntiForgeryToken ]属性。
3、对于所有对数据库等信息进行操作的方法,全部加上[HttpPost]属性,即使用POST提交数据。
4、在该方法上利用BindAttribute绑定entityclass,将用Include属性限定绑定的属性范围,令该方法不处理指定参数之外的参数。
       [HttpPost]
        [ValidateAntiForgeryToken ]
        public ActionResultEdit([Bind(Include="ID,LastName,FirstMidName,EnrollmentDate")]Student student)
        {
            if(ModelState.IsValid)
            {
                db.Entry(student).State =EntityState.Modified;
                db.SaveChanges();
                returnRedirectToAction("Index");
            }
            returnView(student);
        }
但经测试,上述代码会产生一个问题,即不在绑定的属性清单中的字段值会被直接清为null。
5、不采用绑定entity class,而是通过利用控制器的 TryUpdateModel方法来限定字段范围,再通过 db.Entry将其 State设置为 EntityState.Modified,最后提交数据。具体如下:
       [HttpPost,ActionName("Edit")]
        [ValidateAntiForgeryToken ]
        public ActionResult EditPost(int? id)
        {
            if (id ==null)
            {
                return newHttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            varstudentToUpdate = db.Students.Find(id);
            if(TryUpdateModel(studentToUpdate, "",
                new string[] { "LastName","FirstMidName", "EnrollmentDate" }))
            {
                try
                {
                    db.Entry(studentToUpdate).State =EntityState.Modified;
                    db.SaveChanges();

                    return RedirectToAction("Index");
                }
                catch (DataException )
                {
                    //Log the error (uncomment dex variable name andadd a line here to write a log.
                    ModelState.AddModelError("", "Unable to savechanges. Try again, and if the problem persists, see your systemadministrator.");
                }
            }
            returnView(studentToUpdate);
        }
用此方法,并发处理将会被忽略,也就是即便没有被指定的字段也会使用加载时(Find方法调用时)的值重新更新一次。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值