0

I've been following the official documentation to mock the authorization service, and it seems to be working perfectly when using JWTBearer authentication, but it returns a 500 status code when I try using Negotiate instead.

Working Program.cs

builder.Services.AddAuthentication("Bearer")
   .AddJwtBearer();

NOT working Program.cs

builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
   .AddNegotiate();

Test code

...

HttpClient client = _factory.WithWebHostBuilder(builder =>
    {
        builder.ConfigureTestServices(services =>
        {
            services.AddAuthentication("Test")
                .AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("Test", options => { });
        });
    })
    .CreateClient();

client.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue(scheme: "Test");

var response = await client.GetAsync("/my-endpoint"); // HTTP status is 200 with JWTBearer but 500 with Negotiate

...

TestAuthHandler.cs

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

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var claims = new[] { new Claim(ClaimTypes.Name, "Test user") };
        var identity = new ClaimsIdentity(claims, "Test");
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, "Test");

        AuthenticateResult result = AuthenticateResult.Success(ticket);

        return Task.FromResult(result);
    }
}
Tiny Wang
  • 10,423
  • 1
  • 11
  • 29
Matteo
  • 1
  • 1
  • Is there any sub status code? and development mode error details. – Qiang Fu Aug 10 '23 at 10:07
  • Thank you @QiangFu, the exception thrown was "Negotiate authentication requires a server that supports IConnectionItemsFeature like Kestrel." It led me to these related questions that clarify that it is not possible to do it this way and provide useful workarounds: https://stackoverflow.com/q/60111553/22364883 https://stackoverflow.com/q/72400529/22364883 – Matteo Aug 10 '23 at 13:18

0 Answers0