加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-web-api – 如何在ConfigureServices方法中获取IOptions

发布时间:2020-12-16 07:07:10 所属栏目:asp.Net 来源:网络整理
导读:我正在开发asp .net核心web api 2.1应用程序. 我在静态类中添加JWT身份验证服务作为扩展方法: public static class AuthenticationMiddleware { public static IServiceCollection AddJwtAuthentication(this IServiceCollection services,string issuer,st
我正在开发asp .net核心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 here

            services.AddJwtAuthentication(Configuration["Jwt:Issuer"],Configuration["Jwt:Key"]);

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);           
        }

现在,我需要使用IOptions模式从appsettings.json获取JWT身份验证数据

如何在ConfigureServices方法中获取IOptions以将issuer和key传递给extension方法?或者如何将IOptions传递给扩展方法?

解决方法

要将数据从appsettings.json绑定到Model,您可以按照以下步骤操作:

> Appsettings.json内容

{
"Logging": {
 "IncludeScopes": false,"LogLevel": {
    "Default": "Warning"
       }
 },"JWT": {
      "Issuer": "I","Key": "K"
    }
 }

> JWT选项

public class JwtOptions
{
    public string Issuer { get; set; }
    public string Key { get; set; }
 }

> Startup.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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读