何时使用MSAL AcquireTokenSilentAsync [英] When to use MSAL AcquireTokenSilentAsync
问题描述
我正在对Xamarin.Forms使用MSAl,并在 Xamarin上实现了示例使用Azure AD B2C授权
I am using MSAl for Xamarin.Forms and implemented the sample on Xamarin Authorization with Azure AD B2C
在示例中,从LoginPage
的OnAppearing()
-Method(视图)(从LoginAsync(true)委托)调用AcquireTokenSilentAsync()
-Method.登录页面是此示例应用程序的启动页面.
In the sample the AcquireTokenSilentAsync()
-Method is called from the OnAppearing()
-Method of the LoginPage
(the View) (delegated from LoginAsync(true)). The login page is the start-up page of this sample app.
我的问题是,我必须在逻辑之前在任何视图(或视图模型)中调用AcquireTokenSilentAsync()
还是足以在启动页面上使用它?如果我必须在任何视图/视图模型上使用它,这似乎是一个方面.您是通过使用某些AOP模式还是在每个视图/视图模型上真正调用此方法来解决此问题?
My question is, do I have to call AcquireTokenSilentAsync()
in any view (or view model) before my logic or is it enough to use it on my start-up page? If I have to use it on any view/view model it seems this is kind of an aspect. Do you solve this by using some AOP pattern or really calling this method on each and every view/view model?
推荐答案
我现在在启动时立即调用AquireTokenSilentAsync
.
I now call AquireTokenSilentAsync
once on startup.
他们现在对如何使用它有很好的解释: https://github. com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/AcquireTokenSilentAsync-using-a-cached-token
They now have a great explanation how to use it: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/AcquireTokenSilentAsync-using-a-cached-token
使用Msal 2.x的公共客户端应用程序中的推荐呼叫模式
Recommended call pattern in public client applications with Msal 2.x
AuthenticationResult result = null;
var accounts = await app.GetAccountsAsync();
try
{
result = await app.AcquireTokenSilentAsync(scopes, accounts.FirstOrDefault());
}
catch (MsalUiRequiredException ex)
{
// A MsalUiRequiredException happened on AcquireTokenSilentAsync.
// This indicates you need to call AcquireTokenAsync to acquire a token
System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");
try
{
result = await app.AcquireTokenAsync(scopes);
}
catch (MsalException msalex)
{
ResultText.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
}
}
catch (Exception ex)
{
ResultText.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
return;
}
if (result != null)
{
string accessToken = result.AccessToken;
// Use the token
}
这篇关于何时使用MSAL AcquireTokenSilentAsync的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!