【发布时间】:2021-05-03 14:16:36
【问题描述】:
在我创建的 Xamarin 应用程序中,我尝试连接到在单独的解决方案中本地运行的 Web API。为了成功连接到此 API,我必须从身份服务器端点 (OAuth 2.0) 检索访问令牌。
我目前发现很难找到允许我检索此令牌的解决方案。
在现有的 .NET 项目中,我使用以下代码检索访问令牌,但在 Xamarin 应用程序中这不起作用,它到达第一行并在 5 分钟后返回说它已被取消:
try
{
var disco = await httpClient.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest
{
Address = clientCredentials.Path,
Policy =
{
RequireHttps = false
}
});
if (disco.IsError) Console.WriteLine(disco.Error);
var tokenResponse = await httpClient.RequestClientCredentialsTokenAsync(newClientCredentialsTokenRequest
{
Address = "https://<local-machine-ip>:<port-of-auth-localhost>/connect/token",
ClientId = clientCredentials.ClientId,
ClientSecret = clientCredentials.ClientSecret,
Scope = clientCredentials.Scope
});
if (tokenResponse.IsError) Console.WriteLine(tokenResponse.Error);
httpClient.SetBearerToken(tokenResponse.AccessToken);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
我得到的最接近的是通过此代码,但这会返回“错误:TrustFailure(身份验证失败,请参阅内部异常。)”:
var client = new RestClient("https://<local-machine-ip>:<port-of-auth-localhost>/connect/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=xxxx&client_secret=xxxxx&scope=xxxxx", ParameterType.RequestBody);
IRestResponse response = await client.ExecuteAsync(request);
目前我的想法已经用完了,有人知道解决方案吗?
请注意,我正在运行安卓模拟器 xamarin.android。上面显示的代码当前位于 xamarin.forms 解决方案的 ClassLibrary 中的一个类中
【问题讨论】:
-
此示例可能会有所帮助。你可以检查一下。 github.com/xamarin/Xamarin.Auth
-
谢谢@WendyZang-MSFT 我会检查样品。我最终通过使用 10.0.2.2 作为我的 IP 地址来获取访问令牌,但是,当我使用访问令牌调用我的 API 方法时,令牌作者无效。所以手指越过样本有帮助
标签: c# android xamarin xamarin.forms oauth-2.0