Skip to content

Adding a custom AuthenticationHandler doesn't work / HandleAuthenticateAsync does not get invoked #18125

@jochenz

Description

@jochenz

I started from the example on the official documentation page and defined a simple custom authentication handler, which I added to my integration test startup:

    internal class DemoApiFactory : WebApplicationFactory<Startup>
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureTestServices(services =>
            {
                services
                    .AddAuthentication(TestAuthentication.Scheme)
                    .AddScheme<AuthenticationSchemeOptions, TestAuthenticationHandler>(TestAuthentication.Scheme, null);
            });
        }
    }

When running tests with this code, the TestAuthenticationHandler does get challenged, but HandleAuthenticateAsync never gets invoked.

Here's a simple solution on github with integration tests to reproduce the issue.

The TestAuthenticationHandler is defined as:

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

        protected override Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            var testAuthHeaderPresent = Request
                .Headers[HeaderNames.Authorization]
                .Contains(TestAuthentication.Scheme);

            var authResult = testAuthHeaderPresent ? AuthenticatedTestUser() : AuthenticateResult.NoResult();

            return Task.FromResult(authResult);
        }

        protected override Task HandleChallengeAsync(AuthenticationProperties properties)
        {
            Response.Headers["WWW-Authenticate"] = TestAuthentication.Scheme;

            return base.HandleChallengeAsync(properties);
        }

        private static AuthenticateResult AuthenticatedTestUser()
        {
            var claims = new[] { new Claim(ClaimTypes.Name, "Test user") };
            var identity = new ClaimsIdentity(claims, TestAuthentication.Scheme);
            var principal = new ClaimsPrincipal(identity);
            var ticket = new AuthenticationTicket(principal, TestAuthentication.Scheme);

            return AuthenticateResult.Success(ticket);
        }
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions