asp.net-web-api - 如何在 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 传递给扩展方法?
解决方案
appsettings.json
对于从to绑定数据Model
,您可以按照以下步骤操作:
Appsettings.json 内容
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }, "JWT": { "Issuer": "I", "Key": "K" } }
智威汤逊选项
public class JwtOptions { public string Issuer { get; set; } public string Key { get; set; } }
启动.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(); }
直接通过的另一种选择
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(); }
更改扩展方法。
public static IServiceCollection AddJwtAuthentication(this IServiceCollection services, JwtOptions opt)
推荐阅读
- c# - C#如何取消进度条?
- jquery - Script1014:IE 11 用 jQuery.ajax 替换 fetch 的无效字符
- python - 使用 map plus 函数在列表中移动值
- paypal - 如何在 cs-cart 上获得一键式 PayPal 结帐按钮?
- c# - WPF - 用于 16 位深度灰度监视器的专用图像显示
- java - 如何在 Java 中将图像转换为形状?
- azure - 尝试在 Azure DevOps Server 2019 中创建团队项目集合时出错
- excel - 如何检查列表框的一行是否为空
- javascript - 将我的代码转换为使用 ie11 并收到错误
- struct - 可区分联合的结构属性