问题
I am using MSAl for Xamarin.Forms and implemented the sample on Xamarin Authorization with Azure AD B2C
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.
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?
回答1:
I now call AquireTokenSilentAsync
once on startup.
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
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
}
来源:https://stackoverflow.com/questions/47739512/when-to-use-msal-acquiretokensilentasync