身份验证选项中的依赖注入

时间:2021-07-15 02:23:50

标签: c# asp.net-core

我正在尝试将服务注入到 ValidationHandler 中,该 JwtSecurityTokenHandler 继承自 new 以验证 Jwt 的签名。不幸的是,要使用处理程序,我必须在 ConfigureServices 中使用带有 public class DynamicKeyJwtValidationHandler : JwtSecurityTokenHandler { private readonly IMemoryCache _cache; public DynamicKeyJwtValidationHandler(IMemoryCache cache) { _cache = cache; } } 的对象初始化,这意味着我无法使用将服务添加到依赖项容器所附带的注入服务。

services.AddTransient<DynamicKeyJwtValidationHandler>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
      .AddJwtBearer(opts => 
      {
          opts.SecurityTokenValidators.Clear();
          opts.SecurityTokenValidators.Add(new DynamicKeyJwtValidationHandler(???));
      });
IMemoryCache

那么我该怎么做才能仍然可以使用 my-promise.js

1 个答案:

答案 0 :(得分:1)

您可以创建 IConfigureNamedOptions<JwtBearerOptions> 的实现:

public class JwtOptionsConfigurer : IConfigureNamedOptions<JwtBearerOptions>
{
    private readonly DynamicKeyJwtValidationHandler _tokenValidator;

    public JwtOptionsConfigurer(DynamicKeyJwtValidationHandler tokenValidator)
    {
        _tokenValidator = tokenValidator;
    }

    public void Configure(string name, JwtBearerOptions options)
    {
        options.SecurityTokenValidators.Clear();
        options.SecurityTokenValidators.Add(_tokenValidator);
    }

    public void Configure(JwtBearerOptions options)
    {
        Configure(JwtBearerDefaults.AuthenticationScheme, options);
    }
}

然后像这样添加:

services.AddSingleton<IConfigureOptions<JwtBearerOptions>, JwtOptionsConfigurer>();
services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer();

我们仍然需要调用 .AddJwtBearer(),因为这会进行一些必要的注册等。

旁注(以防它对任何人有用):身份验证中间件每次需要时都会创建一个新的 JwtBearerOptions,因此上面的配置代码将多次运行。