JWT Token .NET Core 身份服务器问题

JWT Token .NET Core Identity Server problem

我正在尝试使用 OAuth 客户端凭据流程保护 .NET 5.0 Web API。

我的客户正在从 IdentityServer4 实例请求令牌并将其提供给 API。 API 然后在我访问端点时返回 401 错误。我注意到以下 header: WWW-Authenticate header 包含 Bearer error=\"invalid_token\", error_description=\"The audience 'empty' is invalid\"

这表明我的 JWT 不包含受众参数。

我的 JWT 请求代码如下所示:

var tokenResponseType = await serverClient.RequestClientCredentialsTokenAsync(new                 
    ClientCredentialsTokenRequest
    {
        Address = discoveryDocument.TokenEndpoint,
        ClientId = "client_id",
        ClientSecret = "client_secret",
        Scope = "ApiOne",
    });

验证令牌的代码在这里:

services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", config =>
    {
        config.Authority = "https://localhost:44335/";
        config.Audience = "ApiOne";
        config.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidateIssuer = true,
            ValidateActor = true,
            ValidateLifetime = true,
            ValidateAudience = true,
            ValidateIssuerSigningKey = true
        };
        config.RequireHttpsMetadata = false;
     });

我认为 JWT 令牌应该包含受众参数。当我请求 JWT 时,我找不到设置受众参数的方法。

我已使用 jwt.io 调试我的 JWT 令牌,这确认未设置受众值。我希望根据请求设置范围会做到这一点。

缺少的是IdentityServer中的ApiScope和ApiResource配置。

首先你需要定义一个Api范围,比如:

new ApiScope(name: "ApiOneScope",
            displayName:"You can manage the ApiOne system.",
            userClaims: new List<string>{ });

Api范围是客户端可以请求访问的范围。

然后你需要一个Api资源定义如下:

new ApiResource()
{
    Name = "ApiOne",   
    DisplayName = "Orders API Service",
    Scopes = new List<string> { "ApiOneScope" },
};

Api资源是实际的 Api,当客户请求名为 ApiOneScope 的范围时,它最终出现在观众声明中。