2

I've attempted to authenticate users using Azure B2C and MSAL, but have stumbled upon some user experience issues.

When I debug my app, I usually don't have to sign in as I'm already authenticated and the token is still valid. However, if I switch from Debug to Release and then test the app, the AquireTokenSilentAsync method doesn't seem able to retrieve a valid token from the UserTokenCache. My assumption is that the UserTokenCache is cleared every time the app is closed. Somehow this doesn't happen in Debug mode, I guess it's because the cache is persisted between deploys.

I'm getting the authentication result this way, but have tried different overloads without any success.

AuthenticationResult ar = await App.PCApplication.AcquireTokenSilentAsync(App.Scopes, "", App.Authority, App.SignUpSignInpolicy, false);

So, when I sign in, close and re-enter the app I still need to login again.

I'm fully aware MSAL is still in preview, but I haven't been able to find any issues (yet) related to this behaviour. Is this a known issue and is there a workaround available?

Looking at the MSAL source code, I can clearly see that the UserTokenCache is using Android SharePreferences for persistance, and this works perfectly in debug mode. So, either this is a bug/missing implementation, or I'm failing to see something obvious..

1
  • I've done a blog post about what I did to figure out this issue over here: blog.wislon.io/posts/2016/12/05/… - the slightly less detailed version is provided as a potential answer below.
    – wislon
    Dec 10, 2016 at 11:36

1 Answer 1

4

I was able to replicate this almost exactly. Running under an IDE debugger, it works perfectly, but if it's not attached to a debugger, or running as a release version, it silently fails to store the token and everything else that comes after the attempted persistence usually fails to run as well.

I managed to resolve this same issue on Android by implementing my own cache derived from TokenCache and looking at what it was trying to do.

I located an example for a desktop app, as described here:

https://learn.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-devquickstarts-native-dotnet

and then had a look at their FileCache as it was defined in their GitHub repo:

https://github.com/AzureADQuickStarts/B2C-NativeClient-DotNet/blob/complete/TaskClient/FileCache.cs

I copied their FileCache, and added it to the PublicClientApplication initialisation :

ClientApplication = new PublicClientApplication(SharedConstants.AuthContext, SharedConstants.ClientId)
{
  RedirectUri = "urn:ietf:wg:oauth:2.0:oob",
  UserTokenCache = new FileCache(),
};

(by default most examples leave the UserTokenCache property empty, to presumably use the platform default shared prefs).

Then tweaked it to do some verbose logging during the reads/writes/accesses just to see what it was up to:

private void AfterAccessNotification(TokenCacheNotificationArgs args)
{
  // if the access operation resulted in a cache update
  try
  {
    this.Log().Debug("About to update token cache (if it's changed)...");
    if (this.HasStateChanged)
    {
      this.Log().Debug("State has changed, updating cache file...");
      lock (FileLock)
      {
        // reflect changes in the persistent store
        _file.WriteAllBytes(CacheFilePath, this.Serialize());
        // once the write operation took place, restore the HasStateChanged bit to false
        this.HasStateChanged = false;
      }
      this.Log().Debug("Token cache file updated");
    }
    this.Log().Debug("Finished updating token cache file");
  }
  catch (Exception ex)
  {
    this.Log().ErrorException($"Something went wrong during token AfterAccessNotification: {ex.Message}", ex);
  }
}

The logging showed that on Android, it was throwing an exception related to there not being a serialisation handler for a DateTimeOffset-type property somewhere deep in the bowels of the MSAL library.

Once I wrapped the AfterAccessNotification in a try-catch with a handler to log that the exception had occurred, it all started working perfectly.

I've stuck with using this version of FileCache for now, because it mostly solves my problem for the moment, but it does mean that the auth tokens etc. aren't stored securely now.

I suspect the same problem occurs on iOS 10.x on the simulator as well, but I've not been able to verify this yet.

I hope this helps someone.

Edit: as @Henrik has mentioned in his comment: editing the project properties and telling it not to link the System.Runtime.Serialization.dll on Android then fixes the problem permanently. Based on my (admittedly) limited testing, it's then safe to switch away from using the FileCache to the default behaviour again.

4
  • 1
    Thank you for this! The Serialize method in TokenCache indeed throws an exception: System.Runtime.Serialization.InvalidDataContractException: No set method for property 'OffsetMinutes' in type 'System.Runtime.Serialization.DateTimeOffsetAdapter'. Some had advised to skip linking the System.Runtime.Serialization assembly in the Android project, and this solved the issue immediately. Dec 13, 2016 at 18:33
  • fantastic! would you be willing/able to perhaps mark this as the answer? obviously I can't do this myself ;)
    – wislon
    Dec 14, 2016 at 22:15
  • Skipping linking of "System.Runtime.Serializaton" will it give any other issue some where else in project? Like any non-workable scenarios because of this skip. Thanks
    – Suchith
    Mar 20, 2017 at 12:01
  • @Suchith I have no idea, I guess it'll depend on what you are building that requires S.R.S to be physically linked into your app. I suspect not tho, it just means that S.R.S gets distributed as the full dll in your app.
    – wislon
    Mar 28, 2017 at 4:25

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.