[英]ASP.NET Core 6 MVC : how to configure authentication and authorisation based on person department/role
我正在尋找有關如何在 ASP.NET Core 6 中實現我的安全要求的一些建議。
基本上,我的公司 A 擁有多項資產(資產 A、資產 B)。
我設想了以下角色:
到目前為止,我想到的兩條途徑是
選項1
as.netUserRole
表以包含AssetId
SignInManager
並更改IsInRole
以檢查用戶是否具有assetId
的角色。 assetId
存儲在聲明中。這樣做的缺點是,對於角色管理員來說,任何具有此功能的人都需要添加到每個位置,這似乎有點痛苦。
選項 2
政策,我想知道這是否是更好的選擇,但我不確定如何構建它以使其對用戶友好。
我在考慮政策:
然后我需要一個連接策略、資產和用戶的新表來確定他們對每個資產的策略。
但是我應該如何處理應該做任何事情的管理員? 它會像一個名為SiteAdmin
的策略一樣簡單嗎?
我認為您可以嘗試向用戶添加另一個聲明Asset
//For SuperUser:
var userclaim = new Claim("Asset","AssetA");
//var userclaim = new Claim("Asset","AssetB");
.......
//For Administrator
var userclaim = new Claim("Asset","AllAsset");
// add the claim to User
var claimresult = await _userManager.AddClaimAsync(user, userclaim);
為用戶添加角色:
await _rolemanager.CreateAsync(new IdentityRole("Admin"));
var addroleresult = await _userManager.AddToRoleAsync(user, "Admin");
注冊政策:
public void ConfigureServices(IServiceCollection services)
{
.......
services.AddAuthorization(options =>
{
options.AddPolicy("AssetA",
policy => policy.RequireClaim("Asset", "AssetA", "AllAsset").RequireRole("Admin", "SuperAdmin"));
options.AddPolicy("AssetB",
policy => policy.RequireClaim("Asset", "AssetB", "AllAsset").RequireRole("Admin", "SuperAdmin"));
options.AddPolicy("SuperAdmin",
policy => policy.RequireRole("SuperAdmin"));
});
}
用控制器測試:
[Authorize(Policy = "AssetA")]
public IActionResult AssetA()
{
return View();
}
[Authorize(Policy = "AssetB")]
public IActionResult AssetB()
{
return View();
}
[Authorize(Policy = "SuperAdmin")]
public IActionResult SuperAdmin()
{
return View();
}
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.