3

We just migrated our authentication middleware from .net core 1.1 to .net core 2.0, following the example from this answer. Everything builds and runs, however, when I try to make a request (even when trying to get to the Swagger UI) I get the following exception on my custom AuthenticationHandler called UserAuthHandler : System.InvalidOperationException: A suitable constructor for type 'BrokerAPI.AuthMiddleware.UserAuthHandler' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.
The code from UserAuthHandler:

public class UserAuthHandler : AuthenticationHandler<UserAuthAuthenticationOptions>    
{
    protected UserAuthHandler(IOptionsMonitor<UserAuthAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
    {
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        //handle authentication
        var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity),
           new AuthenticationProperties(), "UserAuth");

        return Task.FromResult(AuthenticateResult.Success(ticket));
    }
}

The code from UserAuthExtensions:

public static class UserAuthExtensions
{
    public static AuthenticationBuilder AddCustomAuth(this AuthenticationBuilder builder, Action<UserAuthAuthenticationOptions> configureOptions)
    { 
        return builder.AddScheme<UserAuthAuthenticationOptions, UserAuthHandler>("UserAuth", "UserAuth", configureOptions);
    }
}

How I call everything in Startup.cs:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(options =>
            {
                options.DefaultScheme = "UserAuth";
            }).AddCustomAuth(o => { });
    }
public void Configure()
    {
        app.UseAuthentication();
    }

I have scavenged Google for examples and people with similar issues, but to no avail.

Am I missing something related to my DI-container? Or is it something related to Authentication in .net core 2 in general?

Thanks in advance.

Teodor Savov
  • 71
  • 1
  • 7

1 Answers1

6

The exception message is actually really clear: your handler has a protected constructor that cannot be used by the dependency injection system. Make it public and it should work:

public class UserAuthHandler : AuthenticationHandler<UserAuthAuthenticationOptions>    
{
    public UserAuthHandler(IOptionsMonitor<UserAuthAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
    {
    }
}
Kévin Chalet
  • 39,509
  • 7
  • 121
  • 131