Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core AuthenticationHandler dependency injection

Following this article, I am trying to implement a custom AuthenticationHandler, but I got stuck on dependency injection.

I need to inject an IRepository instance into the AuthenticationHandler to provide a dbo connection (to check the credentials).

Code:

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("...");
        );
    }

Do you have any hints?

Thanks

like image 799
Luke1988 Avatar asked Jun 23 '26 19:06

Luke1988


1 Answers

Just add the repository dependency to the constructor, set the variable in the constructor body

public CustomAuthenticationHandler(
    IOptionsMonitor<CustomAuthenticationOptions> options,
    ILoggerFactory logger,
    UrlEncoder encoder,
    ISystemClock clock,
    IRepository repo)
        : base(options, logger, encoder, clock) {
    repository = repo;
}
like image 74
pedrommuller Avatar answered Jun 25 '26 18:06

pedrommuller