【问题标题】:Obtaining OAuth access token from identity server within Xamarin application从 Xamarin 应用程序中的身份服务器获取 OAuth 访问令牌
【发布时间】: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


【解决方案1】:

locahost 是模拟器本身,而不是托管模拟器的 PC,请使用 10.0.2.2 代替“访问”托管 PC。

另外请注意,您的开发机器上的地址 127.0.0.1 对应于模拟器自己的环回接口。如果您想访问在您的开发机器环回接口(也就是您机器上的 127.0.0.1)上运行的服务,您应该改用特殊地址 10.0.2.2。

设置 Android Emulator 网络:https://developer.android.com/studio/run/emulator-networking

【讨论】:

  • 感谢@SushiHangover 的帮助 - 我的客户也是:var client = new RestClient("http://10.0.2.2:&lt;local auth server port&gt;/connect/token");?我已经尝试过了,但出现以下错误:“无法从传输连接中读取数据:套接字已关闭。”
猜你喜欢
  • 2017-07-03
  • 2016-04-25
  • 1970-01-01
  • 2015-10-12
  • 2017-03-08
  • 2012-08-12
  • 1970-01-01
  • 2011-05-26
  • 2020-05-10
相关资源
最近更新 更多