我正在学习使用天蓝色后端构建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;
}
因此,如果我正确地理解了你,在我对后端进行调用的任何地方,我应该捕获错误,刷新用户并再次尝试呼叫。 – Brad
只需在Azure移动应用程序SDK中调用刷新API即可在发生认证错误时刷新令牌。请尝试使用新的访问令牌来查看它是否有效。 –