Lar*_*y S 5 security entity-framework-4.1 asp.net-mvc-3
ASP.NET MVC 3中默认的强类型编辑页面通常公开实体的所有字段.虽然这通常是可行的,但某些领域存在安全风险.例如,简化的杂志订阅实体可能如下所示:
public void Subscription() {
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public DateTime SubscribedThru { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
例如,如果我提供编辑页面以允许用户更改自己的地址,那么包含该SubscribedThru字段会带来安全风险,因为知识渊博的恶意用户可以通过伪造日期为自己提供10年免费订阅(即使我使用@Html.HiddenFor(model => model.SubscribedThru).因此,我不会在编辑页面html(通过razor)中以任何方式包含该字段.
我认为答案可能是防止SubscribedThru在控制器中对Edit方法进行绑定尝试,例如:
[HttpPost]
public ActionResult Edit([Bind(Exclude="SubscribedThru")] Subscription subscription) {
if (ModelState.IsValid) {
db.Entry(subscription).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View(subscription);
}
Run Code Online (Sandbox Code Playgroud)
当我到达该SaveChanges();行时,它会抛出错误The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.我认为SubscribedThru日期(正确吗?)不存在,并且空值小于SQL Server可以处理的值.令我惊讶的是,当我将Binding排除在外时,它甚至会尝试更新该字段.
到目前为止,我最好的解决方案似乎是创建一个省略SubscribedThru日期的自定义ViewModel,但这似乎有很多重复的字段,验证等; 如果可能的话,我想让SubscribedThru用户编辑的一个字段安全无虞.
我不能说我完全理解UpdateModel和TryUpdateModel方法,不知道如果这是头一个方向?我和他们一起玩,EF因为有重复的对象(相同的密钥)而引发错误.
此外,我不清楚订阅数据是否从public ActionResult Edit(int id)控制器中的初始加载一直保留到最终[HttpPost]
public ActionResult Edit(Subscription subscription)...方法,或者该行db.Entry(subscription).State = EntityState.Modified;尝试并设置所有数据(我认为它只是设置一个标志指示"编辑那么EF-应该保存,此").
我是一名长期的.NET开发人员,刚刚进入我的第一个ASP.NET MVC项目,所以我可能会忽略一些非常明显的东西.谢谢你的帮助!
到目前为止,我最好的解决方案似乎是创建一个省略 SubscribedThru 日期的自定义 ViewModel,但这似乎有很多重复的字段、验证等;
这正是您应该做的,以保持一切整洁。 AutoMapper缓解了ViewModel变化带来的麻烦。
| 归档时间: |
|
| 查看次数: |
1018 次 |
| 最近记录: |