Search code examples
.netoauth-2.0azure-ad-msalmaui

MS ID client in MAUI: how to avoid UI to get access token silently after restart the App if I previously signed in


I am developing a cross-platform .NET 6 MAUI App for manage information and need to backup it to onedrive. It uses Microsoft.Identity.Client and Microsoft.Graph packages to authenticate, authorize and access to onedrive functionallity.

When I run the sample App from this MS Dev Blog, the 1st time it uses UI (system browser) to interact with the user and finally get the access token, the 2nd time as expected I can get the token silently, but whenever I restart the App, it requires UI again to get the token as if where the first time… This happens on windows 11, but not on Android...

How can I avoid the continuous use of UI to get the access token after restart the App, if previously already I signed in?

As far as I know, there is a token cache in MSAL, but it appears to get flushed when I restart the App.

Thank you in advance


Solution

  • On desktop Apps, the tokens are in-memory, not persisted by default. If you close the app that acquired the tokens, the cache is lost. You have to persist this cache (serializing) to preserve the tokens...

    Token cache serialization in MSAL.NET

    "MSAL.NET provides an in-memory token cache by default. Serialization is provided by default for platforms where secure storage is available for a user as part of the platform: Universal Windows Platform (UWP), Xamarin.iOS, and Xamarin.Android.

    ...

    In desktop applications, we recommend that you use the cross-platform token cache. MSAL.NET provides the cross-platform token cache in a separate library named Microsoft.Identity.Client.Extensions.Msal."

    Dec 11, 2022 - Edition: I checked again in repository of the sample and found that "MAUI sample has moved"

    Now, the new sample project seems to persist token cache on windows (as it did on android/ios)...

    You can use this new project as reference to build an App that needs to get user's consent to access a cloud API (Ej. on Microsoft Graph)...

    Microsoft's Guys are hard working, it seems!