Passing claims into HandleAuthenticateAsync for integration testing

Viewed 20

While following Microsoft's ASP.NET Core guide for integration testing authentication, I have the following test built for Authentication:

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

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

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

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

What I want to do, is use the [Theory] option instead of [Fact] to test multiple Authentications so it will look like this:

[Theory]
[InlineData("TestAuth1","12345")]
[InlineData("TestAuth2","23456")]
[InlineData("TestAuth3","34567")]
public async Task Get_SecurePageIsReturnedForAnAuthenticatedUser(string claim, string claimsIdentity)
{
   var claim = new Claim(claim, claimsIdentity);

.
.
.

However I'm not sure how to pass claim to TestAuthHandler through AddScheme<AuthenticationSchemeOptions, TestAuthHandler>

Here is the given TestAuthHandler

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");

        var result = AuthenticateResult.Success(ticket);

        return Task.FromResult(result);
    }
}

I would like to replace the claims variable in HandleAuthenticaAsync() with the claim passed into Get_SecurePageIsReturnedForAnAuthenticatedUser(Claim claim)

As a note they do have to be tested individually since my current authentication will pass as long as one correct authentication exists in the HandleAuthenticateAsync claims variable.

Thank you for any help provided.

0 Answers
Related