将身份验证从dotnet核心1.1迁移到dotnet核心2.0

时间:2017-10-24 11:48:48

标签: dependency-injection asp.net-core asp.net-authentication

我们刚刚将我们的身份验证中间件从.net核心1.1迁移到.net核心2.0,遵循this回答的示例。但是,当我尝试发出请求时(即使在尝试访问Swagger UI时),所有内容都会构建和运行。我在名为AuthenticationHandler的自定义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.
来自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));
    }
}

来自UserAuthExtensions的代码:

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

我如何调用Startup.cs中的所有内容:

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

我已经向谷歌搜寻了类似问题的例子和人,但无济于事。

我错过了与我的DI容器有关的东西吗?或者它是否与.net core 2中的身份验证有关?

提前致谢。

1 个答案:

答案 0 :(得分:6)

异常消息实际上非常清楚:您的处理程序有一个受保护的构造函数,依赖注入系统无法使用它。公开它应该有效:

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