【发布时间】:2019-02-14 22:14:27
【问题描述】:
我正在开发 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 传递给扩展方法?
【问题讨论】:
-
这里为什么需要IOptions?
-
Docs (docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/…) 说“不要在 Startup.ConfigureServices 中使用 IOptions
或 IOptionsMonitor 。由于服务注册的顺序,可能存在不一致的选项状态。”。
标签: asp.net-web-api asp.net-core .net-core asp.net-core-2.0