【问题标题】:How do you configure and inject JwtOptions in .net core 3.1 using TOptions? [closed]如何使用 TOptions 在 .net core 3.1 中配置和注入 JwtOptions? [关闭]
【发布时间】: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


    【解决方案1】:

    我有多种 IIS 身份验证方案,包括 Windows。上面的代码对我有用。

    【讨论】:

      猜你喜欢
      • 2020-08-20
      • 1970-01-01
      • 2020-08-22
      • 2020-07-11
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-04
      相关资源
      最近更新 更多