gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 20:19:59 30 4
gpt4 key购买 nike

在 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com