从配置文件配置JwtBearerOptions

我正在尝试找到一个文档,该文档如何使用microsoft预定义的confuration部分/关键字从配置文件中的asp.net核心中配置jwt承载及其JwtBearerOptions。 Mucrosoft文档中没有关于此是否可能的解释。我觉得应该有可能,因为.net核心代中的所有内容都在使用选项模式。

Here is an example如何使用相同的技术来配置Kestrel主机。

从配置文件配置JwtBearerOptions

hexar 回答:从配置文件配置JwtBearerOptions

这不是最初问题的真实答案。但是我对此解决方案感到非常满意。

在研究了AspNetCore源代码几个小时之后,我发现JwtBearerOptions是added to the DI as a named options。这意味着您不编写代码就无法从配置文件中提供配置。但是,我找到了可以在大多数情况下使用的可接受的解决方案。

我没有所有可用键的列表,这里的示例仅显示其中两个。您可以检查JwtBearerOptions的公共属性,并将它们添加到appsettings.json中。它们将由框架选择和使用。

有关以下内容的详细信息,请参见下面的代码及其注释:

appsettings.json

{
    "Cronus": {
        "Api": {
            "JwtAuthentication": {
                "Authority": "https://example.com","Audience": "https://example.com/resources"
            }
        }
    }
}

Startup.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();
    }
}
,
services.AddAuthentication(defaultScheme: JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(o => Configuration.Bind("JwtBearerOptions",o));

其中 应用程序settings.json

{
"JwtBearerOptions": {
    "Audience": "Your aud" 
  }
}
本文链接:https://www.f2er.com/3152316.html

大家都在问