微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

WebAuthenticator.AuthenticateAsync Facebook 登录未关闭

如何解决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

,

经过大量测试后,我让它工作了。我进行了一些更改,但我不确定哪个更改起作用了:

  1. 添加了 [ApiController] LoginController 类
  2. 添加了 cookie 处理:https://docs.microsoft.com/en-us/aspnet/core/security/gdpr?view=aspnetcore-5.0
  3. 在我模拟的 Android 上,我认为 chrome 版本存在问题,因此我将托管的 Android 中的 chrome 浏览器更新为最新版本
  4. 我将回调方案从 APPSCHEME 更改为 app

在我看来,第 4 点起到了作用,但其他点肯定是一个有趣的点。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?