如何解决WebAuthenticator.AuthenticateAsync Facebook 登录未关闭
我正在尝试启动并运行它,但我不知道问题出在哪里。 我的启动:
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity<ApplicationUser,ApplicationRole>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI();
// .AddDefaultTokenProviders();
services.AddControllersWithViews();
//language
services.Configure<RequestLocalizationoptions>(options =>
{
options.DefaultRequestCulture = new RequestCulture("fr");
options.RequestCultureProviders = new List<IRequestCultureProvider>
{
new QueryStringRequestCultureProvider(),new CookieRequestCultureProvider()
};
});
services.AddAuthentication(o =>
{
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddFacebook(facebookOptions =>
{
facebookOptions.AppId = "XXXXX";
facebookOptions.AppSecret = "XXXXX";
facebookOptions.Savetokens = true;
});
services.AddControllersWithViews();
services.AddRazorPages();
services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});
}
我的登录控制器
[HttpGet]
[AllowAnonymous]
public async Task GetFacebook()
{
try
{
string scheme = "Facebook";
var auth = await Request.HttpContext.AuthenticateAsync(scheme);
if (!auth.Succeeded
|| auth?.Principal == null
|| !auth.Principal.Identities.Any(id => id.IsAuthenticated)
|| string.IsNullOrEmpty(auth.Properties.GetTokenValue("access_token")))
{
COMMON_FUNCTIONS.storeError(_context,"Not authenticated",MethodBase.GetCurrentMethod().ReflectedType.Name,auth.ToString());
// Not authenticated,challenge
await Request.HttpContext.ChallengeAsync(scheme);
}
else
{
var claims = auth.Principal.Identities.FirstOrDefault()?.Claims;
var email = string.Empty;
email = claims?.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value;
COMMON_FUNCTIONS.storeError(_context,"authenticated - mail",email);
// Get parameters to send back to the callback
var qs = new Dictionary<string,string>
{
{ "access_token",auth.Properties.GetTokenValue("access_token") },{ "refresh_token",auth.Properties.GetTokenValue("refresh_token") ?? string.Empty },{ "expires",(auth.Properties.ExpiresUtc?.ToUnixTimeSeconds() ?? -1).ToString() },{ "email",email }
};
// Build the result url
var url = "APPSCHEME" + "://#" + string.Join(
"&",qs.Where(kvp => !string.IsNullOrEmpty(kvp.Value) && kvp.Value != "-1")
.Select(kvp => $"{WebUtility.UrlEncode(kvp.Key)}={WebUtility.UrlEncode(kvp.Value)}"));
COMMON_FUNCTIONS.storeError(_context,"authenticated - url",url);
// Redirect to final url
Request.HttpContext.Response.Redirect(url);
}
}
catch (Exception ex)
{
COMMON_FUNCTIONS.storeError(_context,"Authenticate-ex",ex.ToString());
}
}
在我的 XAMARIN.FORMS 中:
private async void OnFacebookClicked(object sender,EventArgs e)
{
lblMessage.Text = "";
try
{
var authResult = await WebAuthenticator.AuthenticateAsync(new Uri(App.g_WebSite + "api/v1/Authenticate/GetFacebook"),new Uri("APPSCHEME://"));
var accesstoken = authResult?.Accesstoken;
}
catch (Exception ex) when (ex is TaskCanceledException || ex is OperationCanceledException)
{
lblMessage.Text = "User cancelled!";
}
catch (Exception ex)
{
string tt = ex.ToString();
lblMessage.Text = "Login Failed!";
}
}
当我点击 Loginbutton
时,我的函数 GetFacebook()
被调用。在服务器日志中,我可以看到如何在重定向调用之前生成令牌 APPSCHEME://#access_token=xxxxxxxxxxxxxxxxxxxxxxxxx
Request.HttpContext.Response.Redirect(url);
但是页面 facebook 页面没有关闭,XAMARIN.FORMS 更新中的代码到达
var accesstoken = authResult?.Accesstoken;
更新 我的 Android 中的代码
[Activity(Label = "GSAQ_Mobile",Icon = "@mipmap/icon",Theme = "@style/MainTheme",MainLauncher = true,ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this,savedInstanceState);
global::Xamarin.Forms.Forms.Init(this,savedInstanceState);
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode,string[] permissions,[GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode,permissions,grantResults);
base.OnRequestPermissionsResult(requestCode,grantResults);
}
//protected override void OnResume()
//{
// base.OnResume();
// Xamarin.Essentials.Platform.OnResume();
//}
}
[Activity(NoHistory = true,LaunchMode = LaunchMode.Singletop)]
[IntentFilter(new[] { Android.Content.Intent.ActionView },Categories = new[] { Android.Content.Intent.CategoryDefault,Android.Content.Intent.Categorybrowsable },DataScheme = "APPSCHEME")]
public class WebAuthenticationCallbackActivity : Xamarin.Essentials.WebAuthenticatorCallbackActivity
{
}
在我的网站上,facebooklogin
工作正常。
有人有想法吗?
解决方法
在您的 iOS App Delegate 中,您必须定义以下内容:
public override bool ContinueUserActivity(UIApplication application,NSUserActivity userActivity,UIApplicationRestorationHandler completionHandler)
{
if (Xamarin.Essentials.Platform.ContinueUserActivity(application,userActivity,completionHandler))
return true;
return base.ContinueUserActivity(application,completionHandler);
}
在安卓上:
const string CALLBACK_SCHEME = "myapp";
[Activity(NoHistory = true,LaunchMode = LaunchMode.SingleTop)]
[IntentFilter(new[] { Android.Content.Intent.ActionView },Categories = new[] { Android.Content.Intent.CategoryDefault,Android.Content.Intent.CategoryBrowsable },DataScheme = CALLBACK_SCHEME)]
public class WebAuthenticationCallbackActivity : Xamarin.Essentials.WebAuthenticatorCallbackActivity
{
}
https://docs.microsoft.com/en-us/xamarin/essentials/web-authenticator?tabs=ios#get-started
,经过大量测试后,我让它工作了。我进行了一些更改,但我不确定哪个更改起作用了:
- 添加了 [ApiController] LoginController 类
- 添加了 cookie 处理:https://docs.microsoft.com/en-us/aspnet/core/security/gdpr?view=aspnetcore-5.0
- 在我模拟的 Android 上,我认为 chrome 版本存在问题,因此我将托管的 Android 中的 chrome 浏览器更新为最新版本
- 我将回调方案从 APPSCHEME 更改为 app
在我看来,第 4 点起到了作用,但其他点肯定是一个有趣的点。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。