使用Xamarin中的Cognito联合身份 [英] Using Cognito Federated Identities from Xamarin

查看:73
本文介绍了使用Xamarin中的Cognito联合身份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我的问题>了解认知身份不够具体。我仍然不知道如何使用Xamarin应用程序中的联合身份。这是我正在尝试的方法,但实际上非常随机,因为我无法在其中找到该任务的任何示例代码。我尝试在 AddLogin 行上放置一个断点,即使断点两行确实被命中,它也永远不会被命中。对于我来说,这段代码中有太多的新技术对我来说不知道从哪里开始查找问题。 (我在下面的代码中删除了身份池ID,但是有一个真实的ID。)在这一点上,我只是想证明我可以唯一地标识/验证一个Amazon帐户,并且可以将其添加到我的用户池。但是我什至无法使代码完全执行或报告错误。

I guess my question, Understanding Cognito Identities, wasn't specific enough. I still can't figure out how to use a federated identity from a Xamarin app. Here's what I'm trying, but it's really quite random because I can't find any sample code for this task out there. I tried putting a breakpoint on the AddLogin line, and it never gets hit, even though breakpoint two lines up does get hit. There are too many new-to-me technologies in this code for me to know where to begin on tracking down the problem. (I x'd out the Identity pool ID in the code below, but a real one is there.) At this point I'm just trying to get evidence that I can uniquely identify/validate an Amazon account, and maybe add it to my user pool. But I can't even get the code to entirely execute or report an error.

Login().ContinueWith(t => { if (t.Exception != null) 
    Toast.MakeText(ApplicationContext, t.Exception.ToString(), ToastLength.Long).Show(); });

public async Task Login()
{
   CognitoAWSCredentials credentials = new CognitoAWSCredentials(
       "us-east-2:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", // Identity pool ID
       RegionEndpoint.USEast2 // Region
   );

   var client = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient(credentials);
   var request = new Amazon.SecurityToken.Model.GetFederationTokenRequest("myamazonid@gmail.com");
   var response = await client.GetFederationTokenAsync(request);
   credentials.AddLogin("www.amazon.com", response.Credentials.SessionToken);
}


推荐答案

搜索,但我想我已经知道了。与编写代码相比,设置服务和获取客户端ID不太困难(有据可查),因此此答案将集中在代码上。 Google特别棘手,因为对其OAuth实现进行了更改,从而阻止了某些形式的身份验证工作。为了使Google身份能够与Cognito一起使用,API必须是最新的。使用NuGet引用以下API版本或更高版本:

It took a good deal of searching, but I think I figured it out. Setting up the services and getting the client ID is not too hard (is well documented) compared to working out the code, so this answer will focus on the code. Google is particularly tricky because of changes made to their OAuth implementation that prevents some forms of authentication from working. In order for Google identities to work with Cognito, APIs need to be up-to-date. Use NuGet to reference the following API versions or later:


  • Xamarin.Auth 1.5.0.3

  • Xamarin.Android.Support.v4 25.4.0.2

  • Xamarin.Android.Support.CustomTabs 25.4.0.2

  • AWSSDK.CognitoIdentity 3.3.2.14

  • AWSSDK.Core 3.3.17.8

  • 验证2.4.15

  • Xamarin.Android.Support.Annotations 25.4。 0.2

  • Xamarin.Auth 1.5.0.3
  • Xamarin.Android.Support.v4 25.4.0.2
  • Xamarin.Android.Support.CustomTabs 25.4.0.2
  • AWSSDK.CognitoIdentity 3.3.2.14
  • AWSSDK.Core 3.3.17.8
  • Validation 2.4.15
  • Xamarin.Android.Support.Annotations 25.4.0.2

此代码在主要活动中:

protected override void OnCreate(Bundle savedInstanceState)
{
    // (etc)
    credentials = new CognitoAWSCredentials(
       "us-east-2:00000000-0000-0000-0000-000000000000", // Identity pool ID
       RegionEndpoint.USEast2 // Region
    );
    // (etc)
}

private void ShowMessage(string message)
{
  AlertDialog dlgAlert = new AlertDialog.Builder(this).Create();
  dlgAlert.SetMessage(message);
  dlgAlert.SetButton("Close", (s, args) => { dlgAlert.Dismiss(); });
  dlgAlert.Show();
}

public void Logout()
{
  credentials.Clear();
}

public void Login()
{
  if (!string.IsNullOrEmpty(credentials.GetCachedIdentityId()) || credentials.CurrentLoginProviders.Length > 0)
  {
     if (!bDidLogin)
        ShowMessage(string.Format("I still remember you're {0} ", credentials.GetIdentityId()));
     bDidLogin = true;
     return;
  }

  bDidLogin = true;
  auth = new Xamarin.Auth.OAuth2Authenticator(
     "my-google-client-id.apps.googleusercontent.com",
     string.Empty,
     "openid",
     new System.Uri("https://accounts.google.com/o/oauth2/v2/auth"),
     new System.Uri("com.mynamespace.myapp:/oauth2redirect"),
     new System.Uri("https://www.googleapis.com/oauth2/v4/token"),
     isUsingNativeUI: true);

  auth.Completed += Auth_Completed;
  StartActivity(auth.GetUI(this));
}

private void Auth_Completed(object sender, Xamarin.Auth.AuthenticatorCompletedEventArgs e)
{
  if (e.IsAuthenticated)
  {
     var http = new System.Net.Http.HttpClient();
     var idToken = e.Account.Properties["id_token"];

     credentials.AddLogin("accounts.google.com", idToken);
     AmazonCognitoIdentityClient cli = new AmazonCognitoIdentityClient(credentials, RegionEndpoint.USEast2);
     var req = new Amazon.CognitoIdentity.Model.GetIdRequest();
     req.Logins.Add("accounts.google.com", idToken);
     req.IdentityPoolId = "us-east-2:00000000-0000-0000-0000-000000000000";
     cli.GetIdAsync(req).ContinueWith((task) =>
     {
        if ((task.Status == TaskStatus.RanToCompletion) && (task.Result != null))
           ShowMessage(string.Format("Identity {0} retrieved", task.Result.IdentityId));
        else
           ShowMessage(task.Exception.InnerException!=null ? task.Exception.InnerException.Message : task.Exception.Message);
     });
  }
  else
     ShowMessage("Login cancelled");
}

然后在Google身份验证中还有另一个活动来处理来自重定向URL的回调过程:

Then there's another activity to handle the callback from the redirect URL in the Google authentication process:

[Activity(Label = "GoodleAuthInterceptor")]
[IntentFilter(actions: new[] { Intent.ActionView }, Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
  DataSchemes = new[] { "com.mynamespace.myapp" }, DataPaths = new[] { "/oauth2redirect" })]
public class GoodleAuthInterceptor : Activity
{
  protected override void OnCreate(Bundle savedInstanceState)
  {
     base.OnCreate(savedInstanceState);
     Android.Net.Uri uri_android = Intent.Data;
     Uri uri_netfx = new Uri(uri_android.ToString());
     MainActivity.auth?.OnPageLoading(uri_netfx);
     Finish();
  }
}

这篇关于使用Xamarin中的Cognito联合身份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆