Solving the MessageSecurityException "The HTTP request is unauthorized" in service calls

Posted: (EET/GMT+2)

 

I was working on some SOAP protocol integration today for a new endpoint, and started developing C# code to call it. Everything went according to the plan, but during testing, I got the following error:

System.ServiceModel.Security.MessageSecurityException: The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Negotiate'. ---> System.Net.WebException: The remote server returned an error: (401) Unauthorized.

So clearly, it was a mismatch between my code and the authentication settings on the server. The missing piece we the way I had set the authentication settings. The crucial missing part was this line:

// set client credential type to Windows Authentication
httpsBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;

Here, I'm using the BasicHttpsBinding class to define the object httpsBinding, and then set the client credential type. After this, the credentials themselves can be set in the usual way:

// set the credentials
client.ClientCredentials.Windows.ClientCredential = new NetworkCredential("myuser", "mypwd", "domain");

With these settings in place, the call succeeded without any authentication problems.

Remember that you can configure these settings also in the application configuration file (usually app.config or web.config), but if you resort to code-based configuration, be sure to keep the actual credentials out of source control.