[我在 Xamarin 中执行此操作,但我怀疑答案并不重要,因为 Xamarin 公开了与 native Java 或多或少相同的 API]
我正在尝试学习 OAuth 并实现授权流程(无隐式授权)。这涉及打开浏览器、进行身份验证,然后不进行 key 交换。你可能会认为这真的很容易。这是我下面的内容。
这样做的问题是,浏览器页面在用户登录后仍然存在。我如何让它消失?
public void Authenticate()
{
var sb = new StringBuilder();
sb.Append("https://accounts.google.com/o/oauth2/v2/auth");
sb.Append("?client_id=<MY ID HERE>");
sb.Append("&response_type=code");
sb.Append("&scope=openid%20email");
sb.Append("&redirect_uri=<MY PACKAGE NAME HERE>:/oauth2redirect");
var url = sb.ToString();
var uri = Android.Net.Uri.Parse("googlechrome://navigate?url=" + url);
try
{
System.Diagnostics.Debug.WriteLine(uri.ToString());
Intent i = new Intent(Intent.ActionView, uri);
i.AddFlags(ActivityFlags.NewTask);
i.AddFlags(ActivityFlags.SingleTop);
i.AddFlags(ActivityFlags.ClearTop);
i.AddFlags(ActivityFlags.NoHistory);
Android.App.Application.Context.StartActivity(i);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
相关:
Is there any way in Android to force open a link to open in Chrome?
Redirect page doesn't automatically close after successful OAuth authorization
最佳答案
您使用的是 Chrome
,而不是 Chrome 自定义标签
:
示例:
var sb = new StringBuilder()
.Append("https://accounts.google.com/o/oauth2/v2/auth")
.Append($"?client_id={clientID}")
.Append("&response_type=code")
.Append("&scope=https://www.googleapis.com/auth/drive")
.Append($"&redirect_uri={PackageName}:/SushiRedirect");
var builder = new CustomTabsIntent.Builder(GetSession())
.SetToolbarColor(Color.ParseColor(TOOLBAR_COLOR)).SetShowTitle(true)
.SetStartAnimations(this, Resource.Animation.slide_in_right, Resource.Animation.slide_out_left)
.SetExitAnimations(this, Resource.Animation.slide_in_left, Resource.Animation.slide_out_right)
.SetCloseButtonIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.ic_arrow_back));
var customTabsIntent = builder.Build();
CustomTabsHelper.AddKeepAliveExtra(this, customTabsIntent.Intent);
customTabsIntent.LaunchUrl(this, Uri.Parse(sb.ToString()));
并向 LaunchMode.SingleTask
Activity 添加 Intent 过滤器以捕获重定向并“关闭”共享选项卡
。您的授权代码将位于 Intent 数据中 (Intent?.Data?.ToString()
):
[Activity(Label = "CustomTabsClient.Application", MainLauncher = true, Icon = "@drawable/ic_launcher", LaunchMode = LaunchMode.SingleTask)]
[IntentFilter(
new[] { Intent.ActionView },
Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
DataScheme = "com.sushhangover.customtabsclient.example", DataPath = "/SushiRedirect")]
我有 Google 的 Java Chrome 共享选项卡演示的移植以及他们的共享库代码的 nuget 包,以帮助实现您自己的共享选项卡设置:
SushiHangover.Android.Support.CustomTabs.Shared
https://github.com/sushihangover/SushiHangover.GoogleChrome.CustomTabs.Shared
关于android - 如何在 Android 上的 Chrome 中打开然后自动关闭 OAuth 页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46223771/