2017-04-04 13 views
1

我正在学习使用天蓝色后端构建Windows 10应用程序。我正在使用Micosoft帐户作为我的身份验证提供程序。我已经学会了如何缓存访问令牌,但我有点挂断刷新令牌。在Windows 10应用中使用天蓝色后端刷新访问令牌的时间/地点

据我所知,访问令牌是短暂的,更长的到期刷新令牌允许我获得新的访问令牌。我一直试图跟随阿德里安霍尔的书在这里:https://adrianhall.github.io/develop-mobile-apps-with-csharp-and-azure/chapter2/realworld/#refresh-tokens

我的问题是,我不太明白何时/在哪里调用或如何使用“client.RefreshUserAsync();”这本书不是很清楚。

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

现在,我的应用程序在我的主页上只有一个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

我想这个问题是该令牌可在使用应用程序的用户的中间到期,迫使用户重新登录吗?

根据您的描述,您将使用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,资源,client_secret(Web应用程序只)。所以我们不需要让用户再次登录。

什么时候应该刷新?

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

+0

因此,如果我正确地理解了你,在我对后端进行调用的任何地方,我应该捕获错误,刷新用户并再次尝试呼叫。 – Brad

+0

只需在Azure移动应用程序SDK中调用刷新API即可在发生认证错误时刷新令牌。请尝试使用新的访问令牌来查看它是否有效。 –

相关问题