首页 > 解决方案 > JwtHandler(IOptions构造函数中的选项总是为空(使用默认值)

问题描述

public class JwtHandler : IJwtHandler
{
    private readonly JwtOptions _options;
    private readonly SecurityKey _issuerSigningKey;
    ...

    // options inside constructor always gets empty (with default values).
    public JwtHandler(IOptions<JwtOptions> options) 
    {
        _options = options.Value;       
        _issuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.SecretKey));
    }
    ...
}

在启动类中我正在注册 Jwt

public void ConfigureServices(IServiceCollection services)
{
    ...
    Extensions.AddJwt(services, Configuration);    
}


public static class Extensions
{
    public static void AddJwt(IServiceCollection services, IConfiguration configuration)
    {
        var secretKey = configuration.GetValue<string>("jwt:secretKey");
        var expiryMinutes = configuration.GetValue<int>("jwt:expiryMinutes");
        var issuer = configuration.GetValue<string>("jwt:issuer");

        // options gets populated properly here
        var options = new JwtOptions { SecretKey = secretKey, ExpiryMinutes = expiryMinutes, Issuer = issuer };

        services.AddSingleton<IJwtHandler, JwtHandler>();
        services.AddAuthentication()
                .AddJwtBearer(cfg =>
                {
                    cfg.RequireHttpsMetadata = false;
                    cfg.SaveToken = true;
                    cfg.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateAudience = false,
                        ValidIssuer = options.Issuer,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(options.SecretKey))
                    };
                });
            }
        }
    }
}

内部 JwtHandler 构造函数选项始终为空,没有来自 AddJwt 方法的注入值。

标签: c#.netjwt

解决方案


你错过了像这样的一行

services.Configure<JwtOptions>(configuration.GetSection("jwt"));

或类似的东西来告诉您的依赖注入容器如何创建这样的对象。


推荐阅读