Добавление пользовательского BasicAuthenticationHandler в .NET Core - проблемы с внедрением необходимых служб в обработчик - PullRequest
1 голос
/ 07 ноября 2019

Мне нужно добавить наш пользовательский обработчик базовой аутентификации, но наша реализация требует передачи ему параметров. Я не могу добиться этого с помощью DI. Вот часть кода:

    // Part of ConfigureServices in Startup.cs
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        ...
        // Some DIs in ConfigureService
        services.AddTransient<ICustomService, CustomService>(); //this should be passed later to handler
        services.AddHttpContextAccessor();
        ...
        // Adding authentication in ConfigureServices
        services.AddAuthentication("Basic")
            .AddScheme<CustomBasicAuthenticationOptions, CustomBasicAuthenticationHandler>(
            "Basic",
            options => new CustomBasicAuthenticationOptions()
            {
                CustomService = ??? // HOW OT GET CustomService: ICustomService from Container here?
            });
      ...
   }

   // CustomBasicAuthenticationOptions
   public class CustomBasicAuthenticationOptions : AuthenticationSchemeOptions
   {
       public CustomBasicAuthenticationOptions();
       public static string AuthenticationScheme { get; }
       public ICustomService CustomService { get; set; }  //THIS SHOULD BE INJECTED HERE during AddAuthentication?! How?
       ...
   }

   // CustomService and its constructor of 
   public class CustomService : ICustomService 
   {
       public CustomService(IHttpContextAccessor httpContextAccessor) {
          ...
       }
   }

1 Ответ

0 голосов
/ 07 ноября 2019

Вы комментируете в исходном примере, показывает, что на самом деле зависит от службы

// это должно быть передано позже обработчику

Переместите службу в обработчикв качестве явной зависимости через внедрение в конструктор.

public class CustomBasicAuthenticationHandler : AuthenticationHandler<CustomBasicAuthenticationOptions> {
    private readonly ICustomService customService;

    public CustomBasicAuthenticationHandler(
        ICustomService customService, //<-- NOTE
        IOptionsMonitor<BasicAuthenticationOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder,
        ISystemClock clock
    )
    : base(options, logger, encoder, clock) {
        this.customService = customService;
    }

    //...
}

и рефакторинг регистрации

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    //...

    // Some DIs in ConfigureService
    services.AddTransient<ICustomService, CustomService>(); //this should be passed later to handler
    services.AddHttpContextAccessor();

    //...

    // Adding authentication in ConfigureServices
    services.AddAuthentication("Basic")
        .AddScheme<CustomBasicAuthenticationOptions, CustomBasicAuthenticationHandler>("Basic", null);

    //...
}
...