![](/img/trans.png)
[英]How can I implement Claims-Based Authorization with ASP.NET WebAPI without using Roles?
[英]Claims-based authorization and where to add what the user can do
我剛剛使用基於聲明的授權實現了 web api。 用戶可以登錄系統,然后根據用戶可以執行的操作從數據庫中提取一組聲明並添加到 httpContext.User.Identity。
在 Startup.cs 中注冊策略后,使用以下內容:
services.AddAuthorization(options =>
{
options.AddPolicy(PoliciesDefinitions.RequiresVehicleList, policy => policy.RequireClaim(Permissions.VehiclesList.ToString()));
...
});
我可以在要授權的控制器方法上使用 Authorize 屬性,例如:
Authorize(Policy=PoliciesDefinitions.RequiresDriversList)]
[HttpGet]
public ActionResult Get() { ... }
這工作正常,但今天我更徹底地閱讀了微軟文檔,我在基於聲明的授權文檔中遇到了這個聲明:
聲明是一個名稱值對,表示主題是什么,而不是主題可以做什么
目前,我正在做 microsfot 建議不要做的事情。 我正在將用戶可以做的事情(權限)添加到身份中。 所以,這讓我想,我做錯了嗎? 如果答案是肯定的,您將在哪里存儲用戶權限以及授權如何工作?
這允許 KVP 和多個值。
// with Razor, you did not specific if it was core 2, 3.1 or Razor
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddRazorPages();
services.AddAuthorization(options =>
{
options.AddPolicy("Vendors", policy =>
policy.RequireClaim("Type.Tykt.org", "Dealer", "Driver", "WholeSaler", "Asset", "Repair"));
});
}
選項 2:
還有一個claims
集合,您可以在用戶成功登錄后添加它。
var user = new User {
Email = "xyz@tykt.org",
Name = "xyz"
}
user.Claims.Add(new IdentityUserClaim<string>
{
ClaimType="your-type", // your key
ClaimValue="your-value" // your value
});
await userManager.CreateAsync(user);
更新參考 MSDN :
如果我理解這個問題,那么您對如何存儲檢索確實是您的選擇,那么您的問題就是索賠的價值。
通常,映射和驗證發生在PermissionHandler: IAuthorizationHandler
或通用方法MinimumAgeHandler: AuthorizationHandler<MinimumAgeRequirement>
中。 其中,加載值,並處理特定權限的要求驗證,例如最小年齡,但實際聲明(您在說明什么/ min age policy
與值通常在數據庫中,如 DOB= 1/1/1990
) 與Principal
object 一起旅行。 現在,您選擇在哪里檢索索賠的價值取決於您
在下面的 function 中,他從 Context 中獲取 Key 的值,然后進行驗證
public class MinimumAgeHandler : AuthorizationHandler<MinimumAgeRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
MinimumAgeRequirement requirement)
{
if (!context.User.HasClaim(c => c.Type == ClaimTypes.DateOfBirth &&
c.Issuer == "http://contoso.com"))
{
return Task.CompletedTask;
}
var dateOfBirth = Convert.ToDateTime(
// He gets the value on the server-side from any store or 3rd party relayer
context.User.FindFirst(c => c.Type == ClaimTypes.DateOfBirth &&
c.Issuer == "http://contoso.com").Value);
int calculatedAge = DateTime.Today.Year - dateOfBirth.Year;
if (dateOfBirth > DateTime.Today.AddYears(-calculatedAge))
{
calculatedAge--;
}
if (calculatedAge >= requirement.MinimumAge)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.