c# - Jwt Bearer 和依赖注入(inject)

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

我正在尝试配置我的 Jwt Bearer 颁发者 key ,但通常在生产中,我使用由 KeyManager 包装的 Azure Key Vault .KeyManager类在依赖注入(inject)中配置,但在 ConfigureServices方法我不能使用它(显然),但是如果我不能使用它,我就无法检索我的 key 。

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

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;
});

最佳答案

使用Options pattern并实现IConfigureNamedOptions<JwtBearerOptions> :

public class ConfigureJwtBearerOptions : IConfigureNamedOptions<JwtBearerOptions>
{
    private readonly IKeyManager _keyManager;

    public ConfigureJwtBearerOptions(IKeyManager keyManager)
    {
        _keyManager = keyManager;
    }

    public void Configure(JwtBearerOptions options)
    {
        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;
    }

    public void Configure(string name, JwtBearerOptions options)
    {
        Configure(options);
    }
}

在 Startup.cs 中:
services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer();

services.ConfigureOptions<ConfigureJwtBearerOptions>();

关于c# - Jwt Bearer 和依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61186836/

相关文章:

sql-server - 使用 EF Core 选择特定表列以列出异步

c# - 在 .NET 6 中使用 xsltc.exe 生成的程序集(XSLT 样式表)

c# - COM 互操作、C#、Visual Studio 2010 -> 嵌入互操作类型

c# - 仅在反序列化时设置

c# - 如何正确更改 WPF 中的 XBim 标准墙颜色

entity-framework - SQL 超时已过期。操作完成前超时时间已过或服务器未响应

c# - 无法在脚手架中向 DI 添加服务

c# - InternalEquals(object objA, object objB) 的实现在哪里

asp.net-core - 如何通过在 dapper 中执行 SQL 查询返回字符串

c# - 如何从 Controller 获取身份页面 URL?