在使用EF检索和提交对SQL的更改之前检查用户ID是否足够安全?

在使用EF检索和提交对SQL的更改之前检查用户ID是否足够安全?,sql,entity-framework,asp.net-identity,Sql,Entity Framework,Asp.net Identity,我试图确保用户不能访问或修改表中属于其他用户的行。在做了一些研究之后,这就是我提出的方法(示例代码) 公共虚拟操作结果编辑(int-id) { var myEntity=myEntityService.GetEntity(id); 如果(myEntity==null) 返回HttpNotFound(); if(myEntity.UserId!=User.Identity.GetUserId()) 返回HttpNotFound(); MyEntityFormModel editMyEntity=M

我试图确保用户不能访问或修改表中属于其他用户的行。在做了一些研究之后,这就是我提出的方法(示例代码)

公共虚拟操作结果编辑(int-id)
{
var myEntity=myEntityService.GetEntity(id);
如果(myEntity==null)
返回HttpNotFound();
if(myEntity.UserId!=User.Identity.GetUserId())
返回HttpNotFound();
MyEntityFormModel editMyEntity=Mapper.Map(myEntity);
返回视图(editMyEntity);
}
}
对于其他CRUD操作,还有一种类似的方法:通过其Id检索实体,然后检查以确保实体的UserId属性(从AspNet.Identity.GetUserId()检索并在创建过程中存储)与用户UserId匹配,然后再允许任何CRUD操作发生


这是否足够安全?这是防止人们访问彼此数据的有效方法,还是我应该执行另一个安全检查?

我还没有与EF合作,了解该框架中可能的具体内容,但这是我在nHibernate中要做的

对于GetEntity,在查询参数中执行get by Id和UserId。 它节省了sql server负载、带宽和网络使用率,因为如果实体对登录用户无效,您将不会返回任何不必要的数据

插入:这不是问题,因为您仍然需要将entity.UserId设置为登录用户的Id

更新:这是您可能需要手动验证entity.UserId是否与登录用户的Id匹配的地方。但是,检查EF是否有“更新entity where Id=X和UserId=Y”的方法—从长远来看,这将使其更安全,更易于维护

Delete:与GetEntity相同-以Id和UserId作为查询参数进行删除。因此,如果记录不是针对当前用户的,则不会删除任何内容

我猜一般的方法几乎就像对待实体一样,它们在Id和UserId上有一个复合键

MyEntityDbContext看起来像这样

interface IMyEntityDbContext {
    Entity GetEntity(int id, int userId);
    int Insert(Entity entity);
    void Delete(int id, int userId);

    void Update(Entity entity);
    //or if possible in EF
    void Update(Entity entity, int userId);
}
它减少了只需在Update语句中写入的验证逻辑的数量。它还使得绝对不可能为不同的用户获取或删除记录

interface IMyEntityDbContext {
    Entity GetEntity(int id, int userId);
    int Insert(Entity entity);
    void Delete(int id, int userId);

    void Update(Entity entity);
    //or if possible in EF
    void Update(Entity entity, int userId);
}