为什么IdentityServer4 ApiResource无法与JwtBearerOption.Audience一起使用?

问题描述

我在IdentityServer中具有此配置:

public static IEnumerable<ApiResource> ApiResources =>
        new ApiResource[]
        {
            new ApiResource
            {
                Name = "MyApi"
            }
        };

以及ASP.NET Core Web API上的jwt配置:

 services.AddAuthentication("Bearer")
       .AddJwtBearer("Bearer",options =>
       {
           //identity server
           options.Authority = "https://localhost:5001";

           //access token recepient
           options.Audience = "https://localhost:5001/resources";

           options.TokenValidationParameters = new TokenValidationParameters
           {
               ValidateAudience = true,ValidateLifetime = true,};
       });

我期望Web API身份验证不会接受来自IdentityServer的令牌,因为Web API JwtBearerOption.Audience不等于“ MyApi”。但是在我的配置中,只有在将受众设置为“ https:// localhost:5001 / resources”的情况下,才对受众进行验证,并且如果将其设置为“ MyApi”,受众将无效。

IdentityServer4 documentation about related to my question.

解决方法

要使MyApi进入受众列表,您需要像在IdentityServer4(v4.0x)中那样定义ApiScope

有关更多详细信息,请参见此articles