将Xamarin和IdentityModel用于由IdentityServer 3保护的WebAPI时的响应401

时间:2016-11-28 10:37:02

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

我遇到了与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样本中的版本)

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

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

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