c# - 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 方法的注入值。
解决方案
你错过了像这样的一行
services.Configure<JwtOptions>(configuration.GetSection("jwt"));
或类似的东西来告诉您的依赖注入容器如何创建这样的对象。
推荐阅读
- sql - 使用表中的索引规范化数据
- nginx - 如何允许从 nginx 中的子域访问域?
- css - 无法覆盖 chromecast 图标的 jwplayer css 样式
- java - 将从文件生成的值列表转换为数组(Java)
- azure-pipelines-release-pipeline - 如何在 TFS2018 Update 2 中配置 Partial Artifact 下载?
- r - 跨多个列使用 grepl 和 ifelse 的更简单方法
- c++ - 阶级友谊和继承问题
- php - 如何在 PHP 中使用一行代码显示数组和对象?
- opengl - 如何解决 GLFW_KEY_UNKNOWN
- java - JavaFX ListView IndexOutOfBoundsException