gpt4 book ai didi

ASP.NET Core AuthenticationHandler 依赖注入(inject)

转载 作者:行者123 更新时间:2023-12-04 00:32:06 26 4
gpt4 key购买 nike

正在关注 this article ,我正在尝试实现自定义 AuthenticationHandler,但我陷入了依赖注入(inject)。

我需要将 IRepository 实例注入(inject)到 AuthenticationHandler 中以提供 dbo 连接(以检查凭据)。

代码:

public class CustomAuthenticationHandler : AuthenticationHandler<CustomAuthenticationOptions>  
{
// how to inject this?!
private IRepository repository;

public CustomAuthenticationHandler(IOptionsMonitor<CustomAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock) {
}

protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
// this is just a sample
if (repository.users.Count(w => w.user_name == Request.Headers["user_name"] && w.password == Request.Headers["password"]) == 1)
{
return Task.FromResult(
AuthenticateResult.Success(
new AuthenticationTicket(
new ClaimsPrincipal(Options.Identity),
new AuthenticationProperties(),
this.Scheme.Name)));
}

return Task.FromResult(
AuthenticateResult.Failed("...");
);
}

你有什么提示吗?

谢谢

最佳答案

只需在构造函数中添加repository依赖,在构造函数体中设置变量

public CustomAuthenticationHandler(
IOptionsMonitor<CustomAuthenticationOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock,
IRepository repo)
: base(options, logger, encoder, clock) {
repository = repo;
}

关于ASP.NET Core AuthenticationHandler 依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49656999/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com