[英]In Entity Framework where should you check if the user has permission to Get or Set the data in DbSet/DbContext?
I have a model in MVC which looks like this我在 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; }
}
and In my DbContext I have在我的 DbContext 中,我有
public DbSet<PdfFile> PdfSet { get; set; }
and in my Identity model I have a variable UserGroup
在我的身份模型中,我有一个变量UserGroup
public string UserGroup { get; set; }
Now in my controller everytime I have to check if a user has permission to access the Pdf File I have to do现在在我的控制器中每次我必须检查用户是否有权访问我必须做的 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;
}
Now imagine this scenario where everytime I have to access the model either for edit details, delete etc I have to check现在想象一下这种情况,每次我必须访问模型以进行编辑详细信息、删除等操作时,我都必须检查
if (model.UserGroup == User.UserGroup) // plus I have to check XML in secureinfo for individual for each user when editing or deleting
for lists i have to do对于我必须做的清单
var dblist = db.PdfSet.ToList();
dblist = dblist.Where(u => u.UserGroup == User.UserGroup).ToList();
This makes the controller code very ugly and hard to debug on error Is there any way I can do these checks in my DbContext directly when Editing, Creating, Deleting, Accessing the record?这使得控制器代码非常难看,并且在出错时难以调试 有什么方法可以在编辑、创建、删除、访问记录时直接在我的 DbContext 中进行这些检查?
I am not even sure if this is the correct method to do security check for Users.我什至不确定这是否是对用户进行安全检查的正确方法。
I agree with you it makes code ugly and hard to maintain but it's not a good idea to couple data access with cross-cutting concerns and consider using role.我同意你的看法,它使代码变得丑陋且难以维护,但将数据访问与横切关注点结合起来并考虑使用角色并不是一个好主意。 Create a role and determine the role has access to which part of the application then assign a user to a role.创建角色并确定该角色有权访问应用程序的哪个部分,然后将用户分配给角色。 Create a role and name it PdfAccess
and use the Authorize
attribute with the role:创建一个角色并将其命名为PdfAccess
并使用该角色的Authorize
属性:
[Authorize("PdfAccess")]
[NoUserGroupNoAccess]
public ActionResult SendSingleItem(int? id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.