'GetAccountsAsync' returns null in my .NET Maui application (C#)

281 Views Asked by At

I have a .NET Maui application that is supposed to use MSAL Authentication (B2B). The login with username and password works. However, I want to check if a valid access token is stored in the cache when the application starts. The code line var accounts = await _application.GetAccountsAsync(); returns null, which is why the AcquireTokenSilent method never works. Does anyone have an idea why this is null? Do I need to manually write the token to the cache or is it done automatically? Does anyone have a suggestion for an alternative?

_application.GetAccountsAsync().IsFaulted is false.

My code for the authentication process is as follows:

private static IPublicClientApplication _application;
private static AuthenticationResult _authenticationResult;

private static void BuildApplication()
{
    _application = PublicClientApplicationBuilder.Create(B2BConstants.ClientId)
        .WithTenantId(B2BConstants.TenantId)
        .WithAuthority(B2BConstants.Authority)
        .WithRedirectUri("http://localhost")
        .Build();
}


/// <summary>
/// MSAL Authenticate Silent with token cache.
/// </summary>
/// <returns>AccessToken as String</returns>
public static async Task<string> AuthenticateSilentAsync()
{
    if (_application == null) BuildApplication();
    var accounts = await _application.GetAccountsAsync();

    _authenticationResult = await _application.AcquireTokenSilent(B2BConstants.Scopes, accounts.FirstOrDefault())
        .ExecuteAsync();

    return _authenticationResult.AccessToken;
}

public static async Task<string> AuthenticateAsync(string username, string password)
{
    BuildApplication();
    _authenticationResult = null;

    try
    {
        return await AuthenticateSilentAsync();
        
    }
    catch (MsalUiRequiredException ex)
    {
        try
        {
            _authenticationResult = await _application.AcquireTokenByUsernamePassword(B2BConstants.Scopes, username, password)
                .WithTenantId(B2BConstants.TenantId)
                .ExecuteAsync();

            return _authenticationResult.AccessToken;
        }
        catch (MsalException msalex)
        {
            return null;
        }
    }
    catch (Exception ex)
    {
        return null;
    }
}

I have already tried to retrieve the token using the GetAccountsAsync method in order to pass the result to AcquireTokenSilent. However, the accounts are always null.

0

There are 0 best solutions below