我正在使用 Xamarin 表单应用程序。
我使用下面的代码片段来获取 AAD 登录的 token 。
IEnumerable<IAccount> accounts = await App.PCA.GetAccountsAsync().ConfigureAwait(false);
try
{
if (btnSignInSignOut.Text == "Sign in")
{
try
{
IAccount firstAccount = accounts.FirstOrDefault();
authResult = await App.PCA.AcquireTokenSilent(App.Scopes, firstAccount)
.ExecuteAsync()
.ConfigureAwait(false);
}
catch (MsalUiRequiredException)
{
try
{
var builder = App.PCA.AcquireTokenInteractive(App.Scopes)
.WithParentActivityOrWindow(App.ParentWindow);
if (Device.RuntimePlatform != "UWP")
{
// on Android and iOS, prefer to use the system browser, which does not exist on UWP
SystemWebViewOptions systemWebViewOptions = new SystemWebViewOptions()
{
iOSHidePrivacyPrompt = true,
};
builder.WithSystemWebViewOptions(systemWebViewOptions);
builder.WithUseEmbeddedWebView(false);
}
authResult = await builder.ExecuteAsync().ConfigureAwait(false);
}
catch (Exception ex2)
{
await DisplayAlert("Acquire token interactive failed. See exception message for details: ", ex2.Message, "Dismiss");
}
}
if (authResult != null)
{
var content = await GetHttpContentWithTokenAsync(authResult.AccessToken);
UpdateUserContent(content);
}
}
else
{
while (accounts.Any())
{
await App.PCA.RemoveAsync(accounts.FirstOrDefault()).ConfigureAwait(false);
accounts = await App.PCA.GetAccountsAsync().ConfigureAwait(false);
}
Device.BeginInvokeOnMainThread(() =>
{
slUser.IsVisible = false;
btnSignInSignOut.Text = "Sign in";
});
}
}
catch (Exception ex)
{
await DisplayAlert("Authentication failed. See exception message for details: ", ex.Message, "Dismiss");
}
但是一段时间后, token 会以某种方式过期并且不会刷新。因此,它总是将用户重定向到 MS 登录页面。
我的要求是,它应该自动获取登录用户的详细信息。
可以引用这个code .
我还检查了其他选项,例如直接调用 api 来获取刷新 token ,但没有发现任何有用的信息。
如果有人对此有任何想法,请告诉我。
提前致谢。
最佳答案
目前,MSAL 已缓存您的授权,如果授权仍然有效,可以让您以静默方式登录。因此,作为用户,您无需每次使用该应用程序时都登录。
您可以使用 SecureStorage.SetAsync
来存储访问 token 。
登录:
public async Task<bool> SignInAsync()
{
try
{
var accounts = await _pca.GetAccountsAsync();
var firstAccount = accounts.FirstOrDefault();
var authResult = await _pca.AcquireTokenSilent(Scopes, firstAccount).ExecuteAsync();
// Store the access token securely for later use.
await SecureStorage.SetAsync("AccessToken", authResult?.AccessToken);
return true;
}
catch (MsalUiRequiredException)
{
try
{
// This means we need to login again through the MSAL window.
var authResult = await _pca.AcquireTokenInteractive(Scopes)
.WithParentActivityOrWindow(ParentWindow)
.ExecuteAsync();
// Store the access token securely for later use.
await SecureStorage.SetAsync("AccessToken", authResult?.AccessToken);
return true;
}
catch (Exception ex2)
{
Debug.WriteLine(ex2.ToString());
return false;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
return false;
}
}
关于xamarin.forms - AcquireToken 一段时间后停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69163418/