c# - 使用依赖注入(inject)替换 ASP.NET Core 中的 JWT Bearer Options

标签 c# dependency-injection integration-testing asp.net-core-2.0 identityserver4

在 Web API 中,我使用 Jwt Auth 进行保护,我有以下 ConfigureServices Startup.cs :

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(this.Configuration.GetConnectionString("DefaultConnection")));
    // Some additional application dependencies here with AddTransient()...
    services.AddMvc();
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
           options.Authority = "xxxxx";
           options.RequireHttpsMetadata = false;
           options.Audience = "xxxxx";
           options.BackchannelHttpHandler = BackChannelHandler;
        });
}

在这里,BackChannelHandlerStartup.cs 的公共(public)属性(property):

public static HttpMessageHandler BackChannelHandler { get; set; }

我使用此属性的原因是,当我使用 xUnit 进行集成测试时,我使用的是内存 TestServer来自Microsoft.AspNetCore.TestHost 。所以,我需要在 TestFixture 中注册反向 channel 处理程序类如

testIdentityServer = new TestServer(identityServerBuilder);
My.Project.Startup.BackChannelHandler = testIdentityServer.CreateHandler();
testApiServer = new TestServer(apiServerBuilder);

虽然这工作正常,但我想覆盖 services.AddAuthentication()AddJwtBearer()在 DI 容器中,因此我可以注入(inject)身份验证中间件配置用于测试目的,而不是像处理任何其他依赖项一样使用公共(public)静态属性。当我尝试使用以下方法执行此操作时:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
       options.Authority = "xxxxx";
       options.RequireHttpsMetadata = false;
       options.Audience = "xxxxx";
       options.BackchannelHttpHandler = testIdentityServer.CreateHandler();
    });

TestFixture.cs我收到错误:带有“承载 token ”的身份验证方案已存在。

如何正确使用 ASP.NET Core 来执行此操作?

最佳答案

您遇到的行为是正常的,因为同一身份验证方案不能有 2 个处理程序。此处,AddJwtBearer 添加了身份验证方案 Bearer 的处理程序,该处理程序的值来自 JwtBearerDefaults.AuthenticationScheme

您传递给 AddJwtBearer 的 lambda 表达式被注册为命名选项配置,其注册名称是身份验证方案。

因此,您可以在测试项目中执行以下操作:

services.PostConfigure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options =>
{
    options.BackchannelHttpHandler = testIdentityServer.CreateHandler();
});

这样做不会更改已在容器中注册的身份验证方案,而只会修改与 JWT 处理程序关联的选项。

关于c# - 使用依赖注入(inject)替换 ASP.NET Core 中的 JWT Bearer Options,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51586562/

相关文章:

c# - 'C# in depth' 中的抽象类实例化

c# - 在 gridview 中的 asp.net 按钮中传递多个参数

php - Symfony 4 服务依赖注入(inject)——构造函数与方法

c# - 将 Flutter 前端与 Android 和 iOS 的 .NET Core 后端相结合

php - 什么是依赖注入(inject)容器?

java - 私有(private)不可访问字段是否需要是最终的?

unit-testing - 如何在集成测试中模拟 BLoC

tomcat - 在部署到 Tomcat 上进行集成测试之前修改 my.war/WEB-INF/中的配置文件

unit-testing - Glimmer 中的组件单元测试

C# MVC。如何将新项目用作单独区域?