无法阻止使用客户ID过度发布

时间:2015-04-09 06:50:16

标签: c# asp.net-mvc

我有简单的MVC应用程序。

在编辑操作

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(string CustomerId, [Bind(Include = "CustomerId,CompanyId,CompanyName,ContactName,ContactTitle,Address,City,Region,PostalCode,Country,Phone,Fax")] Customer customer)
{
    var user = db.Users.Find(CustomerId);
    if (user != null)
        TryUpdateModel(user);
    else
        return HttpNotFound();
    if (ModelState.IsValid)
    {
        db.SaveChanges();
        return RedirectToAction("Index");
    }
}
  

但是,当我执行F12并更改CustomerId的隐藏字段值时,它会更改为CustomerId,而不应该这样做吗?

我想阻止CustomerId过度发布。

1.如果使用F12更改CustomerId,则抛出错误。 2.如果CustomerId正确无法篡改,则只需更新所有值

我得到例外:

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code

Additional information: Attaching an entity of type 'MVCDemo.Models.Customer' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

2 个答案:

答案 0 :(得分:1)

我认为有很多方法可以做到这一点,我脑海中最简单的就是这样。

  1. 生成randomKey(可以是Guid或其他内容)将customerId存储在Session[randomKey] = customerId中,这是在呈现包含表单的视图之前发生的。

  2. 在隐藏的字段存储randomKey中,当您在服务器端发帖时,从customerId Session customerId = Session[randomKey]获取customerId

  3. 这种方式customerId 永远不会在客户端,并且无法更改为在服务器上发布。

    注意:

    1. 用户可以使用F12更改randomKey,请记住用户拥有HTML ,他可以进行任何他想要的更改。

    2. 也许您可以通过javascript捕获此更改,但如果他禁用javascript并更改值会发生什么?

    3. 由于Session存储在{{1}}中,因此密钥的时间有限,用户无法复制该密钥以供后一种使用。

答案 1 :(得分:1)

一种防止隐藏字段被篡改以包含另一个包含CustomerId值哈希值的隐藏字段的技术。然后在POST方法中,您可以比较值并知道它是否被篡改。

This article讨论了包含自定义html助手的技术,以生成隐藏的输入。