从配置文件配置 JwtBearerOptions

myn*_*kow 5 .net-core asp.net-core

我正在尝试查找如何使用 Microsoft 预定义的配置节/键从配置文件中配置 jwt 承载及其JwtBearerOptions在 asp.net core 中的文档。微软文档中没有关于这是否可能的解释。我觉得这应该是可能的,因为 .net core 一代中的所有内容都在使用选项模式。

以下是如何使用相同技术配置 Kestrel 主机的示例。

在此输入图像描述

myn*_*kow 6

这不是对最初问题的真正答案。不过我对这个解决方案非常满意。

在深入研究 AspNetCore 源代码几个小时后,我发现 JwtBearerOptions作为命名选项添加到 DI 中。这意味着您无法在不编写代码的情况下从配置文件提供配置。然而,我找到了一个可接受的解决方案,适用于大多数情况。

我没有所有可用密钥的列表,此处的示例仅显示其中两个。您可以检查 JwtBearerOptions 的公共属性并将它们添加到 appsettings.json 中。它们将被框架挑选和使用。

请参阅下面的代码和注释,了解其工作原理的详细信息:

应用程序设置.json

{
    "Cronus": {
        "Api": {
            "JwtAuthentication": {
                "Authority": "https://example.com",
                "Audience": "https://example.com/resources"
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

启动.cs

public class Startup
{
    const string JwtSectionName = "Cronus:Api:JwtAuthentication";

    private readonly IConfiguration configuration;

    public Startup(IConfiguration configuration)
    {
        this.configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        // Gets the settings from a configuration section. Notice how we specify the name for the JwtBearerOptions to be JwtBearerDefaults.AuthenticationScheme.
        services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, configuration.GetSection(JwtSectionName));

        // OR

        // Gets the settings from a configuration. Notice how we specify the name for the JwtBearerOptions to be JwtBearerDefaults.AuthenticationScheme.
        services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, configuration);

        services.AddAuthentication(o =>
        {
            // AspNetCore uses the DefaultAuthenticateScheme as a name for the JwtBearerOptions. You can skip these settings because .AddJwtBearer() is doing exactly this.
            o.DefaultAuthenticateScheme = Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme;
            o.DefaultChallengeScheme = Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer();
    }
}
Run Code Online (Sandbox Code Playgroud)