dependency-injection - 将身份验证从 dotnet core 1.1 迁移到 dotnet core 2.0

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

我们刚刚将身份验证中间件从 .net core 1.1 迁移到 .net core 2.0,遵循 this 中的示例回答。但是,当我尝试发出请求时(即使是尝试访问 Swagger UI),一切都会构建并运行: System.InvalidOperationException:找不到适合“BrokerAPI.AuthMiddleware.UserAuthHandler”类型的构造函数。确保类型是具体的,并且为公共(public)构造函数的所有参数注册了服务。
来自 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();
    }

我已经在 Google 上搜索过类似问题的示例和人员,但无济于事。

我是否遗漏了与我的 DI 容器相关的内容?还是一般来说与 .net core 2 中的身份验证有关?

提前致谢。

最佳答案

异常消息实际上非常清楚:您的处理程序有一个 protected 构造函数,不能被依赖注入(inject)系统使用。公开它,它应该可以工作:

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

关于dependency-injection - 将身份验证从 dotnet core 1.1 迁移到 dotnet core 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46909801/

相关文章:

android - 如何将 Activity 注入(inject)到正在注入(inject) Activity 的对象中?

asp.net-mvc - MVC 项目之外的 DbContext 依赖注入(inject)

c# - MVC6 默认页面

c# - SignInManager.PasswordSignInAsync() 成功,但 User.Identity.IsAuthenticated 为 false

asp.net - VS 2015 Preview 缺少 "ASP.NET 5 Web Application"项目类型?

asp.net - 将 session 超时增加到一周或更长时间

java - 如何使用控制反转在java中创建即插即用代码?

ASP.NET Forms 身份验证需要启用匿名

asp.net - 如何在 ASP.NET 中使用多个授权方案颁发相应的 Bearer 和 Cookie 标识?

c# - Ninject - 静态类中的内核?