我们刚刚将身份验证中间件从 .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/