authentication - 在 .NET Core API 集成测试中使用正确的身份验证方案

标签 authentication testing .net-core integration-testing okta

我们正在尝试支持多种身份验证方案。这适用于非测试代码,但不适用于我们的集成测试。

在我们的集成测试中,我们无法为给定测试使用正确的身份验证方案。一些测试测试我们的 NTLM 身份验证,而其他测试则测试我们的 Bearer 身份验证。我们可以执行 NTLM 身份验证或 Bearer 身份验证,但我们的代码无法从我们的测试请求中正确选择要使用的身份验证方案。

在我们应用程序的启动代码中,我们为 Okta 配置了 JWT 承载身份验证:

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());
    });

在我们的集成测试 WebApplicationFactory 中,我们使用身份验证方案名称“Test”设置了一个测试身份验证处理程序:

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

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

我们的承载身份验证测试发出这样的请求:

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

出于某种原因,我们的测试身份验证始终使用我们的集成 WebApplicationFactory 中定义的默认身份验证方案,而从不使用我们认为应该基于请求的方案。

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

有人知道我们做错了什么吗?

最佳答案

在 AddAuthentication("Test") 上面添加以下代码,然后它将工作并识别测试方案。

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

关于authentication - 在 .NET Core API 集成测试中使用正确的身份验证方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62032627/

相关文章:

未在 REST 服务器上验证来自 Flutter App 的 Firebase Id token

c# - 如何使 API 仅向每个用户发出一个 token (在多个选项卡中打开)?

c# - 我可以在 C# 中将 gRPC 和 webapi 应用程序组合到 .NET Core 3.0 中吗?

c++ - 在 Windows 上使用 OpenSSL 通过身份验证访问 REST API

ios - Pinterest SDK 验证权限失败

php - Laravel 5.1 auth attempt with extra parameters using default auth controller and middleware

python - 有没有更简洁的方法来测试 python3 中的长参数列表?

javascript - mocha assert.deepEqual 当其中一个值是函数时?

ruby-on-rails - 使用 React 和 Selenium-Webdriver 以 Rails 作为后端的前端测试

.net - 如何在不使用 Authorize 属性的情况下获取 User.Identity 值?