Xamarin Auth - Facebook& GOOGLEPLUS

时间:2017-08-30 13:42:37

标签: android oauth-2.0 xamarin.forms xamarin.auth

我目前正在开始与Xamarin.Auth合作,我面临着两个问题,因为我从一天半开始就陷入困境......

我有这段代码:

public class OAuth
{
    private Account account;
    private AccountStore store;

    // These values do not need changing
    public string Scope;
    public string AuthorizeUrl;
    public string AccessTokenUrl;
    public string UserInfoUrl;

    string clientId;
    string redirectUri;

    private Func<JObject, User> OAuthParser;

    private Action<User> OnCompleted;
    private Action<string> OnError;

    public OAuth()
    {
        account = null;
        store = null;

        Scope = "";
        AuthorizeUrl = "";
        AccessTokenUrl = "";
        UserInfoUrl = "";

        clientId = "";
        redirectUri = "";
    }

    public OAuth Facebook()
    {
        // These values do not need changing
        Scope = "public_profile";
        AuthorizeUrl = "https://m.facebook.com/dialog/oauth/";
        AccessTokenUrl = "";
        UserInfoUrl = "";

        switch (Device.RuntimePlatform)
        {
            case Device.iOS:
                clientId = "<insert IOS client ID here>";
                redirectUri = "<insert IOS redirect URL here>:/oauth2redirect";
                break;

            case Device.Android:
                clientId = "206316176526191";
                redirectUri = "http://www.facebook.com/connect/login_success.html";
                break;
        }

        OAuthParser = ParseFacebookResponse;

        return this;
    }

    public OAuth GooglePlus()
    {
        // These values do not need changing
        Scope = "https://www.googleapis.com/auth/userinfo.email";
        AuthorizeUrl = "https://accounts.google.com/o/oauth2/auth";
        AccessTokenUrl = "https://www.googleapis.com/oauth2/v4/token";
        UserInfoUrl = "https://www.googleapis.com/oauth2/v2/userinfo";

        switch (Device.RuntimePlatform)
        {
            case Device.iOS:
                clientId = "<insert IOS client ID here>";
                redirectUri = "<insert IOS redirect URL here>:/oauth2redirect";
                break;

            case Device.Android:
                clientId = "548539660999-muighch5brcrbae8r53js0ggdad5jt45.apps.googleusercontent.com";
                redirectUri = "com.googleusercontent.apps.548539660999-muighch5brcrbae8r53js0ggdad5jt45:/oauth2redirect";
                break;
        }

        OAuthParser = ParseGooglePlusResponse;

        return this;
    }

    public OAuth2Authenticator Authenticator(Action<User> onCompleted, Action<string> onError)
    {
        OAuth2Authenticator authenticator = new OAuth2Authenticator(
            clientId,
            null,
            Scope,
            new Uri(AuthorizeUrl),
            new Uri(redirectUri),
            new Uri(AccessTokenUrl),
            null,
            false);

    authenticator.Completed += OnAuthCompleted;
    authenticator.Error += OnAuthError;

        OnCompleted = onCompleted;
        OnError = onError;

        return authenticator;
    }

    private async void OnAuthCompleted(object sender, AuthenticatorCompletedEventArgs e)
    {
    OAuth2Authenticator OAuth2Authenticator = sender as OAuth2Authenticator;
    if (OAuth2Authenticator != null)
    {
        OAuth2Authenticator.Completed -= OnAuthCompleted;
        OAuth2Authenticator.Error -= OnAuthError;
    }

    //User user = null;
    if (e.IsAuthenticated)
    {
        // If the user is authenticated, request their basic user data from Google
        // UserInfoUrl = https://www.googleapis.com/oauth2/v2/userinfo
        var request = new OAuth2Request("GET", new Uri(UserInfoUrl), null, e.Account);
        var response = await request.GetResponseAsync();
        if (response != null)
        {
                // Deserialize the data and store it in the account store
                // The users email address will be used to identify data in SimpleDB
                string str = await response.GetResponseTextAsync();
                JObject jobject = JObject.Parse(str);
                User user = OAuthParser(jobject);

                OnCompleted(user);
        }

        if (account != null)
        {
            store.Delete(account, App.AppName);
        }

        await store.SaveAsync(account = e.Account, App.AppName);
    }
}

private void OnAuthError(object sender, AuthenticatorErrorEventArgs e)
{
        OAuth2Authenticator OAuth2Authenticator = sender as OAuth2Authenticator;

    if (OAuth2Authenticator != null)
    {
        OAuth2Authenticator.Completed -= OnAuthCompleted;
        OAuth2Authenticator.Error -= OnAuthError;
    }

    OnError("Authentication error: " + e.Message);
}

    private static User ParseGooglePlusResponse(JObject jobject)
    {
        try
        {
            User user = new User()
            {
                Email = jobject["email"].ToString(),
                Pseudo = jobject["name"].ToString(),
                Firstname = jobject["given_name"].ToString(),
                Surname = jobject["family_name"].ToString(),
                Image = jobject["picture"].ToString(),
                Password = "girafe"
            };
            return user;
        }
        catch (Exception e) 
        { Debug.WriteLine(e.ToString()); }
        return null;
    }

    private static User ParseFacebookResponse(JObject jobject)
    {
        try
        {
            Debug.WriteLine(jobject);
            User user = new User()
            {
                Email = jobject["email"].ToString(),
                Pseudo = jobject["name"].ToString(),
                Firstname = jobject["given_name"].ToString(),
                Surname = jobject["family_name"].ToString(),
                Image = jobject["picture"].ToString(),
                Password = "girafe"
            };
            return user;
        }
        catch (Exception e)
        { Debug.WriteLine(e.ToString()); }
        return null;
    }
}

所以,我正在使用这个类:

private void FacebookAuthConnection()
    {
        AuthenticationState.Authenticator = OAuthService.Facebook().Authenticator(OAuthLoginCompleted, OAuthLoginError);
        Presenter.Login(AuthenticationState.Authenticator);
    }

然而,问题即将来临..首先,GooglePlus有效,但我在Android手机上收到一条警告,说明“Chrome自定义标签无法关闭...”,因此该应用程序崩溃与空堆栈跟踪...我在网上搜索,我唯一得到的是将new OAuth2Authenticator();的最后一个参数变为false,这不起作用,因为谷歌不允许它从webview。 ..

所以我想,好吧我的代码工作,我得到用户信息blablabla,让我们试试facebook,如果它是从本机浏览器。但是,我找不到参数URL ...

Scope = "";
AuthorizeUrl = "";
AccessTokenUrl = "";
UserInfoUrl = "";
  • 范围似乎是public_profile
  • AuthorizationUrl 将为https://m.facebook.com/dialog/oauth/

但另外两个呢?我将它们用于Google +。

我真的被卡住了,我觉得,每过一个新的秒数,我就会越来越沮丧......

谢谢!

修改

我的实际价值观:

Scope = "email";
AuthorizeUrl = "https://www.facebook.com/v2.8/dialog/oauth";
AccessTokenUrl = "https://graph.facebook.com/oauth/access_token";
UserInfoUrl = "https://graph.facebook.com/me?fields=email,name,gender,picture\"";

clientId = "XXXX";
redirectUri = "http://www.facebook.com/connect/login_success.html";

1 个答案:

答案 0 :(得分:2)

Facebook允许在嵌入式Web视图中进行授权。 所以它做的是使用外部身份验证(在chrome标签中)用于谷歌+(在某些设备上它只是在授权后它不会返回我的应用程序) - 就像你做的那样。 但是对于Facebook和VKontakte,我在网页浏览中使用了xamarin.auth,它的问题要少得多,除了登录视图设计外,你可以完全控制所有内容。除了UWP ofc之外,整个过程仍然存在问题。

回答关于webview auth进程的facebook权限参数的问题:

// OAuth Facebook
// For Facebook login, configure at https://developers.facebook.com/apps
public static string FacebookClientId = "XXX";
public static string FacebookScope = "email";
public static string FacebookAuthorizeUrl = "https://www.facebook.com/v2.9/dialog/oauth";
public static string FacebookAccessTokenUrl = "https://graph.facebook.com/oauth/access_token";

用作:

auth = new OAuth2Authenticator(
                        clientId: Constants.FacebookClientId,  
                        scope: "email",
                        authorizeUrl: new Uri("https://www.facebook.com/v2.9/dialog/oauth"), // These values do not need changing
                        redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html")// These values do not need changing
                    );

用以下内容获取用户的详细信息后

var request1 = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me?fields=email,first_name,last_name,gender,picture"), null, eventArgs.Account);