【问题标题】:Migrating Authentication from dotnet core 1.1 to dotnet core 2.0将身份验证从 dotnet core 1.1 迁移到 dotnet core 2.0
【发布时间】:2018-04-05 04:59:53
【问题描述】:

我们刚刚将身份验证中间件从 .net core 1.1 迁移到 .net core 2.0,遵循this 答案中的示例。但是,当我尝试发出请求时(即使尝试访问 Swagger UI),一切都会构建并运行,我在名为 UserAuthHandler 的自定义 AuthenticationHandler 上收到以下异常: 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();
    }

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

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

提前致谢。

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-02-15
      • 2018-01-28
      • 2018-05-28
      • 2018-02-04
      • 2018-01-28
      • 2020-02-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-27
      相关资源
      最近更新 更多