Dependency Injection on Authorization Policy

前端 未结 3 1234
滥情空心
滥情空心 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:27

    Thanks to Nkosi for the tip!

    Since AddAuthorization is basically configuring AuthorizationOptions behind the scenes, I followed the same pattern only I used OptionsBuilder to configure options with dependencies

    I created my own AddAuthorization method that accepts dependencies:

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

    And now I can use it to properly configure the requirement:

    services.AddAuthorization((options, employeeProvider> =>
    {
        options.AddPolicy("Founders", policy =>
            policy.RequireClaim("EmployeeNumber", employeeProvider.GetAuthorizedEmployeeIds())
        );
    });
    

    You can follow the same technique if you need more dependencies (OptionsBuilder.Configure supports up to 5 dependencies)

    Obviously, this solution requires extra validation when upgrading to newer ASP versions, as the underlying implementation of AddAuhtorization may change

提交回复
热议问题