dotnet / AspNetCore.Docs

Documentation for ASP.NET Core
https://docs.microsoft.com/aspnet/core
Creative Commons Attribution 4.0 International
12.65k stars 25.28k forks source link

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

Open vladig98 opened 1 year ago

vladig98 commented 1 year ago

Is there an existing issue for this?

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

martincostello commented 1 year ago

Hey @vladig98 - If you click the Open a documentation issue link at the bottom of the page, it will take you to a GitHub issue in the repo where the docs are stored. If you have the time, you could also submit a pull request in the same repo to make the change you suggest for the documentation team to review.

image

mkArtakMSFT commented 9 months ago

Thanks for bringing this up to our attention, @vladig98. Your recommded change does sound reasonable. Feel free to submit a PR in the dotnet/AspNetCore.Docs repo with this change: https://github.com/dotnet/AspNetCore.Docs.Samples/blob/b24f6b3845a2cb1956081dd883abeb016ab254e6/test/integration-tests/IntegrationTestsSample/tests/RazorPagesProject.Tests/IntegrationTests/AuthTests.cs#L109

Rick-Anderson commented 9 months ago

@vladig98 source here

Are you interested doing a PR for this? Let me know, otherwise I'll ask other folks.