Caching / remembering accounts for MSAL .NET desktop app

Viewed 11

Currently working on providing OAUTH for some office365 email related tasks. I've looked into OAUTH and Microsoft Identity on .NET and have the following code, mostly copied from tutorials:

private async void Button_Click(object sender, RoutedEventArgs e)
        {
            var app = PublicClientApplicationBuilder.Create(ClientId)
                .WithDefaultRedirectUri()
                .WithAuthority(AzureCloudInstance.AzurePublic, Tenant)
                .Build();

            var scopes = new string[] {"Mail.Send"};

            var accounts = await app.GetAccountsAsync();
            var userAcc = accounts.FirstOrDefault();
            AuthenticationResult authRes = null;

            try
            {
                authRes = await app.AcquireTokenSilent(scopes, userAcc).ExecuteAsync();
            }
            catch (MsalUiRequiredException ex)
            {
                try
                {
                    authRes = await app.AcquireTokenInteractive(scopes)
                        .WithAccount(userAcc)
                        .ExecuteAsync();
                }
                catch { }
            }
            catch { }

            if (authRes != null)
            {
                MessageBox.Show(authRes.AccessToken);
            }
        }

Everytime I click a button, I request a token to get access to sending mail (in this case via Graph). However, everytime I click the button, the app object returns an empty list from the GetAccountsAsync call.

I can understand caching the token while running. However, it seems everytime I make a call to GetAccountsAsync, either after creating a new instance of publicclientapplication, or by restarting the app, I need to login interactively. How do I keep the app logged in? Should I just be trying to keep a reference to the token whenever possible?

0 Answers
Related