.net.net-8.0

WebApplicationFactory httpClient not saving auth cookie


I'm working on some integration tests using MSTest.

In one of my tests I'm calling my login endpoint which is returning correctly. Using the same HttpClient I'm calling another endpoint and getting a 401

Inspecting the request I see the cookies are empty on the following request.

Custom App Factory

public class WebAppFactory<TProgram> : WebApplicationFactory<TProgram> where TProgram : class

** Test method **

Factory = new WebAppFactory<Program>();
Client = Factory.CreateClient();

// 200 with correct response and set-cookies header
var jsonContent = JsonSerializer.Serialize(new { Username = "test", Password = "test"});
var requestContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
var authResponse = await Client.PostAsync("/login", requestContent);

// 401
var response = await Client.GetAsync("/user/details");

Solution

  • Most likely your cookie has the attribute “secure = true”. By default, WebApplicationFactoryClientOptions creates a client that accesses via http. Therefore, this cookie will not be passed.

    Set the https BaseAddress when you create the client

    Client = Factory.CreateClient(new WebApplicationFactoryClientOptions
            {
                BaseAddress = new Uri("https://localhost")
            });