簡體   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