I want to create a claim based authorization for my ASP.NET Core app:
(我想为我的ASP.NET Core应用创建基于声明的授权:)
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthorization(options =>
{
options.AddPolicy("Founders", policy =>
policy.RequireClaim("EmployeeNumber", "1", "2", "3", "4", "5"));
});
}
The problem is that I have a non trivial method to resolve the employee numbers (1 to 5) and I want to use a DI service:
(问题是我有一种非平凡的方法来解析员工人数(1到5),并且我想使用DI服务:)
public interface IEmployeeProvider {
string[] GetAuthorizedEmployeeIds();
}
I would like to inject this service and use it in AddPolicy, something like:
(我想注入此服务并在AddPolicy中使用它,例如:)
services.AddAuthorization(options =>
{
options.AddPolicy("Founders", policy =>
policy.RequireClaim("EmployeeNumber", *employeeProvider.GetAuthorizedEmployeeIds()));
});
Note
(注意)
I know that I can write my own AuthorizationHandler where I can easily inject IEmployeeProvider
but I'm against this pattern because:
(我知道我可以编写自己的AuthorizationHandler,在其中可以轻松注入IEmployeeProvider
但是我反对这种模式,因为:)
- There is a already a handler that does exactly what I need
(已经有一个处理程序可以完全满足我的需要)
- I need to write a new handler for each claim type and each different requirement
(我需要为每个索赔类型和每个不同的需求编写一个新的处理程序)
- This is an anti pattern because the employee ids should really be part of the requirement while the handler should be generic component that handles the requirements
(这是一种反模式,因为员工id实际上应该是需求的一部分,而处理程序应该是处理需求的通用组件)
So I'm looking for a way to inject services when the policy is being built
(所以我正在寻找一种在构建策略时注入服务的方法)
ask by Michael Shterenberg translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…