Xamarin.Auth与Google API:续订凭据?

时间:2014-04-09 15:30:45

标签: authentication google-api xamarin xamarin.auth

我正在尝试使用Xamarin.Auth和Xamarin Google-APIs登录Google并访问云端硬盘。我已经设法使几乎所有工作,但身份验证令牌似乎在大约一个小时后到期。一切都运行良好一段时间,但大约一个小时后,当我尝试访问时,我收到一个无效的凭据[401]错误和泄漏:

Google.Apis.Requests.RequestError
Invalid Credentials [401]
Errors [
    Message[Invalid Credentials] Location[Authorization - header] Reason[authError] Domain[global]
]
: GoogleDriveAgent: FetchRemoteFileList() Failed! with Exception: {0}
[0:] Google.Apis.Requests.RequestError
Invalid Credentials [401]
Errors [
    Message[Invalid Credentials] Location[Authorization - header] Reason[authError] Domain[global]
]
: GoogleDriveAgent: FetchRemoteFileList() Failed! with Exception: {0}

objc[37488]: Object 0x7f1530c0 of class __NSDate autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug
objc[37488]: Object 0x7f151e50 of class __NSCFString autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug
//...more leaks.

我想确保我按预期使用Xamarin.Auth和Google API,所以这是我的代码:

在我的GoogleDriveService课程中,我有一个帐户商店和一个已保存的帐户:

AccountStore Store { 
    get {
        if (m_store == null)
            m_store = AccountStore.Create ();
        return m_store;
    }
}

Account SavedAccount { 
    get {
        var savedAccounts = Store.FindAccountsForService ("google");
        m_savedAccount = (savedAccounts as List<Account>).Count > 0 ? (savedAccounts as List<Account>) [0] : null;

        return m_savedAccount;
    }
}

我初始化会话并启动服务:

void InitializeSession ()
{
    Authenticator = new GoogleAuthenticator (ClientID, new Uri (RedirectUrl), GoogleDriveScope);
    Authenticator.Completed += HandleAuthenticationCompletedEvents;

    if (SavedAccount != null) {
        Authenticator.Account = SavedAccount;
        StartService ();
    }

    UpdateSignInStatus ();
}

bool StartService ()
{
    try {
        Service = new DriveService (Authenticator);
        return true;
    } catch (Exception ex) {
        // Log exception
        return false;
    }
}

...并回复认证已完成的事件:

void HandleAuthenticationCompletedEvents (object sender, AuthenticatorCompletedEventArgs e)
{
    if (e.IsAuthenticated) {  // Success
        UpdateSignInStatus();
        Store.Save (e.Account, "google");
        Authenticator.Account = e.Account;
        StartService();
        LoginController.DismissViewController(true, null);
    } else {                                    // Cancelled or no success
        UpdateSignInStatus();
        LoginController.DismissViewController(true, null);
        LoginController = null;
        InitializeSession ();  // Start a new session
    }
}

同样,一切正常,一段时间,但身份验证到期。我理解it should,但我认为保存在AccountStore中的凭据应该仍然有效。

Xamarin.Auth getting started docs中,它表示再次调用Save将覆盖凭据,并且“这对于使帐户对象中存储的凭据到期的服务很方便”。听起来很有希望......

所以我尝试了另一种方法:拥有一个始终覆盖getter中凭据的IsSignedIn属性......

public bool IsSignedIn { 
    get {
        if (Authenticator == null) {
            m_isSignedIn = false;
            return m_isSignedIn;
        }

        if (Authenticator.Account != null) {
            Store.Save (Authenticator.Account, "google"); // refresh the account store
            Authenticator.Account = SavedAccount;
            m_isSignedIn = StartService ();
        } else {
            m_isSignedIn = false;
        }

        return m_isSignedIn;
    }
}

...然后在任何API调用(获取元数据,下载等)之前访问IsSignedIn。它不起作用:我上面仍然显示过期的凭据错误。

这是否需要refresh the token?我究竟做错了什么?

1 个答案:

答案 0 :(得分:2)

访问令牌应该相对较快到期。这就是为什么在第一次授权之后你还会收到一个refresh_token,你可以用它来获取一个新的访问令牌,如果当前的一个到期。连续的auths不会给你一个刷新令牌,所以一定要保留你收到的那个!

访问令牌变为无效后,您只需使用refresh_token并将OAuthRequest发送到Google OAuth端点的token_url。

var postDictionary = new Dictionary<string, string>();
postDictionary.Add("refresh_token", googleAccount.Properties["refresh_token"]);
postDictionary.Add("client_id", "<<your_client_id>>");
postDictionary.Add("client_secret", "<<your_client_secret>>");
postDictionary.Add("grant_type", "refresh_token");

var refreshRequest = new OAuth2Request ("POST", new Uri (OAuthSettings.TokenURL), postDictionary, googleAccount);
        refreshRequest.GetResponseAsync().ContinueWith (task => {
            if (task.IsFaulted)
                Console.WriteLine ("Error: " + task.Exception.InnerException.Message);
            else {
                string json = task.Result.GetResponseText();
                Console.WriteLine (json);
                try {
                    <<just deserialize the json response, eg. with Newtonsoft>>
                }
                catch (Exception exception) {
                    Console.WriteLine("!!!!!Exception: {0}", exception.ToString());
                    Logout();
                }
            }
        });