JwtHandler (IOptions <JwtOptions>options внутри конструктора всегда становится пустым (со значениями по умолчанию) - PullRequest
1 голос
/ 24 сентября 2019
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.

1 Ответ

0 голосов
/ 24 сентября 2019

Вам не хватает строки типа

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

или чего-либо подобного, чтобы сообщить контейнеру внедрения зависимостей, как создается такой объект.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...