Xamarin.Forms Google API使用身份提供者对用户进行身份验证

Xamarin.Forms Google API使用身份提供者对用户进行身份验证

问题描述:

我仍然习惯于Xamarin.Forms,并且我处于非常基础的水平.我针对该问题浏览了许多文章,但最终无法解决.所以...

I am still getting used to Xamarin.Forms and I am on very basic level. I went through many articles for my issue, but to the end couldn't resolve it. So...

当前,我正在尝试在使用Droid和iOS(无WP)的Xamarin.Forms应用程序中添加Google身份验证. 到目前为止,我正在此处进行操作.我正在使用Xamarin.Auth对Google进行身份验证.

Currently I am trying to add Google authentication inside my Xamarin.Forms application, which use Droid and iOS (no WP). So far I am following guide from here. I am using Xamarin.Auth to authenticate to Google.

这是我源代码中的一部分.

Here is some part from my source code.



    private async void GoogleSheetsButton_Tapped()
    {
        string clientId = null;
        string redirectUri = null;

        if (Device.RuntimePlatform == Device.iOS)
        {
            clientId = Constants.iOSClientId;
            redirectUri = Constants.iOSRedirectUrl;
        }
        else if (Device.RuntimePlatform == Device.Android)
        {
            clientId = Constants.AndroidClientId;
            redirectUri = Constants.AndroidRedirectUrl;
        }

        var authenticator = new OAuth2Authenticator(
            clientId,
            null,
            Constants.Scope,
            new Uri(Constants.AuthorizeUrl),
            new Uri(redirectUri),
            new Uri(Constants.AccessTokenUrl),
            null,
            true);

        authenticator.Completed += OnAuthCompleted;
        authenticator.Error += OnAuthError;

        AuthenticationState.Authenticator = authenticator;

        var presenter = new Xamarin.Auth.Presenters.OAuthLoginPresenter();
        presenter.Login(authenticator);
    }

问题出在我的方法完成工作之后.所以在我的最后一行之后:

The problem is coming after my method complete it's work. So after my last line:



    presenter.Login(authenticator);

一切看起来都很好,并且正在调试我正在跟踪编译器退出方法而没有任何错误,但是随后我收到异常,您可以看到 没有兼容的代码正在运行 ".

everything looks alright and debugging I am following that compiler goes out of method without any errors, but then I receive exception, which you can see here. It's "No compatible code running".

以下是有关我的源代码的更多信息:

Here some more information regarding my source code:

  • 用于客户端ID和URL的常量"类的来源


    public static class Constants
    {
        public static string AppName = "....";

        // OAuth
        // For Google login, configure at https://console.developers.google.com/
        public static string iOSClientId = "6.....apps.googleusercontent.com";
        public static string AndroidClientId = "6.....apps.googleusercontent.com";

        // These values do not need changing
        public static string Scope = "https://www.googleapis.com/auth/userinfo.email";
        public static string AuthorizeUrl = "https://accounts.google.com/o/oauth2/auth";
        public static string AccessTokenUrl = "https://www.googleapis.com/oauth2/v4/token";
        public static string UserInfoUrl = "https://www.googleapis.com/oauth2/v2/userinfo";

        // Set these to reversed iOS/Android client ids, with :/oauth2redirect appended
        public static string iOSRedirectUrl = "com.googleusercontent.apps.6......h:/oauth2redirect";
        public static string AndroidRedirectUrl = "com.googleusercontent.apps.6......l:/oauth2redirect";
    }

  • 关于身份验证完成/错误的已实现方法的来源,实际上由于我的错误我仍然无法击中
 

    async void OnAuthCompleted(object sender, AuthenticatorCompletedEventArgs e)
    {
        var authenticator = sender as OAuth2Authenticator;
        if (authenticator != null)
        {
            authenticator.Completed -= OnAuthCompleted;
            authenticator.Error -= OnAuthError;
        }

        GoogleLoginUser user = null;
        if (e.IsAuthenticated)
        {
            var request = new OAuth2Request("GET", new Uri(Constants.UserInfoUrl), null, e.Account);
            var response = await request.GetResponseAsync();
            if (response != null)
            {
                string userJson = await response.GetResponseTextAsync();
                user = JsonConvert.DeserializeObject(userJson);
            }

            if (_account != null)
            {
                _store.Delete(_account, Constants.AppName);
            }

            await _store.SaveAsync(_account = e.Account, Constants.AppName);
            await DisplayAlert("Email address", user.Email, "OK");
        }
    }

    void OnAuthError(object sender, AuthenticatorErrorEventArgs e)
    {
        var authenticator = sender as OAuth2Authenticator;
        if (authenticator != null)
        {
            authenticator.Completed -= OnAuthCompleted;
            authenticator.Error -= OnAuthError;
        }

        var message = e.Message;
    }

  • 我在其中添加的Android MainActivity的来源


    public class MainActivity : FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            Forms.Init(this, bundle);
            global::Xamarin.Auth.Presenters.XamarinAndroid.AuthenticationConfiguration.Init(this, bundle);

            MobileBarcodeScanner.Initialize(Application);

            LoadApplication(new App());
        }
    }

  • UrlSchemeInterceptorActivity的来源


    [Activity(Label = "CustomUrlSchemeInterceptorActivity", NoHistory = true, LaunchMode = LaunchMode.SingleTop)]
    [IntentFilter(new[] { Intent.ActionView }, Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable }, DataSchemes = new[] { "com.googleusercontent.apps.6......l" }, DataPath = "/oauth2redirect")]
    public class CustomUrlSchemeInterceptorActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            var uri = new Uri(Intent.Data.ToString());

            AuthenticationState.Authenticator.OnPageLoading(uri);

            Finish();
        }
    }

这是我深入研究的主要文章=> 链接1 链接2 链接3 ,但仍然无法解决问题.

Here are the main articles I went through deeply => Link 1, Link 2 and Link 3, but still couldn't resolve the issue.

我不确定错误是从哪里来的,或者我可以继续调试它来解决问题.

I am not sure where the error comes from, or can I can I continue debugging it to resolve issue.

预先感谢

解决方案

  1. 在Android项目属性内将android编译器更改为android 7.0. 截屏
  2. 确保在Android Manifest中,您的目标是SDK版本. 截屏
  3. 将所有"Xamarin.Android.*" nuget软件包更新为最低版本25.4.0.1.目前最有可能达到23.3.0.我发现有关更新它的依赖性的问题,因此我进行了手动上传.我去手动下载了每个软件包,并将其移到packages文件夹.然后,我创建了自己的软件包源,并为我的文件夹软件包提供了路径,并用它来安装已经下载的NuGet软件包. 截屏
  4. 之后我的问题解决了.
  1. Change android compiler to Android 7.0 inside Android project properties. Screenshot
  2. Make sure that inside Android Manifest your target is SDK Version. Screenshot
  3. Update all "Xamarin.Android.*" nuget packages to minimum version 25.4.0.1. Most probably they're currently to 23.3.0. I found problems with dependencies on updating it, so I make manual upload. I went and download manually each package and move it to packages folder. Then I created my own package source and give for path my folder packages and I used it to install already downloaded NuGet packages. Screenshot
  4. After that my issue was solved.

请将您的Android SDK更新为API 24或更高版本,并将其设置为项目的编译版本.并将更新的自定义选项卡及其依存关系引用的程序集更新到v25.x.x.而已.您应该能够使其正常工作.

Please update your Android SDK to API 24 or higher and set it as the compile version for your project. And update your referred assemblies for the custom tabs and its dependencies to v25.x.x. Thats it. You should be able to get it working.

维杰.