Xamarin.Essentials.WebAuthenticator.AuthenticateAsync does not close popup window after success login to Facebook on Android

只愿长相守 提交于 2021-01-29 07:02:23

问题


I created a facebook login service in Xamarin. Everything is working fine in an UWP application. I also implemented the required options for Android (CallbackActivity with Intent). The Facebook login page properly appears. The login is succcess, and it redirects to the configured success page. The problem is that on Android after the success page appears, the login windows is not closing, and Xamarin code does not catch the access_token. Everything works fine properly in UWP. In the service I am calling method RequestFacebookToken for opening the login window and requesting access token.

Here is my facebook service:

public class FacebookService
{
    public const string CALLBACK_SCHEME = "https";

    private readonly HttpClient _httpClient;
    private const string _fbOauthEndpoint = "https://www.facebook.com/v7.0/dialog/oauth?";
    private const string CALLBACK_URI = "https://www.facebook.com/connect/login_success.html";
    private const string _fbAPI_URI = "https://graph.facebook.com/v2.8/";
    private string _fbAccessToken;
    private readonly string _AppId;

    public FacebookService(string AppID)
    {
        this._AppId = AppID;

        _httpClient = new HttpClient
        {
            BaseAddress = new Uri(_fbAPI_URI)
        };
        _httpClient.DefaultRequestHeaders
            .Accept
            .Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task RequestFacebookToken()
    {
        WebAuthenticatorResult res = null;
        try
        {
            string state = Convert.ToBase64String(Encoding.Unicode.GetBytes(DateTime.Now.Ticks.ToString()));
            //  if (Device.RuntimePlatform == Device.UWP)
            //  {
            res = await WebAuthenticator.AuthenticateAsync(new Uri($"{_fbOauthEndpoint}client_id={this._AppId}&display=popup&response_type=token&redirect_uri={CALLBACK_URI}&state={state}"), new Uri($"{CALLBACK_URI}"));
            /*      }
                    else
                    {
                        res = await WebAuthenticator.AuthenticateAsync(new Uri($"{_fbOauthEndpoint}client_id={this._AppId}&response_type=token&redirect_uri={CALLBACK_URI}&state={state}"), new Uri($"{CALLBACK_URI}"));
                    }*/
        }
        catch (Exception e)
        {

        }

        this._fbAccessToken = res?.AccessToken;
    }

    public async Task<FacebookProfile> GetUserFromFacebookAsync()
    {
        var result = await GetAsync<dynamic>("me", "fields=first_name,last_name,email,gender,picture.width(100).height(100)");
        if (result == null)
        {
            throw new Exception("User from this token not exist");
        }

        var account = new FacebookProfile()
        {
            Email = result.email,
            FirstName = result.first_name,
            LastName = result.last_name,
            Picture = result.picture.data.url,
            Gender = result.gender
        };

        return account;
    }

    private async Task<T> GetAsync<T>(string endpoint, string args = null)
    {
        var response = await _httpClient.GetAsync($"{endpoint}?access_token={this._fbAccessToken}&{args}");
        var result = await response.Content.ReadAsStringAsync();
        if (!response.IsSuccessStatusCode)
            return default(T);
        return JsonConvert.DeserializeObject<T>(result);
    }
}

Do you have any idea, what could be the issue why the login window is not closing after the login is success?

Thanks in advance!


回答1:


You could use Plugin.FacebookClient to login into the facebook.

 public async Task LoginAsync()
        {
        FacebookResponse<bool> response = await CrossFacebookClient.Current.LoginAsync(permisions);
            switch(response.Status)
        {
            case FacebookActionStatus.Completed:
                IsLoggedIn = true;
                OnLoadDataCommand.Execute(null);
                break;
            case FacebookActionStatus.Canceled:
            
                break;
            case FacebookActionStatus.Unauthorized:
                await App.Current.MainPage.DisplayAlert("Unauthorized", response.Message, "Ok");
                break;
            case FacebookActionStatus.Error:
                await App.Current.MainPage.DisplayAlert("Error", response.Message,"Ok");
                break;
        }

        }

You could download the source file from the link below:https://github.com/WendyZang/FacebookClientPlugin



来源:https://stackoverflow.com/questions/63213480/xamarin-essentials-webauthenticator-authenticateasync-does-not-close-popup-windo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!