5

我已经实现了 Xamarin.Auth示例代码,以便在 Android 上使用 google 的身份提供者进行身份验证。我已使用设备的 Chrome 浏览器成功导航到 Google 登录页面,我可以在其中输入我的凭据。我成功地向 Google 授权,但 Chrome 自定义选项卡在重定向回我的应用程序时没有关闭,也就是说,我只能在 chrome 浏览器中查看 google 搜索。如果我关闭浏览器,我可以再次看到我的应用程序,并显示从谷歌身份提供者返回的用户详细信息。

为什么 Chrome 的自定义选项卡不会在来自 Google 身份提供商的重定向时关闭,如何使用 Xamarin Forms 和 Xamarin.Auth 关闭它?

4

1 回答 1

9

如果将此代码添加到捕获 Android 中 Xamarin.Auth 示例中的重定向 (CustomUrlSchemeInterceptorActivity) 的类中的 OnCreate 方法的末尾,则可以返回到您的应用程序

new Task(() =>{
         StartActivity(new Intent(Application.Context,typeof(MainActivity)));
     }).Start();

其中 MainActivity 是您在 Android 中的主要 Activity 类的名称。更准确地说,这里是一个完整的类,您可以为拦截的每个重定向继承它

public class UrlSchemeInterceptor : Activity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        try
        {
            base.OnCreate(savedInstanceState);

            // Convert Android.Net.Url to Uri
            var uri = new Uri(Intent.Data.ToString());
            new Task(() =>
            {
                var intent = new Intent(ApplicationContext, typeof(MainActivity));
                intent.AddFlags(ActivityFlags.IncludeStoppedPackages);
                intent.AddFlags(ActivityFlags.ReorderToFront);
                StartActivity(intent);

            }).Start();

            // Load redirectUrl page
            AuthenticationState.Authenticator.OnPageLoading(uri);
            Finish();

        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }

}

public class AuthenticationState
{
    public static WebAuthenticator Authenticator;
   /*This static field is used to store the object
   from OAuth1Authenticator or OAuth2Authenticator
   upon initialization in the UI (Xamarin forms or Android or iOS).
   For example:
   var authenticatorObject = new  OAuth2Authenticator (YOUR PARAMETERS);
   AuthenticationState.Authenticator = (WebAuthenticator)authenticatorObject;
    var presenter = new OAuthLoginPresenter();
        presenter.Login(authenticatorObject);
    */
}

例如在谷歌案例中

[Activity(Label = "YOURLABEL", NoHistory = true, LaunchMode = LaunchMode.SingleTop)]
[IntentFilter( new[] { Intent.ActionView }, Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
    DataSchemes = new[]
    {
        "com.googleusercontent.apps.",// YOUR GOOGLE ID INVERTED
    },
    DataPaths = new[]
    {
        "/oauth2redirect",
    })]
public class GoogleUrlSchemeInterceptorActivity : UrlSchemeInterceptor { }
于 2017-09-08T19:14:34.690 回答