在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;
});
}
Run Code Online (Sandbox Code Playgroud)
这BackChannelHandler是的公共财产Startup.cs:
public static HttpMessageHandler BackChannelHandler { get; set; }
Run Code Online (Sandbox Code Playgroud)
我使用此属性的原因是,当我使用xUnit进行集成测试时,我正在使用TestServerfrom 中的内存Microsoft.AspNetCore.TestHost。所以,我需要在TestFixture类中注册反向通道处理程序
testIdentityServer = new TestServer(identityServerBuilder);
My.Project.Startup.BackChannelHandler = testIdentityServer.CreateHandler();
testApiServer = new TestServer(apiServerBuilder);
Run Code Online (Sandbox Code Playgroud)
尽管此方法运行良好,但我想覆盖DI容器中的services.AddAuthentication()或AddJwtBearer(),因此我可以出于测试目的注入身份验证中间件配置,而不是像使用其他依赖项那样使用公共静态属性。当我尝试使用以下方法进行操作时:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options …Run Code Online (Sandbox Code Playgroud) c# integration-testing dependency-injection identityserver4 asp.net-core-2.0