【发布时间】:2020-06-28 20:40:46
【问题描述】:
在 .NetCore 3.0 和 3.1 中,他们删除了将服务注入 Startup 类的功能,除非您有意构建第二个服务提供者并复制您的单例服务(严重)。几乎所有配置 Jwt Bearer 令牌以进行身份验证的示例都显示如下:
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
当您在静态环境中工作时,这很好,但我在这些设置是动态的并且从发出配置设置的 Web 服务中提取的环境中工作。
我在这里找到了一个非常好的使用 TOptions 的演练:
https://andrewlock.net/avoiding-startup-service-injection-in-asp-net-core-3/
我正在尝试使此选项模式与 JwtOptions 一起使用。
我已将此添加到我的 ConfigureServices:
services.AddSingleton<IMyService, MyServiceImplementation>();
services.ConfigureOptions<ConfigureJwtBearerOptions>();
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer();
这是我的新选项类:
public class ConfigureJwtBearerOptions : IConfigureNamedOptions<JwtBearerOptions>
{
private IMyService myService;
public ConfigureJwtBearerOptions(IMyService svc)
{
this.myService = svc;
}
public void Configure(string name, JwtBearerOptions options)
{
// Only configure the options if this is the correct instance
if (name == JwtBearerDefaults.AuthenticationScheme)
{
//use your service to get your settings
options.Authority = myService.GetAuthority();
options.Audience = myService.GetAudience();
}
}
// This won't be called, but is required for the IConfigureNamedOptions interface
public void Configure(JwtBearerOptions options) => Configure(Options.DefaultName, options);
}
有没有我遗漏的概念?由于我现在正在注入选项,是否需要一起删除 .AddJwtBearer() ?
谢谢!
【问题讨论】:
标签: c# .net-core jwt-auth .net-core-3.1