Search code examples
c#web-servicessap-pisap-xi

The HTTP request is unauthorized with client authentication scheme 'Ntlm' while calling SAP PI web service


I am currently creating a .NET C# service which uses webservice invoking to send information from CRM 2011 to SAP PI.

The credentials are said as following:

((BasicHttpBinding)defaultBinding).Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
((BasicHttpBinding)defaultBinding).Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; //.Ntlm;

PropertyInfo piClientCreds = type.GetProperty("ClientCredentials");
ClientCredentials creds = (ClientCredentials)piClientCreds.GetValue(obj, null);
PropertyInfo piWindowsCreds = creds.GetType().GetProperty("Windows");
WindowsClientCredential windowsCreds = (WindowsClientCredential)piWindowsCreds.GetValue(creds, null);
PropertyInfo piAllowNtlm = windowsCreds.GetType().GetProperty("AllowNtlm");
piAllowNtlm.SetValue(windowsCreds, true, null);
PropertyInfo piCredentials = windowsCreds.GetType().GetProperty("ClientCredential");
piCredentials.SetValue(windowsCreds, credentials, null);
PropertyInfo piImpersonation = windowsCreds.GetType().GetProperty("AllowedImpersonationLevel");
piImpersonation.SetValue(windowsCreds, System.Security.Principal.TokenImpersonationLevel.Impersonation, null);

The error I get is:

{System.ServiceModel.Security.MessageSecurityException: The HTTP request is
   unauthorized with client authentication scheme 'Ntlm'. The authentication header
   received from the server was 'Basic realm="Upload Protected Area"'.
---> System.Net.WebException: The remote server returned an error: (401) Unauthorized.
   at System.Net.HttpWebRequest.GetResponse()
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   --- End of inner exception stack trace ---

Any help in resolving this and if possible making it dynamic is much appreciated.

Thank you in advanced.


Solution

  • The problem is quite obvious. The server expects the your client to use Basic authentication while your client attempts to authenticate using NTLM. Try authenticating using UserNamePasswordClientCredential. You should do this only over a secure transport such as HTTPS.