When to use MSAL AcquireTokenSilentAsync

梦想的初衷 提交于 2019-12-08 03:33:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!