首页 > 解决方案 > 如何在 ConfigureServices 方法中获取 IOptions 或将 IOptions 传递给扩展方法?

问题描述

我正在开发 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 传递给扩展方法?

标签: asp.net-web-apiasp.net-core.net-coreasp.net-core-2.0

解决方案


appsettings.json对于从to绑定数据Model,您可以按照以下步骤操作:

  1. Appsettings.json 内容

    {
    "Logging": {
     "IncludeScopes": false,
     "LogLevel": {
        "Default": "Warning"
           }
     },      
     "JWT": {
          "Issuer": "I",
          "Key": "K"
        }
     }
    
  2. 智威汤逊选项

    public class JwtOptions
    {
        public string Issuer { get; set; }
        public string Key { get; set; }
     }
    
  3. 启动.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();
    }
    
  4. 直接通过的另一种选择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();
    }
    
  5. 更改扩展方法。

    public static IServiceCollection AddJwtAuthentication(this IServiceCollection services, JwtOptions opt)
    

推荐阅读