Search code examples
c#asp.net-mvcasp.net-coreintegration-testing

Negotiate authentication and Microsoft.AspNetCore.Mvc.Testing


learn.microsoft.com recommends to use Microsoft.AspNetCore.Mvc.Testing for integration tests and it seems to be a great choice, but it seems that they missed to add the ability to test with NegotiateDefaults.AuthenticationScheme.

Adding to Startup.cs/ConfigureServices

 services.AddAuthentication (NegotiateDefaults.AuthenticationScheme).AddNegotiate ();

causes the tests to fail with

Message: System.NotSupportedException : Negotiate authentication requires a server that supports IConnectionItemsFeature like Kestrel.

Does anybody know how to use Microsoft.AspNetCore.Mvc.Testing with endpoints that use NegotiateDefaults.AuthenticationScheme? Is it just not supported, like the exception claims?


Solution

  • That is not supported by design

    WebApplicationFactory doesn't use kestrel, it uses the in-memory TestServer and in-memory HttpClient. Neither of those support the features needed for Negotiate auth.

    I dropped Microsoft.AspNetCore.Mvc.Testing and used a custom NUnit base class instead:

    public class AspNetCoreIntegrationTestBase
    {
      public CancellationTokenSource? CancellationTokenSource { get; set; }
    
      public Task? TestWebserver { get; set; }
    
      [OneTimeSetUp]
      public void Setup()
      {
        CancellationTokenSource = new CancellationTokenSource();
        TestWebserver = Program.CreateHostBuilder(Array.Empty<string>()).Build().StartAsync(CancellationTokenSource.Token);
      }
    
      [OneTimeTearDown]
      public void CleanUp()
      {
        CancellationTokenSource?.Cancel();
        TestWebserver?.Dispose();
      }
    }
    

    The httpclient to use needs to be initialized with

    UseDefaultCredentials = true