您的位置:首页 > 编程语言 > ASP

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

2015-01-04 21:55 627 查看
环境: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方法调用时)的值重新更新一次。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息