When/where 刷新 Windows 10 个带有 Azure 后端的应用程序中的访问令牌

When/where to refresh access token in Windows 10 app with azure backend

我正在学习使用 Azure 后端构建 Windows 10 个应用程序。我正在使用 Micosoft 帐户作为我的身份验证提供程序。我已经了解了如何缓存访问令牌,但我对刷新令牌有点着迷。

据我了解,访问令牌的有效期很短,刷新令牌过期时间越长,我就可以获取新的访问令牌。我一直在努力跟随 Adrian Hall 的书:https://adrianhall.github.io/develop-mobile-apps-with-csharp-and-azure/chapter2/realworld/#refresh-tokens

我的问题是我不太明白when/where调用或如何使用"client.RefreshUserAsync();"而且这本书也不是很清楚。

我应该什么时候调用刷新??我想问题是令牌可能会在用户使用该应用程序的过程中过期,从而迫使用户再次登录,对吗?那么每次我的用户做任何事情时我都会调用刷新吗?我很困惑。

现在,我的应用程序在我的主页上只有一个 AuthenticateAsync 方法,该方法在用户单击登录按钮时执行。它会查找缓存的令牌,如果有,它会检查过期时间并在过期时重新进行身份验证。

private async System.Threading.Tasks.Task<bool> AuthenticateAsync()
    {
        string message;
        bool success = false;

        var provider = MobileServiceAuthenticationProvider.MicrosoftAccount;

        // Use the PasswordVault to securely store and access credentials
        PasswordVault vault = new PasswordVault();
        PasswordCredential credential = null;

        try
        {
            //try to get an existing credential from the vault.
            credential = vault.FindAllByResource(provider.ToString()).FirstOrDefault();

        }
        catch (Exception)
        {
            //When there is no matching resource an error occurs, which we ignore.
        }

        if (credential != null)
        {

            // Create a user from the stored credentials.
            user = new MobileServiceUser(credential.UserName);
            credential.RetrievePassword();
            user.MobileServiceAuthenticationToken = credential.Password;

            // Set the user from the stored credentials.
            App.MobileService.CurrentUser = user;


            success = true;
            message = string.Format("Cached credentials for user - {0}", user.UserId);

            // Consider adding a check to determine if the token is 
            // expired, as shown in this post: http://aka.ms/jww5vp

            //check expiration
            if (App.MobileService.IsTokenExpired())
            {
                //remove the expired credentials
                vault.Remove(credential);

                try
                {
                    // Login with the identity provider
                    user = await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);

                    // Create and store the user credentials.
                    credential = new PasswordCredential(provider.ToString(),
                        user.UserId, user.MobileServiceAuthenticationToken);

                    vault.Add(credential);

                    message = string.Format("Expired credentials caused re-authentication. You are now signed in - {0}", user.UserId);
                    success = true;
                }
                catch (InvalidOperationException)
                {
                    message = "You must log in. Login required.";
                }
            }
        }
        else
        {
            try
            {
                // Login with the identity provider
                user = await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount);

                // Create and store the user credentials.
                credential = new PasswordCredential(provider.ToString(),
                    user.UserId, user.MobileServiceAuthenticationToken);
                vault.Add(credential);

                message = string.Format("You are now signed in - {0}", user.UserId);
                success = true;
            }
            catch (InvalidOperationException)
            {
                message = "You must log in. Login required.";
            }
        }

        var dialog = new MessageDialog(message);
        dialog.Commands.Add(new UICommand("OK"));
        await dialog.ShowAsync();

        return success;
    }

I guess the problem is that the token might expire in the middle of the user using the app, forcing the user to login again right?

根据您的描述,您使用 Azure 移动应用作为 UWP 后端。要访问移动应用程序,我们需要使用访问令牌。如您所知,访问令牌将过期。为了获得新的访问令牌,我们需要使用刷新令牌。关于如何通过refresh token获取access token,请参考this article。以下是详细的 http 请求信息:

// Line breaks for legibility only

POST /{tenant}/oauth2/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded

client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&refresh_token=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq...
&grant_type=refresh_token
&resource=https%3A%2F%2Fservice.contoso.com%2F
&client_secret=JqQX2PNo9bpM0uEihUPzyrh    // NOTE: Only required for web apps

从上面的 http 请求,我们只提供 client_id、refresh_token、grant_type、资源、client_secret(仅限网络应用程序)。所以我们不需要让用户再次登录。

When should I call refresh??

如果访问令牌过期,我们访问移动应用程序时会出错。此时我们可以尝试在catch{}逻辑中通过refresh token获取新的access token。