Using Correct Authentication Scheme In .NET Core API Integration Test

Viewed 890

We are trying to support multiple authentication schemes. This is working in non-test code, but not working in our integration tests.

In our integration tests, we are unable to use the correct authentication scheme for a given test. Some tests test our NTLM authentication while others test our Bearer authentication. We can do either NTLM auth or Bearer auth but our code is unable to correctly choose which authentication scheme to use from our test request.

In our app's startup code, we have JWT bearer authentication configured for Okta:

services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", opt =>
    {
        opt.Audience = Configuration.GetValue<string>("Okta:Audience");
        opt.Authority = issuer;
        opt.TokenValidationParameters = validationParameters;
        opt.BackchannelHttpHandler = new UserAgentHandler("okta-aspnetcore",
            typeof(OktaAuthenticationOptionsExtensions).Assembly.GetName().Version);
        opt.SecurityTokenValidators.Clear();
        opt.SecurityTokenValidators.Add(new StrictSecurityTokenValidator());
    });

In our integration test WebApplicationFactory, we have a test authentication handler set up using the authentication scheme name "Test":

builder.ConfigureTestServices(x =>
{
    x.AddScoped<IIdentityProvider, FakeIdentityProvider>(factory => new FakeIdentityProvider(User));

    x.AddAuthentication("Test")
        .AddScheme<AuthenticationSchemeOptions, TestAuthenticationHandler>("Test", null);
});

Our Bearer auth tests make a request like this:

var factory = new WebApiApplicationFactory();
var client = factory.CreateClient();

var oktaToken = await TestConfiguration.GetOktaTokenAsync();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", $"{oktaToken}");
await client.PostAsync(uri, content);

For some reason, our test authentication always uses the default authentication scheme defined in our integration WebApplicationFactory and never uses the one that we think it should based on the request.

x.AddAuthentication("Test")
    .AddScheme<AuthenticationSchemeOptions, TestAuthenticationHandler>("Test", null);

Anyone know what we are doing wrong?

1 Answers

Add below code above AddAuthentication("Test") then it will work and recognize Test scheme.

                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = "Test";
                    options.DefaultChallengeScheme = "Test";
                });
Related