身份服务器本身内部 API 控制器的访问令牌

Access token for API controller inside Identity server itself

我已经创建了一个身份服务器 4 项目和一个 mvc 客户端项目。身份验证流程按预期工作。我在与身份服务器相同的项目中添加了一个 API 控制器,我想从 mvc client.Essentially 中访问这个 api 资源,我需要身份服务器中间件和令牌验证中间件服务器项目。

如果您还没有,请将这些 Nuget 包添加到您已经建立的 IdentityServer app/site:

IdentityServer4.AccessTokenValidation
Microsoft.AspNetCore.Mvc

将另一个 Api 资源添加到您的资源列表:

public static IEnumerable<ApiResource> GetApiResources()
{
    return new List<ApiResource>
    {
        new ApiResource("api1", "My API"), 
        new ApiResource("api2", "IdentityServer API")
    };
}

更新您的客户端配置以允许 api2:

public static IEnumerable<Client> GetClients()
{
    return new List<Client>
    {
        new Client
        {
            ClientId = "mvc",

            ... omitted

            AllowedScopes = new List<string>
            {
                IdentityServerConstants.StandardScopes.OpenId,
                IdentityServerConstants.StandardScopes.Profile,
                "api2"
            }
        }
    };
}

在启动的IdentityServer的Configure方法中添加:

app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
    Authority = "http://localhost:5000",
    RequireHttpsMetadata = false,

    ApiName = "api2"
});