相关疑难解决方法(0)

Jwt Bearer 和依赖注入

我正在尝试配置我的 Jwt Bearer 颁发者密钥,但在生产中,我通常使用由KeyManager. 该KeyManager班是依赖注入配置,但在ConfigureServices方法我不能使用的(明显),但如果我不能用我不能找回我的钥匙。

我目前的解决方案是建立一个临时服务提供者并使用它,但我认为这不是最先进的(我需要创建两个单例副本,不是最好的)。

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
    ServiceProvider sp = services.BuildServiceProvider();
    IKeyManager keyManager = sp.GetService<KeyManager>();

    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = keyManager.GetSecurityKeyFromName("jwt").Result,

        ValidIssuer = "https://api.example.com",
        ValidateIssuer = true
    };

    options.Audience = "https://api.example.com";
    options.Authority = "https://api.example.com";

    options.SaveToken = true;
});
Run Code Online (Sandbox Code Playgroud)

c# jwt .net-core asp.net-core asp.net-core-webapi

3
推荐指数
2
解决办法
460
查看次数

标签 统计

.net-core ×1

asp.net-core ×1

asp.net-core-webapi ×1

c# ×1

jwt ×1