Xamarin MobileServiceClient RefreshUserAsync 与 Google 403

Xamarin MobileServiceClient RefreshUserAsync with Google 403

我正在使用 Azure 的 MobileServiceClient sdk 对我的服务器进行身份验证。随着升级到 4.x 版本,我还使用 Xamarin.Auth 通过 Google 和 Facebook 对用户进行身份验证。当响应从 Google 返回时,我得到了一个刷新令牌。然后我像这样调用移动服务 sdk:

   var accessToken = account.Properties["access_token"];
                var idToken = account.Properties["id_token"];

                var zumoPayload = new JObject();
                zumoPayload["access_token"] = accessToken;
                zumoPayload["id_token"] = idToken;

                var user = await client.LoginAsync(MobileServiceAuthenticationProvider.Google, zumoPayload, );

这项工作非常好。不起作用的是对 client.RefreshUserAsync() 的调用。每次说刷新令牌过期或不再有效时都会抛出 403,即使我在登录后立即调用该方法也是如此。我根本看不到很多使用 MobileServiceClient 4.x sdk 和 none 其中有如何使用刷新令牌的示例。

我也试过在 zumo 有效载荷中发送它,但它不起作用。我已尝试在 Google 上使我的用户无效(我正在取回刷新令牌),尝试通过浏览器登录并转到 auth/me 但刷新令牌不存在。任何帮助都会很棒!

AFAIK,您可以利用 Xamarin.Auth SDK 独立联系身份提供者并在您的移动客户端检索访问令牌,然后您需要登录您的后端(Azure 移动应用程序)以及用于检索 authenticationToken 的令牌,那么您可以利用 authenticationToken 访问移动应用程序下的资源。

由于您正在使用 Client-managed authentication, for refreshing the new access_token, you need to do it on your mobile client side. I checked Xamarin.Auth and found that there is no method for requesting an access token. You need to refer to Refreshing an access token and implement this feature by yourself. I followed OAuth2Authenticator.cs 并创建了一个用于请求访问令牌的扩展方法,如下所示:

public static class OAuth2AuthenticatorExtensions
{
    public static Task RefreshAccessTokenAsync(this OAuth2Authenticator authenticator, Account account)
    {
        var dics = new Dictionary<string, string>
        {
            {"refresh_token",account.Properties["refresh_token"]},
            {"client_id", authenticator.ClientId},
            {"grant_type", "refresh_token"}
        };
        if (!string.IsNullOrEmpty(authenticator.ClientSecret))
        {
            dics["client_secret"] = authenticator.ClientSecret;
        }
        return authenticator.RequestAccessTokenAsync(dics).ContinueWith(task =>
        {
            if (task.IsFaulted)
            {
                //todo:
            }
            else
            {
                authenticator.OnRetrievedAccountProperties(task.Result);
            }
        });
    }
}

此外,如果您利用 Server-managed authentication with Microsoft.Azure.Mobile.Client, then you could leverage RefreshUserAsync for refreshing the access token, at this point your previous access_token, clientId are stored on azure, and your mobile app backend would directly communicate with Google's OAuth 2.0 endpoint and request a new access token for you and update the token store on Azure. For more details about token store within App Service, you could follow here