Azure Active Directory Login Connection Closed Exception

Yuta Takayama 21 Reputation points
2020-11-09T22:14:48.993+00:00

I am inconsistently getting a connection closed exception when logging in with an Azure AD account using Microsoft Authentication Library (MSAL.NET) on my client's production environment.

Here is the code similar to the production. This is a simple Windows Form that takes in Client ID / App ID, TenantID or AadAuthorityAudience(organizations/consumers/common), and Redirect URI. Then, it creates an instance of IPublicClientApplication and display Azure Interactive Login Window. After the user is successfully authenticated against Azure AD, this form displays the Username, User's Tenant, ID Token, and Access Token to the textbox of the form.

using Microsoft.Identity.Client;
using System;
using System.Configuration;
using System.Windows.Forms;

namespace AADSimpleTest
{
    public partial class AADSimpleTestForm : Form
    {
        public AADSimpleTestForm()
        {
            InitializeComponent();
        }

        async private void testAADButton_Click(object sender, EventArgs e)
        {
            resultTextBox.Text = string.Empty;

            try
            {
                string clientID = ConfigurationManager.AppSettings["ClientId"];
                string tenantID = ConfigurationManager.AppSettings["Tenant"];
                string redirectURI = ConfigurationManager.AppSettings["RedirectURI"];
                string[] scopes = new string[] { "user.read", "Directory.Read.All" };

                IPublicClientApplication publicClientApp;
                publicClientApp = PublicClientApplicationBuilder.Create(clientID)
                    .WithAuthority(AzureCloudInstance.AzurePublic, tenantID)
                    .WithRedirectUri(redirectURI)
                    .Build();

                AuthenticationResult authenticationResult = await publicClientApp.AcquireTokenInteractive(scopes)
                    .WithPrompt(Prompt.ForceLogin)
                    .WithParentActivityOrWindow(this.Handle)
                    .ExecuteAsync();

                resultTextBox.AppendText($"Username: {authenticationResult.Account.Username}{Environment.NewLine}");
                resultTextBox.AppendText($"User's Tenant: {authenticationResult.TenantId}{Environment.NewLine}");
                resultTextBox.AppendText("ID Token:");
                resultTextBox.AppendText(Environment.NewLine);
                resultTextBox.AppendText(authenticationResult.IdToken);
                resultTextBox.AppendText(Environment.NewLine);
                resultTextBox.AppendText("Access Token:");
                resultTextBox.AppendText(Environment.NewLine);
                resultTextBox.AppendText(authenticationResult.AccessToken);
                resultTextBox.AppendText(Environment.NewLine);

                resultTextBox.AppendText(Environment.NewLine);
                resultTextBox.AppendText(Environment.NewLine);
            }
            catch (Exception ex)
            {
                resultTextBox.Text = ex.ToString();
            }
        }
    }
}

The App in Azure portal is setup as multi-tenant so users from any Azure AD Tenant can login. The code works when doing the test in-house. However, the result is consistent in production environment because it sometimes work and sometimes gets the following connection error exception after the user enters the valid credentials in the Azure interactive Login window.

System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server. ---> System.IO.IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
   at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
   at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
   --- End of inner exception stack trace ---
   at System.Net.Security._SslStream.EndRead(IAsyncResult asyncResult)
   at System.Net.TlsStream.EndRead(IAsyncResult asyncResult)
   at System.Net.PooledStream.EndRead(IAsyncResult asyncResult)
   at System.Net.Connection.ReadCallback(IAsyncResult asyncResult)
   --- End of inner exception stack trace ---
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Platforms.net45.Http.DnsSensitiveClientHandler.<SendAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Http.HttpManager.<ExecuteAsync>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Http.HttpManager.<ExecuteWithRetryAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Http.HttpManager.<SendPostAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Http.HttpManager.<SendPostAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.<ExecuteRequestAsync>d__11`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.<GetTokenAsync>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.OAuth2.TokenClient.<SendHttpAndClearTelemetryAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.OAuth2.TokenClient.<SendTokenRequestAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.<GetTokenResponseAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.<ExecuteAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.<RunAsync>d__13.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.ApiConfig.Executors.PublicClientExecutor.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at AADSimpleTest.AADSimpleTestForm.<testAADButton_Click>d__1.MoveNext()

So the question is how does this connection exception occur and how can this be resolved? I know that the user is successfully authenticated against Azure AD because the "Sign-Ins" Logs from the Azure Portal shows that the user was successfully authenticated. It can be the environment but I'm not sure whether VPN or some other factors can cause this exception.

Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
19,549 questions
0 comments No comments
{count} votes

Accepted answer
  1. 2020-11-10T16:05:00.143+00:00

    Hi @Yuta Takayama , this could be a proxy, firewall or other security appliance within the application network blocking the request. To find more low level detail you can:

    1. Configure network tracing (.NET Framework) or Enable trace level logging (.NET Core).
    2. Capture and analyze network logs

    Let us know if this answer was helpful to you. If so, please remember to mark it as the answer so that others in the community with similar questions can more easily find a solution.


0 additional answers

Sort by: Most helpful