【问题标题】:IdentityServer4 - Call an API as a User from MVCIdentityServer4 - 从 MVC 以用户身份调用 API
【发布时间】:2017-12-09 08:51:34
【问题描述】:

我在试图了解如何调用受 IdentityServer4 保护的 API 时感到很困惑。

基本上,我有以下网站: - 一个 IdentityServer 应用程序, - 一个网络 API 和 - 客户端 Web 应用程序。

我的设置就像 IdentityServer 示例 here。

我定义了一个代表我的客户端 Web 应用程序的 Client 和一个代表我的 Web Api 的 APIResource。

在我的客户端 Web 应用程序中,我想对 WebAPI 进行 HTTP 调用,但我想看起来好像我是登录用户,所以我想让“电子邮件”范围对 Web Api 可用。

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

var accessToken = await httpContextAccessor.HttpContext.Authentication.GetTokenAsync($"access_token");
            var client = new HttpClient();
            client.SetBearerToken(accessToken);

这允许我调用客户端,因此授权步骤正在运行,但 Web Api 上的用户声明没有适当的范围。

我是不是做错了什么?

【问题讨论】:

    标签: identityserver4


    【解决方案1】:

    你可以在你的 web api 中添加范围

    app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
    {
        Authority = "https://demo.identityserver.io",
        ApiName = "api1",
    
        AllowedScopes = { "api1.read", "api1.write" }
    });
    

    你是如何配置你的 web api 的?还是不行就贴代码吧!

    【讨论】:

      【解决方案2】:

      access_token 可以包含 IdentityServer4 中的声明信息。必须在 ApiResource 定义中指定所需的声明。

      否则,您必须随请求一起发送 JWT id_token。

        new ApiResource(ApiResourceNames.SomeApiAccess, "Access to some api.", new List<string>(){
                          new IdentityResources.OpenId().Name,
                          new IdentityResources.Profile().Name,
                          new IdentityResources.Email().Name
                      }),
      

      【讨论】:

        猜你喜欢
        • 2019-03-26
        • 1970-01-01
        • 2013-09-08
        • 2020-12-20
        • 2020-06-27
        • 2018-12-28
        • 1970-01-01
        • 1970-01-01
        • 2015-01-02
        相关资源
        最近更新 更多