问题描述
在我创建的 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);
}
我得到的最接近的是通过此代码,但这会返回“错误:信任失败(身份验证失败,请参阅内部异常。)”:
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 android 模拟器。上面显示的代码当前位于 xamarin.forms 解决方案的 ClassLibrary 中的一个类中
解决方法
locahost
是模拟器本身,而不是托管模拟器的 PC,请改用 10.0.2.2 来“访问”托管 PC。
还要注意,你的开发机器上的地址127.0.0.1对应的是模拟器自己的loopback接口。如果您想访问在您的开发机器环回接口上运行的服务(也就是您机器上的 127.0.0.1),您应该使用特殊地址 10.0.2.2。
设置 Android 模拟器网络:https://developer.android.com/studio/run/emulator-networking