我正在尝试使用 Azure Active Directory 在我的 uwp 应用程序上执行登录功能。这种情况成功发生,但是我无法让它在 token 过期时刷新 token ,并且总是收到错误“刷新失败,出现 403 禁止错误。刷新 token 已撤销或过期。”所以我必须再次打开登录窗口。我使用的是2.1.0版本和以下代码进行身份验证:
private async Task<bool> AuthenticateAsync(bool forceRelogon = false)
{
//string message;
bool success = false;
// Use the PasswordVault to securely store and access credentials.
PasswordVault vault = new PasswordVault();
PasswordCredential credential = null;
//Set the Auth provider
MobileServiceAuthenticationProvider provider = MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory;
MobileServiceUser user = null;
try
{
// Try to get an existing credential from the vault.
var credentials = vault.FindAllByResource(provider.ToString());
credential = credentials.FirstOrDefault();
}
catch (Exception ex)
{
// When there is no matching resource an error occurs, which we ignore.
Debug.WriteLine(ex);
}
if (credential != null && !forceRelogon)
{
// 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;
//message = string.Format($"Cached credentials for user - {user.UserId}");
// Consider adding a check to determine if the token is
// expired, as shown in this post: http://aka.ms/jww5vp.
if (RedemptionApp.ExtensionMethods.TokenExtension.IsTokenExpired(App.MobileService))
{
try
{
await App.MobileService.RefreshUserAsync();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
success = true;
}
else
{
try
{
// Login with the identity provider.
user = await App.MobileService
.LoginAsync(provider);
// Create and store the user credentials.
if (credential != null)
vault.Remove(credential);
credential = new PasswordCredential(provider.ToString(),
user.UserId, user.MobileServiceAuthenticationToken);
vault.Add(credential);
success = true;
//message = string.Format($"You are now logged in - {user.UserId}");
}
catch (MobileServiceInvalidOperationException)
{
//message = "You must log in. Login Required";
}
}
//var dialog = new MessageDialog(message);
//dialog.Commands.Add(new UICommand("OK"));
//await dialog.ShowAsync();
return success;
}
任何人都可以看到我正在做的事情有问题,或者需要在 AAD 服务提供商内做任何事情吗?
最佳答案
通过查看服务器端应用程序日志,您也许能够获得更准确的信息。 token 刷新失败详细信息将自动记录在那里。有关应用程序日志的更多详细信息可以在此处找到:https://azure.microsoft.com/en-us/documentation/articles/web-sites-enable-diagnostic-log/ 。我建议将跟踪级别设置为“信息”或“详细”。
此外,如果您尚未执行此操作,Azure AD 需要一些额外的配置才能启用刷新 token 。具体来说,您需要配置“客户端 key ”并启用 OpenID Connect 混合流。更多详细信息可以在这篇博文中找到:https://cgillum.tech/2016/03/07/app-service-token-store/ (向下滚动到刷新 token 部分,查看其中描述 AAD 流程的位置)。
关于Azure 应用服务(移动应用)AAD 身份验证 token 刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38358196/