Unable to authenticate

ChuckieAJ 91 Reputation points
2024-04-04T10:04:01.3233333+00:00

Moving my application from .Net Framework 4.6.2 to .Net8 and this code fails. The AuthResult object is null and I get exceptions:

2024-04-04 10:55:11.5248|ERROR|MSATools.Program|MSAL.NetCore.4.60.1.0.MsalClientException:

ErrorCode: loopback_redirect_uri

Microsoft.Identity.Client.MsalClientException: Only loopback redirect uri is supported, but urn:ietf:wg:oauth:2.0:oob was found. Configure http://localhost or http://localhost:port both during app registration and when you create the PublicClientApplication object. See https://aka.ms/msal-net-os-browser for details

at Microsoft.Identity.Client.Platforms.Shared.Desktop.OsBrowser.DefaultOsBrowserWebUi.UpdateRedirectUri(Uri redirectUri)

at Microsoft.Identity.Client.Internal.AuthCodeRequestComponent.FetchAuthCodeAndPkceInternalAsync(IWebUI webUi, CancellationToken cancellationToken)

at Microsoft.Identity.Client.Internal.AuthCodeRequestComponent.FetchAuthCodeAndPkceVerifierAsync(CancellationToken cancellationToken)

at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.GetTokenResponseAsync(CancellationToken cancellationToken)

at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.ExecuteAsync(CancellationToken cancellationToken)

at Microsoft.Identity.Client.Internal.Requests.RequestBase.<>c__DisplayClass11_1.<<RunAsync>b__1>d.MoveNext()

--- End of stack trace from previous location ---

at Microsoft.Identity.Client.Utils.StopwatchService.MeasureCodeBlockAsync(Func`1 codeBlock)

at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)

at Microsoft.Identity.Client.ApiConfig.Executors.PublicClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenInteractiveParameters interactiveParameters, CancellationToken cancellationToken)

at MSATools.Outlook.TokenProvider.GetAuthorizationTokenAsync(Uri uri, Dictionary`2 additionalAuthenticationContext, CancellationToken cancellationToken) in D:\My Programs\2022\MSATools\MSATools\Outlook\Outlook.cs:line 50

GetAuthenticatedClientAsync: Acquire token error. See log.

2024-04-04 10:55:30.1889|ERROR|MSATools.Program|The AuthResult value is null

GetAuthenticatedClientAsync: Acquire token silently error. See log.

public class TokenProvider : IAccessTokenProvider
{
    private readonly string _AppID = "xxxxx";
    //Set the scope for API call to user.read
    private readonly string[] _Scopes = new string[] { "user.read", "calendars.readwrite" };
    private AuthenticationResult? _AuthResult = null;
    readonly IPublicClientApplication? PublicClientApp = null;
    public TokenProvider() 
    {
        PublicClientApp = PublicClientApplicationBuilder.Create(_AppID).Build();
        TokenCacheHelper.CacheFilePath = Program.OutlookOptions.TokenCachePath;
        TokenCacheHelper.EnableSerialization(PublicClientApp.UserTokenCache);
    }
    public async Task<string> GetAuthorizationTokenAsync(Uri uri, Dictionary<string, object> additionalAuthenticationContext = default,
        CancellationToken cancellationToken = default)
    {
        try
        {
            var accounts = await PublicClientApp.GetAccountsAsync();
            // See: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/MSAL.NET-3-released#acquiring-a-token-also-got-simpler
            _AuthResult = await PublicClientApp.AcquireTokenSilent(_Scopes, accounts.FirstOrDefault()).ExecuteAsync();
        }
        catch (MsalUiRequiredException ex)
        {
            // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token
            System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");
            try
            {
                // See: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/MSAL.NET-3-released#acquiring-a-token-also-got-simpler
                _AuthResult = await PublicClientApp.AcquireTokenInteractive(_Scopes).ExecuteAsync();
            }
            catch (MsalException msalex)
            {
                Program.MSAToolsLogger.Error(msalex);
                Console.WriteLine("GetAuthenticatedClientAsync: Acquire token error. See log.");
            }
        }
        catch (Exception ex)
        {
            Program.MSAToolsLogger.Error(ex);
            Console.WriteLine("GetAuthenticatedClientAsync: Acquire token silently error. See log.");
        }
        if (_AuthResult == null ) {
            Program.MSAToolsLogger.Error("The AuthResult value is null");
            Console.WriteLine("GetAuthenticatedClientAsync: Acquire token silently error. See log.");
        }
        // get the token and return it in your own way
        return _AuthResult.AccessToken;
    }
    public AllowedHostsValidator AllowedHostsValidator { get; }
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
11,162 questions
{count} vote