Asp.net-Web-Api

如何在 ConfigureServices 方法中獲取 IOptions 或將 IOptions 傳遞給擴展方法?

  • May 7, 2020

我正在開發 asp .net core web api 2.1 應用程序。

我在靜態類中添加 JWT 身份驗證服務作為擴展方法:

public static class AuthenticationMiddleware
{
   public static IServiceCollection AddJwtAuthentication(this IServiceCollection services, string issuer, string key)
   {
       services
           .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
           .AddJwtBearer(options =>
           {
               options.TokenValidationParameters = new TokenValidationParameters
               {
                   // validate the server that created that token
                   ValidateIssuer = true,
                   // ensure that the recipient of the token is authorized to receive it
                   ValidateAudience = true,
                   // check that the token is not expired and that the signing key of the issuer is valid
                   ValidateLifetime = true,
                   // verify that the key used to sign the incoming token is part of a list of trusted keys
                   ValidateIssuerSigningKey = true,
                   ValidIssuer = issuer,
                   ValidAudience = issuer,
                   IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key))
               };
           });

       return services;
   }
}

我在 Startup 類的 ConfigureServices 方法中使用它,如下所示:

public void ConfigureServices(IServiceCollection services)
{
   // adding some services omitted here

   services.AddJwtAuthentication(Configuration["Jwt:Issuer"], Configuration["Jwt:Key"]);

   services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

現在,我需要使用 IOptions 模式從 appsettings.json 獲取 JWT 身份驗證數據

如何在 ConfigureServices 方法中獲取 IOptions 以將頒發者和密鑰傳遞給擴展方法?或者如何將 IOptions 傳遞給擴展方法?

appsettings.json對於從to綁定數據Model,您可以按照以下步驟操作:

  1. Appsettings.json 內容
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
   "Default": "Warning"
      }
},      
"JWT": {
     "Issuer": "I",
     "Key": "K"
   }
}
  1. 智威湯遜選項
public class JwtOptions
{
   public string Issuer { get; set; }
   public string Key { get; set; }
}
  1. 啟動.cs
public void ConfigureServices(IServiceCollection services)
{
   services.Configure<JwtOptions>(Configuration.GetSection("JWT"));
   var serviceProvider = services.BuildServiceProvider();
   var opt = serviceProvider.GetRequiredService<IOptions<JwtOptions>>().Value;
   services.AddJwtAuthentication(opt.Issuer, opt.Key);
   services.AddMvc();
}
  1. 直接通過的另一種選擇JwtOptions
public void ConfigureServices(IServiceCollection services)
{
   services.Configure<JwtOptions>(Configuration.GetSection("JWT"));
   var serviceProvider = services.BuildServiceProvider();
   var opt = serviceProvider.GetRequiredService<IOptions<JwtOptions>>().Value;
   services.AddJwtAuthentication(opt);

   services.AddMvc();
}
  1. 更改擴展方法。
public static IServiceCollection AddJwtAuthentication(this IServiceCollection services, JwtOptions opt)

引用自:https://stackoverflow.com/questions/52258443