Search code examples
xamarin.formsazure-ad-msalmicrosoft-identity-platform

MSAL and Caching accesstoken on Xamarin Forms


We have a Xamarin Forms code base that has been using MSAL since 1.1.4 in 2019, we are now using 4.22.0.

The app has always kept it's own copy of the accesstoken acquired either silectly or interactively and it is the app's copy that it uses when accessing various B2C secured apis.

It only calls AcquireTokenSilent or AcquireTokenInteractive on initial logon or when a 401 is detected.

We beleive we have an issue with the storing of token and from what I understand MSAl caches the access token itself anyway. Looking at the documentation and samples we should be calling AcquireTokenSilent whenever we need the token and handling MSALUIRequiredException to call AcquireTokenInteractive.

Is this correct, does MSAL cache the accesstoken?

When we build the PublicClientApplication we do not call currently call WithIosKeychainSecurityGroup. Is that a prerequisite for the cachhing of tokens to work on iOS?

PublicClientApplicationBuilder
                        .Create(ClinicalServicesSettings.ClientID)
                        .WithB2CAuthority(ClinicalServicesSettings.Authority)
                        .Build()

Solution

  • You should use the recommended call pattern of AcquireTokenSilent, catch the MsalUiRequiredException and call AcquireTokenInteractive.

    MSAL does handle the caching for you, in mobile applications. During AcquireTokenSilent, MSAL will check the cache to see if there is a valid account and if the user can be signed-in silently without being shown a UI. If the refresh token is expired, or there has been a conditional access policy applied to the account (like MFA), then the MsalUiRequiredException will be thrown.

    If you want to share tokens across apps belonging to the same TeamId on iOS, you need to use WithIosKeychainSecurityGroup, which sets the iOS key chain security group. The TeamId is appended to the security group and by default the security group com.microsoft.adalcache is used, which is where MSAL caches tokens after auth (regardless of whether it happened in the app or via the authenticator - however auth via authenticator is not available with B2C). This enables the tokens to be shared across apps, and with both ADAL and MSAL iOS apps.