C#/.NET 6 (ASP.NET Core) – The SSL connection could not be established.. An existing connection was forcibly closed by the remote host

I am looking to resolve an error that appears when communicating with a third party API. I have a service class with a method that communicates with a third-party external API to retrieve an OAuth Token:

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

            string base64EncodedAuthenticationString = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{_clientId}:{_clientSecret}"));
            _httpClient.DefaultRequestHeaders.Add("Authorization", $"Basic ${base64EncodedAuthenticationString}");

            FormUrlEncodedContent content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("grant_type", "client_credentials") });
            HttpResponseMessage response = await _httpClient.PostAsync($"{_baseApiUrl}/oauth2/token", content);

            var token = await response.Content.ReadAsAsync<TokenResponse>();
            return token.access_token;

The method works perfectly when I run it locally, but when it is deployed to our dev environment (Windows Server 2012 Virtual Machine), it returns the below error. I used the “ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;” to enforce which security protocol I am using (I also tried to add it to an HttpClientHandler as well), but that doesn’t seem to work. I am injecting HttpClient here scoped to my service class in Program.cs (builder.services.AddHttpClient()).

On our VM/Active Directory, I know we have a GPO that enables both TLS 1.0 and 1.2 in order to support some legacy apps.

The SSL connection could not be established, see inner exception. System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.. —> System.Net.Sockets.SocketException (10054): An existing connection was forcibly closed by the remote host. at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.CreateException(SocketError error, Boolean forAsyncThrow) at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ReceiveAsync(Socket socket, CancellationToken cancellationSoncThrow) at System.Net.Socket.Socket.1 buffer, SocketFlags socketFlags, Boolean fromNetworkStream, CancellationToken cancellationToken) at System.Net.Sockets.NetworkStream.ReadAsync(Memory1, CancellationToken (cancellationToken) at System.Net.Security.SslStream.FillHandshakeBufferAsync[TIOAdapter](TIOAdapter adapter, Int32 minSize) at System.Net.Security.SslStream.ReceiveBlobAsync[TIOAdapter](TIOAdapter adapter) at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TSstateMachine& stateMachine) at System.Net.Security.SslStream.ReceiveBlobAsync[TIOAdapter](TIOAdapter adapter) at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm) at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TSstateMachine& stateMachine) at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm) at System.Net.Security.SslStream.ProcessAuthenticationAsync(Boolean isAsync, Boolean isApm, CancellationToken cancellationToken) at System.Net.Security.SslStream.AuthenticateAsClientAsync(SslToClientsAuthenticationConperOptionNetkens)HSystem.Net.Security.SslStream.AuthenticateAsClientAsync(SslToClientsAuthenticationConperOptionNetations)HSystem.Net. .EstablishSslConnectionAsync(SslClientAuthenticationOptions sslOptions, HttpRequestMessage request, Boolean async, Stream stream, CancellationToken cancellationToken) at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine) at System.Net.Http.ConnectHelper.EstablishSslConnectionAsync(SslClientAuthenticationOptions sslOptions, HttpRequestMessage request, Boolean async, Stream stream, CancellationToken cancellationToken) at System.Netttnc.ConnectionAsync(CancellationToken cancellationToken) at System.Netttnc.ConnectionHttp. at System.Runtime.CompilerServices.AsyncTaskMethodBuilder1.AsyncStateMachineBox1.ExecutionContextCallback(Object s) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Runtime.CompilerServices.AsyncTaskMethodBuilder1.AsyncStateMachineBox1.MoveNext(Thread threadPoolThread) at System.Runtime.CompilerServices.AsyncTaskMethodBuilder1.AsyncStateMachineBox1.MoveNext() at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(IAsyncStateMachineBox box, Boolean allowInlining) at System.Threading.Tasks.Task.RunContinuations(Object continuationObject) at System.Threading.Fisks(Tasks)Continuations. .Threading.Tasks.Task1.TrySetResult(TResult result) at System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder1.SetResult(TResult result) at System.Net.Http.HttpConnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken) at System.Runtime.CompilerncServicesMethodAs.Async1.AsyncStateMachineBox1.ExecutionContextCallback(Object s) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Runtime.CompilerServices.AsyncTaskMethodBuilder1.AsyncStateMachineBox1.MoveNext(Thread threadPoolThread) at System.Runtime.CompilerServices.AsyncTaskMethodBuilder1.AsyncStateMachineBox1.MoveNext() at System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(IAsyncStateMachineBox box, Boolean allowInlining) at System.Threading.Tasks.Task.RunContinuations(Object continuationObject) at System.Threading.Fisks(Tasks)Continuations. .Threading.Tasks.Task1.TrySetResult(TResult result) at System.Runtime.CompilerServices.AsyncTaskMethodBuilder1.SetExistingTaskResult(Task1 task, TResult result) at System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder.SetResult() at System.Net.Sockets.Socket.<ConnectAsync>g__WaitForConnectWithCancellation|277_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken) at System.Runtime.CompilerServices.AsyncTaskMethodBuilder1.AsyncStateMachineBox1.ExecutionContextCallback(Object s) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Runtime.CompilerServices.AsyncTaskMethodBuilder1.AsyncStateMachineBox1.MoveNext(Thread threadPoolThread) at System.Runtime.CompilerServices.AsyncTaskMethodBuilder1.AsyncStateMachineBox1.MoveNext() at System.Threading.ThreadPool.<>c.<.cctor>b__87_0(Object state) at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.InvokeContinuation(Action1 continuation, Object state, Boolean forceAsync, Boolean requiresExecutionContextFlow) at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.OnCompleted(SocketAsyncEventArgs _) at System.Net.Sockets.SocketAsyncEventArgs internal.g__nCore Task|As1121 addressesTask, Int32 port, SocketType socketType, ProtocolType protocolType, CancellationToken cancellationToken) at System.Runtime.CompilerServices.AsyncTaskMethodBuilder1.AsyncStateMachineBox1.ExecutionContextCallback(Object s) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Runtime.CompilerServices.AsyncTaskMethodBuilder1.AsyncStateMachineBox1.MoveNext(Thread threadPoolThread) at System.Runtime.CompilerServices.AsyncTaskMethodBuilder1.AsyncStateMachineBox1.MoveNext() at System.Threading.ThreadPool.<>c.<.cctor>b__87_0(Object state) at System.Threading.Tasks.Sources.ManualResetValueTaskSourceCore1.SignalCompletion() at System.Threading.Tasks.Sources.ManualResetValueTaskSourceCore`1.SetResult(TResult result) at System.Net.Sockets.SocketAsyncEventArgs.MultiConnectSocketAsyncEventArgs.OnCompleted(SocketNetAsync) event.SocketAsyncEventArgs.MultiConnectSocketAsyncEventArgs.OnCompleted(SocketNetAsync) at System.Net.Sockets.SocketAsyncEvent ) at System.Net.Sockets.SocketAsyncEventArgs.ExecutionCallback(Object state) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ExecutionContext.Run(ExecutionContext callbackContext, ContextContext ) at System.Net.Sockets.SocketAsyncEventArgs.<>c.<.cctor>b__179_0(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped) at System.Threading.ThreadPoolBoundHandleOverlapped.CompletionLapped32*NativeOverlappedOverlapped* nativeOverlapped error*Overlapped. System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverla pped* pNativeOverlapped) — End of stack trace from previous location —

— End of inner exception stack trace — at System.Net.Security.SslStream.g__InternalFillHandshakeBufferAsync|187_0[TIOAdapter](TIOAdapter adap, ValueTask1 task, Int32 minSize) at System.Net.Security.SslStream.ReceiveBlobAsync[TIOAdapter](TIOAdapter adapter) at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm) at System.Net.Http.ConnectHelper.EstablishSslConnectionAsync(SslClientAuthenticationOptions sslOptions, HttpRequestMessage request, Boolean async, Stream stream, CancellationToken cancellationToken) at System.Net.Http.ConnectHelper.EstablishSslConnectionAsync(SslClientAuthenticationOptions sslOptions, HttpRequestMessage request, Boolean async, Stream stream, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.AddHttp11ConnectionAsync(HttpRequestMessage request) at System.Threading.Tasks.TaskCompletionSourceWithCancellation1.WaitWithCancellationAsync(CancellationToken cancellationToken) at System.Net.Http.HttpConnectionPool.GetHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationTokenan cancellationToken) at System.Net.Net.Http.Http.HttpConnectionRequestAsync(HttpRequestMessage request, Boolean async, CancellationTokenan cancellationToken) at System.Net.Http.Http.HttpConnectionRequestionSync. at System.Net.Http.DiagnosticsHandler.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken) at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage MicrosoftLocation request, Boolean async, CanttpExcellationHendler.Http)Logins at System.Net.Http.RedirectHandler. .SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Net.Prettp.Http.Reg__H0 CompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)

Leave a Comment