Skip to content

[Mock Authentication] Integration tests in ASP.NET Core #31717

@vladig98

Description

@vladig98

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-7.0#mock-authentication

This code doesn't work. Authentication fails. You need to introduce additional settings to the authentication service. Change the code from this

[Fact]
public async Task Get_SecurePageIsReturnedForAnAuthenticatedUser()
{
    // Arrange
    var client = _factory.WithWebHostBuilder(builder =>
        {
            builder.ConfigureTestServices(services =>
            {
                services.AddAuthentication(defaultScheme: "TestScheme")
                    .AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(
                        "TestScheme", options => { });
            });
        })
        .CreateClient(new WebApplicationFactoryClientOptions
        {
            AllowAutoRedirect = false,
        });

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

    //Act
    var response = await client.GetAsync("/SecurePage");

    // Assert
    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}

to this

[Fact]
public async Task Get_SecurePageIsReturnedForAnAuthenticatedUser()
{
    // Arrange
    var client = _factory.WithWebHostBuilder(builder =>
        {
            builder.ConfigureTestServices(services =>
            {
                services.AddAuthentication(o =>
                    {
                        o.DefaultAuthenticateScheme = "TestScheme";
                        o.DefaultChallengeScheme = "TestScheme";
                    }).AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(
                        "TestScheme", options => { });
            });
        })
        .CreateClient(new WebApplicationFactoryClientOptions
        {
            AllowAutoRedirect = false,
        });

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

    //Act
    var response = await client.GetAsync("/SecurePage");

    // Assert
    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}

Expected Behavior

You should be able to acces authenticated pages when you've mocked the authentication.

Steps To Reproduce

Implement the "mock authentication" steps and try to access a page that requires authentication. You will receive a 401.

Exceptions (if any)

The HTTPClient returns 401 even when you're mocking the authentication.

.NET Version

7.0.201

Anything else?

https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-7.0#mock-authentication

Page URL

https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-8.0#client-options

Content source URL

https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/test/integration-tests.md

Document ID

f499b131-8b14-7e10-1728-543fdd5a5656


Associated WorkItem - 340922

Metadata

Metadata

Assignees

No one assigned

    Labels

    💣 vanQUESTLabel to remove an item from Azure DevOps.doc-bugseQUESTeredIdentifies that an issue has been imported into Quest.

    Type

    No type

    Projects

    Status

    To do

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions