繁体   English   中英

在实体框架中,您应该在哪里检查用户是否有权在 DbSet/DbContext 中获取或设置数据?

[英]In Entity Framework where should you check if the user has permission to Get or Set the data in DbSet/DbContext?

我在 MVC 中有一个模型,看起来像这样

public class PdfFile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Data { get; set; } //this is a ByteArray of the PDF file
    public int DataCount { get; set; }
    public DateTime Created { get; set; }
    public DateTime LockedOn { get; set; }
    public string CreatedBy { get; set; }
    public string SecurityInfo { get; set; } // actually a xml to check security level
    public string UserGroup { get; set; }
}

在我的 DbContext 中,我有

public DbSet<PdfFile> PdfSet { get; set; }

在我的身份模型中,我有一个变量UserGroup

public string UserGroup { get; set; }

现在在我的控制器中每次我必须检查用户是否有权访问我必须做的 Pdf 文件

[Authorize]
[NoUserGroupNoAccess] // this is a custom filter to ensure that the user has a UserGroup & is not null or empty
public ActionResult SendSingleItem(int? id)
{
    var model = db.PdfSet.Find(id);
    if (model != null && model.UserGroup == User.UserGroup)
    {
        return View(model);
    }

    return null;
}

现在想象一下这种情况,每次我必须访问模型以进行编辑详细信息、删除等操作时,我都必须检查

if (model.UserGroup == User.UserGroup) // plus I have to check XML in secureinfo for individual for each user when editing or deleting

对于我必须做的清单

var dblist = db.PdfSet.ToList();
dblist = dblist.Where(u => u.UserGroup == User.UserGroup).ToList();

这使得控制器代码非常难看,并且在出错时难以调试 有什么方法可以在编辑、创建、删除、访问记录时直接在我的 DbContext 中进行这些检查?

我什至不确定这是否是对用户进行安全检查的正确方法。

我同意你的看法,它使代码变得丑陋且难以维护,但将数据访问与横切关注点结合起来并考虑使用角色并不是一个好主意。 创建角色并确定该角色有权访问应用程序的哪个部分,然后将用户分配给角色。 创建一个角色并将其命名为PdfAccess并使用该角色的Authorize属性:

[Authorize("PdfAccess")]
[NoUserGroupNoAccess] 
public ActionResult SendSingleItem(int? id)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM