Implementing MSAL + AAD B2C in Xamarin – 6 Tips, Tricks and Facts

Inspired by Steven Thewissen’s excellent MSAL article, I thought I would share what I have learned about MSAL over the 3+ years I have worked with MSAL and Xamarin. If you’re just getting started, be sure to read Steven’s article, he does a great job covering how to use the tools. This article is a collection of my personal learnings and experience using MSAL in my apps.

Without further ado, here are 6 tips/tricks/facts about MSAL, AAD B2C and Xamarin:

  1. TIP: Careful with package upgrades!
    • I cannot emphasize how important this is, check out the older packages in nuget: https://www.nuget.org/packages/Microsoft.Identity.Client/ the library was in preview for nearly 3 years and I went through the pain of dealing with api changes and behaviour changes. Read the change log carefully!
  2. FACT: You cannot change the Android webview title from “Sign In” without a custom MSAL build.
  3. TRICK: Use a JWT parser to check your token expiry, if the token is expired, you can pro-actively refresh it avoiding a round trip.
  4. TIP: Android devices with older system browsers may have issues loading the sign in webview.
  5. TRICK: Careful with exceptions
  6. TIP: You don’t need your own code to save tokens to secure storage, MSAL does this for you!

My Implementation

This is roughly what I have used in my last few projects, not exact, I generally use dependency injection and a few other bits. For simplicity’s sake this is a self-contained sample implementation. I would advise using Lazy<T> for IPublicClientApplication at the very least in a real life application.

Note: The Secrets class is generated by Dan Siegel’s excellent mobile build tools.

Your thoughts?

Please let me know your thoughts, tweet at me @dylbot9000. Happy to hear good/bad/ugly/criticisms/suggestions.

One Reply to “Implementing MSAL + AAD B2C in Xamarin – 6 Tips, Tricks and Facts”

Leave a Reply

Your email address will not be published. Required fields are marked *