何时/何处使用azure后端刷新Windows 10应用程序中的访问令牌

时间:2017-04-04 05:51:58

标签: c# azure authentication uwp refresh-token

我正在学习使用天蓝色后端构建Windows 10应用程序。我使用Micosoft Account作为我的身份验证提供程序。我已经学会了如何缓存访问令牌,但我对刷新令牌有点不知所措。

根据我的理解,访问令牌是短暂的,更长的过期刷新令牌允许我获得新的访问令牌。我一直在努力跟随Adrian Hall的书:https://adrianhall.github.io/develop-mobile-apps-with-csharp-and-azure/chapter2/realworld/#refresh-tokens

我的问题是,我不太明白何时/何地致电或如何使用" 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;
    }

1 个答案:

答案 0 :(得分:1)

  

我想问题是令牌可能会在使用该应用的用户中间到期,迫使用户再次登录?

根据您的说明,您使用Azure移动应用作为UWP后端。要访问移动应用,我们需要使用访问令牌。如您所知,访问令牌将过期。为了获得新的访问令牌,我们需要使用刷新令牌。有关如何通过刷新令牌获取访问令牌的信息,请参阅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,resource,client_secret(仅限web app)。所以我们不需要让用户再次登录。

  

我什么时候应该打电话给刷新?

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