简体   繁体   中英

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

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

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

and in my Identity model I have a variable 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

[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?

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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