Whole function:

public static async Task<SaslMechanismOAuth2> AuthenticateMS365Async(Benutzer user)
{
    if (!user.UseImapM365 && !user.UsePopM365)
        return null;

    SaslMechanismOAuth2 oauth2 = null;
    string[] scopes = new string[] { };

    if (user.UseImapM365)
    {
        scopes = new string[]
        {
            "email",
            "offline_access",
            "https://outlook.office.com/IMAP.AccessAsUser.All", // Only needed for IMAP
        };
    }
    else if (user.UsePopM365)
    {
        scopes = new string[]
        {
            "email",
            "offline_access",
            "https://outlook.office.com/POP.AccessAsUser.All",  // Only needed for POP
        };
    }
    var options = new PublicClientApplicationOptions
    {
        ClientId = user.MS_CLIENTID,
        TenantId = user.MS_TENANTID,
        RedirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient"
    };

    var storageProperties = new StorageCreationPropertiesBuilder("merlin_msal_cache.dat", MsalCacheHelper.UserRootDirectory).Build();

    var publicClientApplication = PublicClientApplicationBuilder
        .CreateWithApplicationOptions(options)
        .Build();

    var cacheHelper = await MsalCacheHelper.CreateAsync(storageProperties);
    cacheHelper.RegisterCache(publicClientApplication.UserTokenCache);

    AuthenticationResult authToken;
    try
    {
        authToken = await publicClientApplication.AcquireTokenSilent(scopes, EMailService.MS_AuthAccount).ExecuteAsync();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        //Console.WriteLine(ex.StackTrace);
        authToken = await publicClientApplication.AcquireTokenInteractive(scopes).ExecuteAsync();

        var accounts = await publicClientApplication.GetAccountsAsync().ConfigureAwait(true);
        EMailService.MS_AuthAccount = accounts.FirstOrDefault();
    }

    oauth2 = new SaslMechanismOAuth2(authToken.Account.Username, authToken.AccessToken);
    return oauth2;
}

This function works. I tested it in one part of my program, but somehow ends in a infinite loop in another part of my program (gets stuck).

authToken = await publicClientApplication.AcquireTokenInteractive(scopes).ExecuteAsync();

This is the part where it gets stuck in a infinite loop.

I really have no clue what it could be.

That the AcquireTokenInteractive works equally in different parts of a program and doesn't show erratic behavior?

I checked the input many times and it is absolutely indentical (the Client-ID and Tenant ID and such).

I am clueless right now...

0

There are 0 answers