Dependency Injection on Authorization Policy

前端 未结 3 1211
滥情空心
滥情空心 2021-01-19 16:08

I want to create a claim based authorization for my ASP.NET Core app:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthorizat         


        
3条回答
  •  深忆病人
    2021-01-19 16:11

    To supplement the provided answer by @MichaelShterenberg, the configuration delegate can use a IServiceProvider to allow for additional dependencies

    public static IServiceCollection AddAuthorization(this IServiceCollection services,
        Action configure) {
        services.AddOptions().Configure(configure);
        return services.AddAuthorization();
    }
    

    Which, based on the original example, can be used

    public void ConfigureServices(IServiceCollection services) {
    
        //...
    
        service.AddScoped();
    
        services.AddAuthorization((options, sp) => {
            IEmployeeProvider employeeProvider = sp.GetRequiredService();
            options.AddPolicy("Founders", policy =>
                policy.RequireClaim("EmployeeNumber", employeeProvider.GetAuthorizedEmployeeIds())
            );
        });
    
        //...
    }
    

    If there were other dependencies needed, they could be resolved from the service provider.

提交回复
热议问题