I currently have 2 projects in a solution that is utilizing the MSAL.NET (Microsoft.Identity.Client) for authentication.
These 2 projects essentially are 2 different functionalities on the same Excel Plug In. As of now, if the user wants to access both of these projects they would need to authenticate twice, once for each project.
I'm currently trying to figure out how I can share the token between these two projects so that the user only needs to authenticate themselves once.
I looked into several methods where I finally stumbled upon MSAL's in memory cache functionality and was wondering if this in memory cache would be the correct solution for this situation and how I can implement this functionality.
Below is the authentication code I am currently using:
private static async Task<AuthenticationResult> Login()
{
AuthenticationResult authResult = null;
var app = App.PublicClientApp;
string[] scopes = new string[] { "user.read" };
var accounts = await app.GetAccountsAsync();
var firstAccount = accounts.FirstOrDefault();
try
{
authResult = await App.PublicClientApp.AcquireTokenSilent(scopes, firstAccount)
.ExecuteAsync();
}
catch (MsalUiRequiredException ex)
{
// A MsalUiRequiredException happened on AcquireTokenSilent.
// This indicates you need to call AcquireTokenInteractive to acquire a token
System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");
try
{
authResult = await App.PublicClientApp.AcquireTokenInteractive(scopes)
.WithAccount(accounts.FirstOrDefault())
.WithPrompt(Prompt.SelectAccount)
.ExecuteAsync();
}
catch (MsalException msalex)
{
}
}
catch (Exception ex)
{
}
if (authResult != null)
{
expires_in = (authResult.ExpiresOn.LocalDateTime.ToUniversalTime() - DateTime.Now.ToUniversalTime()).TotalSeconds;
m_GrantedDateTime = DateTime.Now.ToUniversalTime();
}
return authResult;
}
Good that you are using Microsoft.Identity.Client! I am also taking advantage of token cache serialization in a project I’m working on. If your plugins share memory, in-memory token caching may work for you. My code runs in separate processes so I implemented the Cosmos (more reliable than SQL) serialization model. It is not documented at the 1st doc link but is mentioned at the 2nd GitHub link below.
https://github.com/AzureAD/microsoft-identity-web/wiki/token-cache-serialization
Would be great to stay in touch on this as it is one of the more sparsely documented “advanced” topics in Azure AD authentication.