Dot-Net
對特定資源的聲明授權
我正在編寫一個範例文件儲存系統(僅用於 stackoverflow 的範例)。
我目前的域模型如下所示:
public class User { public int ID { get; set; } public string LoginIdentifier { get; set; } public string Password { get; set; } } public class File { public int ID { get; set; } public int UserID { get; set; } public string FileName { get; set; } public byte[] Data { get; set; } }我正在編寫的創建 IPrincipal 的程式碼:
private static IPrincipal CreatePrincipal(User user) { Debug.Assert(user != null); var identity = new GenericIdentity(user.LoginIdentifier, "Basic"); // TODO: add claims identity.AddClaim(new Claim("Files", "Add")); return new GenericPrincipal(identity, new[] { "User" }); }在我的系統中,使用者可以添加文件,也可以檢索、刪除和更新文件,但是需要注意的是使用者只能檢索和修改自己的文件(其中
File.UserID應與登錄使用者的身份匹配) .我的文件控制器如下所示。
[Authorize] public class FilesController : ApiController { private readonly FileRepository _fileRepository = new FileRepository(); public void Post(File file) { // not sure what to do here (...pseudo code...) if (!CheckClaim("Files", "Add")) { throw new HttpError(HttpStatusCode.Forbidden); } // ... add the file file.UserID = CurrentPrincipal.UserID; // more pseudo code... _fileRepository.Add(file); } public File Get(int id) { var file = _fileRepository.Get(id); // not sure what to do here (...pseudo code...) if (!CheckClaim("UserID", file.UserID)) { throw new HttpError(HttpStatusCode.Forbidden); } return file; } }也許使用
Claims 不是適合這項工作的工具,但希望這能說明問題。我應該如何連接我的控制器以確保目前登錄的使用者有權執行特定操作,更具體地說,某些資源?
我不確定索賠是否是您正在做的事情的正確方法。您真正想要表示的是權限。聲明通常代表身份屬性,例如使用者名、電子郵件或它所屬的角色,但不代表權限。您可以使用聲明來表示權限,但您可能需要大量權限,具體取決於您的應用程序有多大。一種典型的方法是將角色映射到一組權限(在您的情況下,添加文件將是一個權限)。您還可以創建從 AuthorizeAttribute 派生的自定義授權過濾器,以檢查目前主體是否具有執行操作的正確權限。該過濾器可能會接收執行操作所需的權限作為參數。