代码之家  ›  专栏  ›  技术社区  ›  BlueMonkMN

使用Xamarin的Cognito联合身份

  •  0
  • BlueMonkMN  · 技术社区  · 7 年前

    Understanding Cognito Identities ,不够具体。我仍然不知道如何从Xamarin应用程序中使用联合身份。这是我正在尝试的,但它确实是随机的,因为我在那里找不到这个任务的任何示例代码。我试着在 AddLogin 行,它永远不会被击中,即使断点向上两行确实被击中。这段代码中有太多新技术,我不知道从哪里开始追踪问题。(我在下面的代码中用x标出了身份池ID,但那里有一个真实的身份池ID。)现在,我只是想找到证据,证明我可以唯一地识别/验证一个Amazon帐户,并可能将其添加到我的用户池中。但我甚至无法让代码完全执行或报告错误。

    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);
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   BlueMonkMN    7 年前

    我花了很多时间搜索,但我想我找到了答案。与编写代码相比,设置服务和获取客户ID并不太难(有很好的文档记录),因此这个答案将集中在代码上。由于对其OAuth实现所做的更改阻止了某些形式的身份验证工作,Google尤其棘手。为了让谷歌身份与Cognito协同工作,API需要是最新的。使用NuGet引用以下API版本或更高版本:

    • Xamarin。安卓支持v4 25.4.0.2
    • AWSSDK。核心3.3.17.8
    • 验证2.4.15

    此代码位于主活动中:

    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");
    }
    

    然后还有另一个活动来处理谷歌认证过程中重定向URL的回调:

    [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();
      }
    }