Not able to get access token using MSAL.Net in VSTO application

Krishan Kataria 10 Reputation points
2023-09-01T13:55:37.1333333+00:00

I have created a VSTO Excel Add-in project (with C#, Target .Net Framework version 4.8, Visual Studio 2022, working on Windows 10 Enterprise (version 21H2)).

With this Microsoft Excel add-in, I want to do authentication for my APIs by getting the access token on behalf of user, for the users present in my Azure Active Directory, using MSAL.Net.

I did my App Registration in Azure and also configured the desired Redirect URLs, scopes.

I am facing some issues in getting access token from the VSTO application, but my same code is working fine in a .Net Console Application (target framework 4.8)

Below is the code (I have referred it from the Quick Start guides available on Azure portal for various platforms), the code is working fine with Console application, able to get the access token through method app.AcquireTokenInteractive(scopes).

But the same method is throwing System.Net.Http.HttpRequestException Exception in the VSTO application,
Exception thrown: 'System.Net.Http.HttpRequestException' in mscorlib.dll

Exception thrown: 'System.Net.Http.HttpRequestException' in mscorlib.dll

An exception of type 'System.Net.Http.HttpRequestException' occurred in mscorlib.dll but was not handled in user code

An error occurred while sending the request.

Here is the code which I am using in both type of projects:

using System;
using System.Threading.Tasks;
using Microsoft.Identity.Client;


public class MyWindowsAuthenticator
{
        private static string ClientId = "********my app's client id********"; // secret

        private static string Tenant = "organizations";
        private static string Instance = "https://login.microsoftonline.com/";
        private static IPublicClientApplication _clientApp;

        //Set the scope for API call to user.read
        string[] scopes = new string[] { "user.read" };

        public static IPublicClientApplication PublicClientApp { get { return _clientApp;}}


        public async Task AuthorizeAsync()
        {
            var builder = PublicClientApplicationBuilder.Create(ClientId)
                .WithAuthority($"{Instance}{Tenant}")
                .WithDefaultRedirectUri();

            WindowsBrokerOptions options = new WindowsBrokerOptions();

            builder.WithWindowsBrokerOptions(options);

            //builder.WithWindowsBroker(true);

            _clientApp = builder.Build();

            AuthenticationResult authResult = null;
            var app = PublicClientApp;

            IAccount firstAccount;
            firstAccount = PublicClientApplication.OperatingSystemAccount;

            try
            {

                authResult = await app.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.AcquireTokenInteractive(scopes)
                        .WithAccount(firstAccount)
                        .WithPrompt(Prompt.SelectAccount)
                        .ExecuteAsync();
                }
                catch (MsalException msalex)
                {
                    var errMsg = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
                    Console.WriteLine(errMsg);
                }
            }
            catch (Exception ex)
            {
                var errMsg = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
                Console.WriteLine(errMsg);
                return;
            }
        }

        
    }

Please help me in understanding the cause for the HttpRequestException in the VSTO application.

Microsoft Identity Manager
Microsoft Identity Manager
A family of Microsoft products that manage a user's digital identity using identity synchronization, certificate management, and user provisioning.
602 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,160 questions
Office Development
Office Development
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Development: The process of researching, productizing, and refining new or existing technologies.
3,439 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
19,293 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Guenther Fuellerer 5 Reputation points
    2024-02-13T12:25:12.8766667+00:00

    Adding

    ServicePointManager.Expect100Continue = true;
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    

    before creating the app solved the issue for me.

    1 person found this answer helpful.