【问题标题】:401 response when using Xamarin and IdentityModel to WebAPI secured by IdentityServer 3使用 Xamarin 和 IdentityModel 到由 IdentityServer 3 保护的 WebAPI 时出现 401 响应
【发布时间】:2016-11-28 10:37:02
【问题描述】:

我遇到了与this 相同的问题,但他们的解决方案对我不起作用。

我正在调用一个 WebAPI 方法 (.Net 4.5.2),该项目引用了 IdentityModel 1.13.1,它使用 IdentityServer 3 和启动类中的以下代码进行保护 -

        JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();

        app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
        {
            Authority = "https://localhost:44305/core/",
            RequiredScopes = new[] { "read", "write" },

            // client credentials for the introspection endpoint
            ClientId = "clientcredentials.client",
            ClientSecret = "secret"
        });

IdentityServer 启动中的客户端配置包括以下客户端定义 -

new Client
            {
                ClientName = "Mobile Api Client",
                Enabled = true,
                ClientId = "clientcredentials.client",
                Flow = Flows.ClientCredentials,

                ClientSecrets = new List<Secret>
                    {
                        new Secret("secret".Sha256()),
                        new Secret
                        {
                            Value = "[valid thumbprint]",
                            Type = "X509Thumbprint",
                            Description = "Client Certificate"
                        },
                    },

                AllowedScopes = new List<string>
                    {
                        "read",
                        "write"
                    },

                Claims = new List<Claim>
                    {
                        new Claim("location", "datacenter")
                    }
            }

在 Xamarin 客户端(也使用 IdentityModel 1.13.1)...

            var token = IdentityServerClient.RequestClientToken();  // this returns a valid bearer token
            TokenResultLabel.Text = token.Raw;

            HttpClient apiClient = new HttpClient();

            apiClient.SetBearerToken(token.AccessToken);
            var result = await apiClient.GetStringAsync("[valid api URL]");
            ApiResultLabel.Text = result;

我已经尝试过 IdentityModel 2.0(最新兼容版本)、1.13.1(引用问题中提到的版本和 1.9.2(IdentityServer 3 示例中的版本)

任何帮助将不胜感激

【问题讨论】:

  • 您需要在您的 API 中开启登录功能 - identityserver.github.io/Documentation/docsv2/consuming/…
  • 感谢您的建议。我已经尝试过了,但是没有生成日志文件。最后我放弃并从头开始重新创建了 WebAPI 项目,但这次我使用了空白的 Web 项目模板并仅添加了 WebAPI 引用,之前我使用了带有 WebAPI 引用的 MVC 模板。我不知道有什么区别,但它正在工作。再次感谢

标签: asp.net-web-api xamarin identityserver3


【解决方案1】:

虽然配置允许客户端同时请求readwrite 范围,但您是否在请求访问令牌时明确指定希望获得包含这两个范围的访问令牌?这应该发生在您的 IdentityServerClient.RequestClientToken 方法中。

允许客户端请求范围并不意味着这些范围将自动包含在 IdentityServer 返回的访问令牌中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-13
    • 2016-12-07
    • 2021-03-01
    • 2021-11-23
    • 2021-07-19
    • 2021-12-09
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多