-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Closed
Description
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
Labels
No labels