sharepointoauthsharepoint-onlineazure-cloud-servicesacs

System.Net.Sockets.SocketException: 'An existing connection was forcibly closed by the remote host' with SharePoint Online low trust authentication


We are using Oauth to authenticate our cloud service in Azure using SharePoint online - https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/three-authorization-systems-for-sharepoint-add-ins#low-trust and we are getting this error - System.Net.Sockets.SocketException: 'An existing connection was forcibly closed by the remote host'

When trying clientContext.ExecuteQuery() code below.

Microsoft.SharePoint.Client.User spUser = null;
            try
            {
                using (clientContext)
                {
                    if (clientContext != null)
                    {
                        spUser = clientContext.Web.CurrentUser;

                        clientContext.Load(spUser);
                        clientContext.ExecuteQuery();

                        return spUser.LoginName.Split('|')[2];
                    }
                }
                return string.Empty;//no context = no id
            }

This is how SharePoint Context looks like

Any idea what this issue could be or how to troubleshoot this? Thanks


Solution

  • So adding this fixed the issue:

    using System.Net;
    using System.Security.Authentication;
    

    Add below code before clientContext.ExecuteQuery();

    const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
                const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
                ServicePointManager.SecurityProtocol = Tls12;
    

    The underlying issue seems to be that we are using .net framework 4.5 and we will have to upgrade this to latest version for this error to go.

    It's explained more here- Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

    Default SecurityProtocol in .NET 4.5