IdentityServer4-从MVC以用户身份调用API

IdentityServer4-从MVC以用户身份调用API,identityserver4,Identityserver4,我正绞尽脑汁试图理解如何调用通过IdentityServer4保护的API 基本上,我有以下网站: -IdentityServer应用程序, -web API和 -客户端web应用程序 我的设置与IdentityServer示例一样 我定义了一个客户端,它代表我的客户端web应用程序,以及一个APIResource,它代表我的web Api 在我的客户端web应用程序中,我希望对WebAPI进行HTTP调用,但我希望显示为我是登录用户,因此我希望web Api可以使用“电子邮件”范围 我在Web

我正绞尽脑汁试图理解如何调用通过IdentityServer4保护的API

基本上,我有以下网站: -IdentityServer应用程序, -web API和 -客户端web应用程序

我的设置与IdentityServer示例一样

我定义了一个
客户端
,它代表我的客户端web应用程序,以及一个
APIResource
,它代表我的web Api

在我的客户端web应用程序中,我希望对WebAPI进行HTTP调用,但我希望显示为我是登录用户,因此我希望web Api可以使用“电子邮件”范围

我在Web应用程序中的做法是获取“访问令牌”,并将其传递给Web API:

var accessToken = await httpContextAccessor.HttpContext.Authentication.GetTokenAsync($"access_token");
            var client = new HttpClient();
            client.SetBearerToken(accessToken);
这允许我调用客户机,因此授权步骤正在工作,但是用户在Web Api上声明没有适当的作用域


我做错什么了吗?

访问令牌可以在IdentityServer4中包含索赔信息。必须在ApiResource定义中指定所需的声明

否则,您必须随请求一起发送JWT id_令牌

  new ApiResource(ApiResourceNames.SomeApiAccess, "Access to some api.", new List<string>(){
                    new IdentityResources.OpenId().Name,
                    new IdentityResources.Profile().Name,
                    new IdentityResources.Email().Name
                }),
new-ApiResource(ApiResourceNames.SomeApiAccess,“访问某些api.”,new-List(){
新标识资源.OpenId().Name,
新标识资源.Profile().Name,
新标识资源.Email().Name
}),

您可以在web api中添加作用域,如

app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
    Authority = "https://demo.identityserver.io",
    ApiName = "api1",

    AllowedScopes = { "api1.read", "api1.write" }
});
您是如何配置web api的?如果代码仍然不起作用,请发布代码